<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/product_core_common.php';
require_once __DIR__ . '/design_core_common.php';
require_login();
$user = current_user();
$role = (string)($user['role'] ?? '');
if (!in_array($role, ['admin','production_manager','store_user','workshop_staff','designer'], true)) {
    require_role(['admin','production_manager','store_user']);
}
$page_title = 'Tasarım Talepleri';
$active_menu = 'design_requests';
$stores = design_stores();
$types = design_product_type_options();
$statusOptions = design_status_options();
$designers = design_users_for_designer();

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'create_request') {
            $title = trim((string)($_POST['title'] ?? ''));
            if ($title === '') throw new RuntimeException('Talep adı/kısa açıklama zorunlu.');
            $storeId = $role === 'store_user' ? (int)($user['store_id'] ?? 0) : (int)($_POST['store_id'] ?? 0);
            if ($storeId <= 0) throw new RuntimeException('Mağaza seçilmedi.');
            $requestNo = design_next_request_no();
            $imagePath = design_handle_image_upload($requestNo, $_FILES['reference_image'] ?? []);
            $sourceUrl = trim((string)($_POST['source_url'] ?? ''));
            $matched = design_find_existing_product_by_url($sourceUrl);
            $stmt = db()->prepare("INSERT INTO design_requests (request_no, store_id, requested_by, title, source_url, reference_image_path, request_note, status, product_type_code, matched_product_id, submitted_at) VALUES (?,?,?,?,?,?,?,?,?,?,NOW())");
            $stmt->execute([$requestNo,$storeId,$user['id'] ?? null,$title,$sourceUrl,$imagePath,trim((string)($_POST['request_note'] ?? '')),'submitted',trim((string)($_POST['product_type_code'] ?? '')) ?: null,$matched['id'] ?? null]);
            $id = (int)db()->lastInsertId();
            design_audit($id, $user['id'] ?? null, 'create_request', null, 'submitted', 'Yeni tasarım talebi oluşturuldu');
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Tasarım talebi oluşturuldu: '.$requestNo];
            redirect('design_request_detail.php?id='.$id);
        }
    } catch (Throwable $e) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('design_requests.php');
}

$q = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));
$storeId = (int)($_GET['store_id'] ?? 0);
$productType = trim((string)($_GET['product_type_code'] ?? ''));
$designerId = (int)($_GET['designer_user_id'] ?? 0);
$sameLink = !empty($_GET['same_link']);
$sort = trim((string)($_GET['sort'] ?? 'oldest'));
[$sql, $params] = design_request_list_sql($user, ['q'=>$q, 'status'=>$status, 'store_id'=>$storeId, 'product_type_code'=>$productType, 'designer_user_id'=>$designerId, 'same_link'=>$sameLink, 'sort'=>$sort]);
$stmt = db()->prepare($sql); $stmt->execute($params); $rows = $stmt->fetchAll();

include __DIR__ . '/includes/layout.php';
?>
<div class="ph">
  <div><h1>Tasarım Talepleri</h1><p>Mağazalar yeni çizim/numune taleplerini açar. Liste varsayılan olarak en eski talep üstte olacak şekilde sıralanır.</p></div>
  <div style="display:flex;gap:10px">
    <?php if (in_array($role, ['admin','production_manager','workshop_staff','designer'], true)): ?>
      <a class="btn btn-secondary" href="design_queue.php">Tasarım Kuyruğu</a>
      <a class="btn btn-secondary" href="design_admin.php">Tasarım Admin Takibi</a>
    <?php endif; ?>
    <a class="btn btn-secondary" href="products.php">Ürün Kartları</a>
  </div>
</div>

<div class="card"><div class="card-header"><span class="card-title">Yeni Tasarım Talebi Aç</span></div><div class="card-body">
<form method="post" enctype="multipart/form-data" style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;align-items:end" onsubmit="const f=this.querySelector('input[type=file]'); if(f && f.files[0] && f.files[0].size>2*1024*1024){alert('Görsel 2 MB üstü. Lütfen küçültüp tekrar yükleyin.'); return false;} return true;">
<?= csrf_field() ?><input type="hidden" name="action" value="create_request">
<?php if ($role !== 'store_user'): ?>
<div><label class="form-label">Mağaza</label><select class="form-control" name="store_id" required><option value="">Seç</option><?php foreach($stores as $s): ?><option value="<?= (int)$s['id'] ?>"><?= e($s['store_code'].' — '.$s['store_name']) ?></option><?php endforeach; ?></select></div>
<?php endif; ?>
<div><label class="form-label">Ürün Tipi</label><select class="form-control" name="product_type_code"><option value="">Şimdilik bilinmiyor</option><?php foreach($types as $k=>$t): ?><option value="<?= e($k) ?>"><?= e($t['label']) ?> — <?= e($t['letter']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Talep Adı</label><input class="form-control" name="title" placeholder="Markiz yüzük / yeni alyans" required></div>
<div style="grid-column:span 2"><label class="form-label">Kaynak Link</label><input class="form-control" name="source_url" placeholder="Etsy / web linki"></div>
<div><label class="form-label">Referans Foto</label><input class="form-control" type="file" name="reference_image" accept="image/*"></div>
<div style="grid-column:span 5"><label class="form-label">Tasarım Notu</label><textarea class="form-control" name="request_note" rows="3" placeholder="Taşı şöyle olsun, ölçüsü şöyle olsun, değiştirilecek detaylar..."></textarea></div>
<div><button class="btn btn-primary" type="submit">Talebi Oluştur</button></div>
</form>
<div class="flash flash-info" style="margin-top:14px">Aynı kaynak link daha önce kullanıldıysa hem listede hem detayda uyarı verir. Görsel maksimum 2 MB olmalı.</div>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Filtrele / Sırala</span></div><div class="card-body">
<form method="get" style="display:grid;grid-template-columns:2fr 1fr 1fr 1fr 1fr 1fr auto auto;gap:12px;align-items:end">
<div><label class="form-label">Arama</label><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="DR no / ürün / link / mağaza / çizim dosyası"></div>
<div><label class="form-label">Durum</label><select class="form-control" name="status"><option value="">Tümü</option><?php foreach($statusOptions as $k=>$v): ?><option value="<?= e($k) ?>" <?= $status===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
<?php if($role !== 'store_user'): ?><div><label class="form-label">Mağaza</label><select class="form-control" name="store_id"><option value="0">Tümü</option><?php foreach($stores as $s): ?><option value="<?= (int)$s['id'] ?>" <?= $storeId===(int)$s['id']?'selected':'' ?>><?= e($s['store_code']) ?></option><?php endforeach; ?></select></div><?php endif; ?>
<div><label class="form-label">Tip</label><select class="form-control" name="product_type_code"><option value="">Tümü</option><?php foreach($types as $k=>$t): ?><option value="<?= e($k) ?>" <?= $productType===$k?'selected':'' ?>><?= e($t['label']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Çizimci</label><select class="form-control" name="designer_user_id"><option value="0">Tümü</option><?php foreach($designers as $d): ?><option value="<?= (int)$d['id'] ?>" <?= $designerId===(int)$d['id']?'selected':'' ?>><?= e($d['full_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Sırala</label><select class="form-control" name="sort"><option value="oldest" <?= $sort==='oldest'?'selected':'' ?>>En eski üstte</option><option value="newest" <?= $sort==='newest'?'selected':'' ?>>En yeni üstte</option><option value="request_no" <?= $sort==='request_no'?'selected':'' ?>>Talep no</option><option value="store" <?= $sort==='store'?'selected':'' ?>>Mağaza</option><option value="status" <?= $sort==='status'?'selected':'' ?>>Durum</option><option value="type" <?= $sort==='type'?'selected':'' ?>>Ürün tipi</option><option value="designer" <?= $sort==='designer'?'selected':'' ?>>Çizimci</option></select></div>
<div><label style="display:block;padding:11px 0"><input type="checkbox" name="same_link" value="1" <?= $sameLink?'checked':'' ?>> Çoklu link</label></div>
<div><button class="btn btn-secondary" type="submit">Ara</button></div><div><a class="btn btn-secondary" href="design_requests.php">Temizle</a></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Talep Listesi</span><span class="c-mt"><?= count($rows) ?> kayıt gösteriliyor</span></div><div class="table-wrap"><table><thead><tr><th>Görsel</th><th>No</th><th>Mağaza</th><th>Talep</th><th>Tip</th><th>Durum</th><th>Çoklu Talep</th><th>Çizim Dosyası</th><th>Tarih</th><th>Çizimci</th><th>İşlem</th></tr></thead><tbody>
<?php if (!$rows): ?><tr><td colspan="11" class="c-mt">Henüz tasarım talebi yok.</td></tr><?php endif; ?>
<?php foreach($rows as $r): $sameCnt=(int)($r['same_url_count'] ?? 0); $storesText = $sameCnt>1 ? design_same_link_store_summary((string)$r['source_url']) : ''; ?>
<tr>
<td><?php if($r['reference_image_path']): ?><img src="<?= e($r['reference_image_path']) ?>" style="width:54px;height:54px;object-fit:cover;border-radius:8px;border:1px solid var(--border)"><?php else: ?><span class="c-mt">-</span><?php endif; ?></td>
<td><strong><?= e($r['request_no']) ?></strong></td>
<td><span class="badge"><?= e($r['store_code']) ?></span></td>
<td><div><strong><?= e($r['title']) ?></strong></div><?php if($r['source_url']): ?><div class="c-mt" style="max-width:360px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= e($r['source_url']) ?></div><?php endif; ?></td>
<td><?= e(design_product_type_label($r['product_type_code'])) ?></td>
<td><span class="<?= e(design_status_badge_class($r['status'])) ?>"><?= e(design_status_label($r['status'])) ?></span></td>
<td><?php if($sameCnt>1): ?><span class="badge badge-gold">Aynı link: <?= $sameCnt ?> mağaza</span><div class="c-mt"><?= e($storesText) ?></div><?php else: ?><span class="c-mt">-</span><?php endif; ?></td>
<td><?= design_file_badge_html($r['group_no'] ?? null, isset($r['group_member_count']) ? (int)$r['group_member_count'] : null, $r['group_status'] ?? null) ?></td>
<td><?= e(substr((string)$r['created_at'],0,16)) ?></td>
<td><?= e($r['designer_name'] ?: '-') ?></td>
<td><a class="btn btn-secondary" href="design_request_detail.php?id=<?= (int)$r['id'] ?>">Detay</a></td>
</tr>
<?php endforeach; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
