<?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();
require_role(['admin','production_manager']);
$user = current_user();
$page_title = 'Tasarım Admin Takibi';
$active_menu = 'design_admin';
$groupId = (int)($_GET['group_id'] ?? $_POST['group_id'] ?? 0);
$requestId = (int)($_GET['request_id'] ?? $_POST['request_id'] ?? 0);

function design_admin_redirect(int $groupId = 0, int $requestId = 0): void {
    if ($groupId > 0) redirect('design_admin.php?group_id='.$groupId);
    if ($requestId > 0) redirect('design_admin.php?request_id='.$requestId);
    redirect('design_admin.php');
}

if (is_post()) {
    verify_csrf();
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'group_selected') {
            $ids = $_POST['request_ids'] ?? [];
            if (!is_array($ids)) $ids = [];
            $groupId = design_group_create_or_attach_selected_requests($ids, $user);
            $_SESSION['flash']=['type'=>'success','msg'=>'Seçilen talepler çizim dosyasına bağlandı.'];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'create_single_file') {
            $requestId = (int)($_POST['request_id'] ?? 0);
            $groupId = design_group_create_or_attach_selected_requests([$requestId], $user);
            $_SESSION['flash']=['type'=>'success','msg'=>'Tekil çizim dosyası oluşturuldu.'];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'detach_member') {
            $groupId = (int)($_POST['group_id'] ?? 0);
            $requestId = (int)($_POST['request_id'] ?? 0);
            design_group_detach_request_v32($groupId, $requestId, $user, trim((string)($_POST['note'] ?? 'Admin çizim dosyasından çıkardı')));
            $_SESSION['flash']=['type'=>'success','msg'=>'Talep çizim dosyasından çıkarıldı.'];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'update_group') {
            $groupId = (int)($_POST['group_id'] ?? 0);
            $group = design_group_find_by_id($groupId);
            if (!$group) throw new RuntimeException('Çizim dosyası bulunamadı.');
            $createdProductId = (int)($_POST['created_product_id'] ?? 0);
            $sampleNo = trim((string)($group['sample_no'] ?? ''));
            if (trim((string)($_POST['sample_no'] ?? '')) !== '') $sampleNo = trim((string)$_POST['sample_no']);
            db()->prepare("UPDATE design_groups SET group_title=?, status=?, drawing_cost_actual_usd=?, sizing_cost_actual_usd=?, drawing_charge_total_usd=?, sizing_charge_total_usd=?, sample_no=?, sample_status=?, sample_note=?, created_product_id=?, admin_note=?, updated_at=NOW() WHERE id=?")->execute([
                trim((string)($_POST['group_title'] ?? $group['group_title'])),
                trim((string)($_POST['status'] ?? $group['status'])),
                design_parse_decimal($_POST['drawing_cost_actual_usd'] ?? null),
                design_parse_decimal($_POST['sizing_cost_actual_usd'] ?? null),
                design_parse_decimal($_POST['drawing_charge_total_usd'] ?? null),
                design_parse_decimal($_POST['sizing_charge_total_usd'] ?? null),
                $sampleNo !== '' ? $sampleNo : null,
                trim((string)($_POST['sample_status'] ?? '')) ?: null,
                trim((string)($_POST['sample_note'] ?? '')),
                $createdProductId > 0 ? $createdProductId : null,
                trim((string)($_POST['admin_note'] ?? '')),
                $groupId,
            ]);
            design_update_group_shares($groupId);
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizim dosyası güncellendi. Paylar yeniden hesaplandı.'];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'send_revision') {
            $groupId = (int)($_POST['group_id'] ?? 0);
            $revType = (string)($_POST['revision_type'] ?? 'admin');
            $note = trim((string)($_POST['revision_note'] ?? ''));
            if ($note === '') throw new RuntimeException('Revize notu zorunlu.');
            $newStatus = $revType === 'production' ? 'production_revision' : 'revision_requested';
            db()->prepare("UPDATE design_groups SET status=?, sample_status=IF(?='production_revision','production_revision',sample_status), revision_note=?, production_revision_note=?, updated_at=NOW() WHERE id=?")->execute([
                $newStatus,
                $newStatus,
                $revType === 'admin' ? $note : null,
                $revType === 'production' ? $note : null,
                $groupId,
            ]);
            foreach (design_group_members($groupId) as $m) {
                $old = (string)$m['request_status'];
                db()->prepare("UPDATE design_requests SET status=?, admin_note=?, revision_requested_at=IF(?='revision_requested', NOW(), revision_requested_at), production_revision_at=IF(?='production_revision', NOW(), production_revision_at), updated_at=NOW() WHERE id=?")->execute([$newStatus, $note, $newStatus, $newStatus, (int)$m['design_request_id']]);
                design_audit((int)$m['design_request_id'], $user['id'] ?? null, $revType === 'production' ? 'production_revision' : 'admin_revision', $old, $newStatus, $note);
            }
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizim dosyası çizimciye revize olarak döndürüldü.'];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'single_revision') {
            $requestId = (int)($_POST['request_id'] ?? 0);
            $revType = (string)($_POST['revision_type'] ?? 'admin');
            $note = trim((string)($_POST['revision_note'] ?? ''));
            if ($note === '') throw new RuntimeException('Revize notu zorunlu.');
            $req = design_find_by_id($requestId);
            if (!$req) throw new RuntimeException('Talep bulunamadı.');
            $newStatus = $revType === 'production' ? 'production_revision' : 'revision_requested';
            db()->prepare("UPDATE design_requests SET status=?, admin_note=?, revision_requested_at=IF(?='revision_requested', NOW(), revision_requested_at), production_revision_at=IF(?='production_revision', NOW(), production_revision_at), updated_at=NOW() WHERE id=?")->execute([$newStatus, $note, $newStatus, $newStatus, $requestId]);
            design_audit($requestId, $user['id'] ?? null, $revType === 'production' ? 'production_revision' : 'admin_revision', $req['status'], $newStatus, $note);
            $_SESSION['flash']=['type'=>'success','msg'=>'Talep çizimciye revize olarak döndürüldü.'];
            design_admin_redirect(0, $requestId);
        }

        if ($action === 'send_sample_queue') {
            $groupId = (int)($_POST['group_id'] ?? 0);
            $sampleNo = trim((string)($_POST['sample_no'] ?? ''));
            if ($sampleNo === '') $sampleNo = 'SM' . str_pad((string)$groupId, 6, '0', STR_PAD_LEFT);
            db()->prepare("UPDATE design_groups SET status='sample_queue', sample_no=?, sample_status='queued', updated_at=NOW() WHERE id=?")->execute([$sampleNo, $groupId]);
            foreach (design_group_members($groupId) as $m) {
                $old = (string)$m['request_status'];
                db()->prepare("UPDATE design_requests SET status='sample_queue', sample_no=?, sample_status='queued', updated_at=NOW() WHERE id=?")->execute([$sampleNo, (int)$m['design_request_id']]);
                design_audit((int)$m['design_request_id'], $user['id'] ?? null, 'sample_queue', $old, 'sample_queue', 'Admin numune üretim sırasına aldı: '.$sampleNo);
            }
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizim dosyası numune üretim sırasına alındı: '.$sampleNo];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'single_sample_queue') {
            $requestId = (int)($_POST['request_id'] ?? 0);
            $groupId = design_group_create_or_attach_selected_requests([$requestId], $user);
            $sampleNo = 'SM' . str_pad((string)$groupId, 6, '0', STR_PAD_LEFT);
            db()->prepare("UPDATE design_groups SET status='sample_queue', sample_no=?, sample_status='queued', updated_at=NOW() WHERE id=?")->execute([$sampleNo, $groupId]);
            foreach (design_group_members($groupId) as $m) {
                $old = (string)$m['request_status'];
                db()->prepare("UPDATE design_requests SET status='sample_queue', sample_no=?, sample_status='queued', updated_at=NOW() WHERE id=?")->execute([$sampleNo, (int)$m['design_request_id']]);
                design_audit((int)$m['design_request_id'], $user['id'] ?? null, 'sample_queue', $old, 'sample_queue', 'Admin numune üretim sırasına aldı: '.$sampleNo);
            }
            $_SESSION['flash']=['type'=>'success','msg'=>'Tekil çizim dosyası numune üretim sırasına alındı: '.$sampleNo];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'link_group_product') {
            $groupId = (int)($_POST['group_id'] ?? 0);
            $productId = (int)($_POST['created_product_id'] ?? 0);
            if ($productId <= 0) throw new RuntimeException('Ürün kartı seçilmedi.');
            db()->prepare("UPDATE design_groups SET status='product_created', sample_status='product_created', created_product_id=?, updated_at=NOW() WHERE id=?")->execute([$productId, $groupId]);
            foreach (design_group_members($groupId) as $m) {
                $old = (string)$m['request_status'];
                db()->prepare("UPDATE design_requests SET status='product_created', created_product_id=?, matched_product_id=?, product_linked_at=NOW(), updated_at=NOW() WHERE id=?")->execute([$productId, $productId, (int)$m['design_request_id']]);
                design_audit((int)$m['design_request_id'], $user['id'] ?? null, 'link_group_product', $old, 'product_created', 'Admin çizim dosyasını ürün kartına bağladı');
            }
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizim dosyası ürün kartına bağlandı.'];
            design_admin_redirect($groupId, 0);
        }

        if ($action === 'link_single_product') {
            $requestId = (int)($_POST['request_id'] ?? 0);
            $productId = (int)($_POST['created_product_id'] ?? 0);
            if ($requestId <= 0 || $productId <= 0) throw new RuntimeException('Talep veya ürün kartı seçilmedi.');
            $req = design_find_by_id($requestId);
            if (!$req) throw new RuntimeException('Talep bulunamadı.');
            db()->prepare("UPDATE design_requests SET status='product_created', created_product_id=?, matched_product_id=?, product_linked_at=NOW(), updated_at=NOW() WHERE id=?")->execute([$productId, $productId, $requestId]);
            design_audit($requestId, $user['id'] ?? null, 'link_single_product', $req['status'], 'product_created', 'Admin tek talebi mevcut ürün kartına bağladı');
            $_SESSION['flash']=['type'=>'success','msg'=>'Talep ürün kartına bağlandı.'];
            design_admin_redirect(0, $requestId);
        }

        if ($action === 'reject_single' || $action === 'cancel_single') {
            $requestId = (int)($_POST['request_id'] ?? 0);
            $note = trim((string)($_POST['reason'] ?? ''));
            if ($note === '') throw new RuntimeException('Sebep yazılmalı.');
            $req = design_find_by_id($requestId);
            if (!$req) throw new RuntimeException('Talep bulunamadı.');
            $new = $action === 'reject_single' ? 'rejected' : 'cancelled';
            if (!empty($req['design_group_id'])) {
                design_group_detach_request((int)$req['design_group_id'], $requestId, $user, 'Red/iptal nedeniyle çizim dosyasından çıkarıldı');
            }
            db()->prepare("UPDATE design_requests SET status=?, rejection_reason=?, admin_note=?, admin_decision_at=NOW(), updated_at=NOW() WHERE id=?")->execute([$new, $note, $note, $requestId]);
            design_audit($requestId, $user['id'] ?? null, $action, $req['status'], $new, $note);
            $_SESSION['flash']=['type'=>'success','msg'=>$new==='rejected'?'Talep reddedildi.':'Talep iptal edildi.'];
            design_admin_redirect(0, $requestId);
        }

        if ($action === 'reject_group') {
            $groupId = (int)($_POST['group_id'] ?? 0);
            $note = trim((string)($_POST['reason'] ?? ''));
            if ($note === '') throw new RuntimeException('Red sebebi yazılmalı.');
            db()->prepare("UPDATE design_groups SET status='rejected', admin_note=?, updated_at=NOW() WHERE id=?")->execute([$note, $groupId]);
            foreach (design_group_members($groupId) as $m) {
                $old = (string)$m['request_status'];
                db()->prepare("UPDATE design_requests SET status='rejected', rejection_reason=?, admin_note=?, admin_decision_at=NOW(), updated_at=NOW() WHERE id=?")->execute([$note, $note, (int)$m['design_request_id']]);
                design_audit((int)$m['design_request_id'], $user['id'] ?? null, 'reject_group', $old, 'rejected', $note);
            }
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizim dosyası reddedildi.'];
            design_admin_redirect($groupId, 0);
        }
    } catch (Throwable $e) {
        $_SESSION['flash']=['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
        design_admin_redirect($groupId, $requestId);
    }
}

$candidates = design_same_link_candidates();
$adminPending = design_requests_by_statuses(['design_completed','admin_review'], 300);
$adminRevision = design_requests_by_statuses(['revision_requested'], 300);
$productionRevision = design_requests_by_statuses(['production_revision'], 300);
$sampleTracking = design_groups_list(['statuses'=>['sample_queue']]);
$productCardWaiting = design_groups_by_sample_statuses(['produced']);
$closedRequests = design_requests_by_statuses(['rejected','cancelled'], 200);
$groups = design_groups_list();
$selectedGroup = $groupId > 0 ? design_group_find_by_id($groupId) : null;
$members = $selectedGroup ? design_group_members($groupId) : [];
$selectedRequest = $requestId > 0 ? design_find_by_id($requestId) : null;
$productOptions = design_product_search_options('');
$sampleStatusOptions = design_sample_status_options();
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Tasarım Admin Takibi</h1><p>Admin onayı, red/revize, numune üretim kararı ve ürün kartına bağlama burada yönetilir.</p></div><div style="display:flex;gap:10px"><a class="btn btn-secondary" href="design_queue.php">Tasarımcı Kuyruğu</a><a class="btn btn-secondary" href="design_requests.php">Tüm Talepler</a></div></div>

<div class="card"><div class="card-header"><span class="card-title">Aynı Link / Çizim Dosyası Adayları</span><span class="c-mt"><?= count($candidates) ?> aday</span></div><div class="card-body">
<?php if(!$candidates): ?><p class="c-mt">Çoklu link adayı yok.</p><?php endif; ?>
<?php foreach($candidates as $c): $candReqs = design_requests_by_source_url((string)$c['source_url']); ?>
  <form method="post" class="card" style="margin-bottom:12px" onsubmit="return confirm('Seçilen talepler aynı çizim dosyasına bağlansın mı? Tek seçim tekil çizim dosyası, birden çok seçim ortak çizim dosyası oluşturur.')">
    <?= csrf_field() ?><input type="hidden" name="action" value="group_selected">
    <div class="card-header"><span><a class="c-gold" href="<?= e($c['source_url']) ?>" target="_blank">Link</a> — <?= e($c['stores_text']) ?></span><span class="c-mt">Checkboxlar bilinçli seçilsin diye boş gelir.</span></div>
    <div class="table-wrap"><table><thead><tr><th>Seç</th><th>Talep</th><th>Mağaza</th><th>Durum</th><th>Çizim Dosyası</th><th>Talep Notu</th><th>İşlem</th></tr></thead><tbody>
    <?php foreach($candReqs as $r): ?><tr>
      <td><input type="checkbox" name="request_ids[]" value="<?= (int)$r['id'] ?>"></td>
      <td><strong><?= e($r['request_no'].' — '.$r['title']) ?></strong><div class="c-mt"><?= e(substr((string)$r['created_at'],0,16)) ?></div></td>
      <td><span class="badge"><?= e($r['store_code']) ?></span></td>
      <td><?= e(design_status_label($r['status'])) ?></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 style="max-width:420px"><?= nl2br(e(design_short_text((string)$r['request_note'], 220))) ?></td>
      <td><a class="btn btn-secondary" href="design_admin.php?request_id=<?= (int)$r['id'] ?>">Admin İncele</a></td>
    </tr><?php endforeach; ?>
    </tbody></table></div>
    <div style="padding:12px"><button class="btn btn-primary">Seçilenlerden Çizim Dosyası Oluştur / Bağla</button></div>
  </form>
<?php endforeach; ?>
</div></div>

<div class="grid" style="grid-template-columns:1fr 1fr;gap:16px">
  <div class="card"><div class="card-header"><span class="card-title">Admin Onayı Bekleyen Çizimler</span><span class="c-mt"><?= count($adminPending) ?> talep</span></div><div class="table-wrap"><table><thead><tr><th>Talep</th><th>Mağaza</th><th>Durum</th><th>Çizim Dosyası</th><th>İşlem</th></tr></thead><tbody><?php if(!$adminPending): ?><tr><td colspan="5" class="c-mt">Bekleyen admin onayı yok.</td></tr><?php endif; ?><?php foreach($adminPending as $r): ?><tr><td><strong><?= e($r['request_no'].' — '.$r['title']) ?></strong><div class="c-mt">Çizimci: <?= e($r['designer_name'] ?: '-') ?></div></td><td><?= e($r['store_code']) ?></td><td><?= e(design_status_label($r['status'])) ?></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><a class="btn btn-secondary" href="design_admin.php?request_id=<?= (int)$r['id'] ?>">Admin İncele</a></td></tr><?php endforeach; ?></tbody></table></div></div>

  <div class="card"><div class="card-header"><span class="card-title">Çizimciye Dönen Revizeler</span></div><div class="table-wrap"><table><thead><tr><th>Talep</th><th>Tip</th><th>Not</th><th>İşlem</th></tr></thead><tbody><?php if(!$adminRevision && !$productionRevision): ?><tr><td colspan="4" class="c-mt">Açık revize yok.</td></tr><?php endif; ?><?php foreach($adminRevision as $r): ?><tr><td><?= e($r['request_no'].' — '.$r['title']) ?></td><td><span class="badge badge-gold">Admin revizesi</span></td><td><?= e(design_short_text($r['admin_note'] ?? '', 120)) ?></td><td><a class="btn btn-secondary" href="design_admin.php?request_id=<?= (int)$r['id'] ?>">Takip</a></td></tr><?php endforeach; ?><?php foreach($productionRevision as $r): ?><tr><td><?= e($r['request_no'].' — '.$r['title']) ?></td><td><span class="badge badge-red">Üretim revizesi</span></td><td><?= e(design_short_text($r['admin_note'] ?? '', 120)) ?></td><td><a class="btn btn-secondary" href="design_admin.php?request_id=<?= (int)$r['id'] ?>">Takip</a></td></tr><?php endforeach; ?></tbody></table></div></div>
</div>

<div class="grid" style="grid-template-columns:1fr 1fr;gap:16px;margin-top:16px">
  <div class="card"><div class="card-header"><span class="card-title">Numune / Ürün Kartı Takibi</span></div><div class="table-wrap"><table><thead><tr><th>Çizim Dosyası</th><th>Mağazalar</th><th>Numune</th><th>Durum</th><th>İşlem</th></tr></thead><tbody><?php if(!$sampleTracking && !$productCardWaiting): ?><tr><td colspan="5" class="c-mt">Numune veya ürün kartı bekleyen dosya yok.</td></tr><?php endif; ?><?php foreach(array_merge($sampleTracking,$productCardWaiting) as $g): ?><tr><td><strong><?= e($g['group_no']) ?></strong><div class="c-mt"><?= e(design_file_kind_label((int)$g['member_count'])) ?></div></td><td><?= e($g['stores_text'] ?: '-') ?></td><td><?= e($g['sample_no'] ?: '-') ?></td><td><?= e(design_sample_status_label($g['sample_status'] ?? '')) ?></td><td><a class="btn btn-secondary" href="design_admin.php?group_id=<?= (int)$g['id'] ?>">Yönet</a></td></tr><?php endforeach; ?></tbody></table></div></div>

  <div class="card"><div class="card-header"><span class="card-title">Reddedilen / İptal Edilenler</span><span class="c-mt"><?= count($closedRequests) ?> kayıt</span></div><div class="table-wrap"><table><thead><tr><th>Talep</th><th>Mağaza</th><th>Durum</th><th>Sebep</th><th>İşlem</th></tr></thead><tbody><?php if(!$closedRequests): ?><tr><td colspan="5" class="c-mt">Red/iptal kaydı yok.</td></tr><?php endif; ?><?php foreach($closedRequests as $r): ?><tr><td><?= e($r['request_no'].' — '.$r['title']) ?></td><td><?= e($r['store_code']) ?></td><td><?= e(design_status_label($r['status'])) ?></td><td><?= e(design_short_text($r['rejection_reason'] ?: $r['admin_note'] ?: '', 100)) ?></td><td><a class="btn btn-secondary" href="design_admin.php?request_id=<?= (int)$r['id'] ?>">Aç</a></td></tr><?php endforeach; ?></tbody></table></div></div>
</div>

<div class="card" style="margin-top:16px"><div class="card-header"><span class="card-title">Çizim Dosyaları</span><span class="c-mt"><?= count($groups) ?> dosya</span></div><div class="table-wrap"><table><thead><tr><th>Dosya</th><th>Mağazalar</th><th>Durum</th><th>Numune</th><th>Pay</th><th>İşlem</th></tr></thead><tbody><?php if(!$groups): ?><tr><td colspan="6" class="c-mt">Çizim dosyası yok.</td></tr><?php endif; ?><?php foreach($groups as $g): ?><tr><td><strong><?= e($g['group_no']) ?></strong><div class="c-mt"><?= e($g['group_title']) ?><br><?= e(design_file_kind_label((int)$g['member_count'])) ?></div></td><td><?= e($g['stores_text'] ?: '-') ?><div class="c-mt"><?= (int)$g['member_count'] ?> talep</div></td><td><?= e(design_group_status_label($g['status'])) ?></td><td><?= e($g['sample_no'] ?: '-') ?><div class="c-mt"><?= e(design_sample_status_label($g['sample_status'] ?? '')) ?></div></td><td>Çizim: $<?= number_format((float)($g['drawing_charge_total_usd'] ?? 0),2) ?><br>Boylama: $<?= number_format((float)($g['sizing_charge_total_usd'] ?? 0),2) ?></td><td><a class="btn btn-secondary" href="design_admin.php?group_id=<?= (int)$g['id'] ?>">Yönet</a></td></tr><?php endforeach; ?></tbody></table></div></div>

<?php if($selectedRequest): ?>
<div class="card" style="margin-top:16px"><div class="card-header"><span class="card-title"><?= e($selectedRequest['request_no']) ?> — Admin Talep İnceleme</span><span class="c-mt"><?= e($selectedRequest['store_code']) ?> / <?= e(design_status_label($selectedRequest['status'])) ?></span></div><div class="card-body">
  <div class="grid" style="grid-template-columns:220px 1fr;gap:16px">
    <div><?php if($selectedRequest['reference_image_path']): ?><img src="<?= e($selectedRequest['reference_image_path']) ?>" style="width:200px;height:200px;object-fit:contain;border-radius:12px;border:1px solid var(--border)"><?php endif; ?><?php if($selectedRequest['source_url']): ?><p><a class="btn btn-secondary" href="<?= e($selectedRequest['source_url']) ?>" target="_blank">Kaynak Linki Aç</a></p><?php endif; ?></div>
    <div>
      <p><strong>Mağaza talep notu:</strong><br><?= nl2br(e($selectedRequest['request_note'] ?: '-')) ?></p>
      <p><strong>Çizimci taş/slot notu:</strong><br><?= nl2br(e($selectedRequest['stone_slot_note'] ?: '-')) ?></p>
      <p><strong>Çizimci notu:</strong><br><?= nl2br(e($selectedRequest['designer_note'] ?: '-')) ?></p>
      <div class="table-wrap"><table><thead><tr><th>Genişlik</th><th>Uzunluk</th><th>Yükseklik</th><th>Band</th><th>10K</th><th>14K</th><th>18K</th><th>Çizim $</th><th>Boylama $</th></tr></thead><tbody><tr><td><?= e($selectedRequest['width_mm'] ?: '-') ?></td><td><?= e($selectedRequest['length_mm'] ?: '-') ?></td><td><?= e($selectedRequest['height_mm'] ?: '-') ?></td><td><?= e($selectedRequest['band_width_mm'] ?: '-') ?></td><td><?= e($selectedRequest['gram_10k'] ?: '-') ?></td><td><?= e($selectedRequest['gram_14k'] ?: '-') ?></td><td><?= e($selectedRequest['gram_18k'] ?: '-') ?></td><td><?= e($selectedRequest['drawing_cost_actual_usd'] ?: '-') ?></td><td><?= e($selectedRequest['sizing_cost_actual_usd'] ?: '-') ?></td></tr></tbody></table></div>
      <p style="margin-top:10px"><strong>Çizim dosyası:</strong> <?= design_file_badge_html($selectedRequest['group_no'] ?? null, isset($selectedRequest['group_member_count']) ? (int)$selectedRequest['group_member_count'] : null, $selectedRequest['group_status'] ?? null) ?></p>
    </div>
  </div>
  <div class="grid" style="grid-template-columns:1fr 1fr;gap:16px;margin-top:16px">
    <div class="card"><div class="card-header"><span class="card-title">Admin Kararları</span></div><div class="card-body">
      <?php if(empty($selectedRequest['design_group_id'])): ?><form method="post" style="margin-bottom:10px"><?= csrf_field() ?><input type="hidden" name="action" value="create_single_file"><input type="hidden" name="request_id" value="<?= (int)$selectedRequest['id'] ?>"><button class="btn btn-primary">Tekil Çizim Dosyası Oluştur</button></form><?php endif; ?>
      <form method="post" style="margin-bottom:10px" onsubmit="return confirm('Bu talep numune üretim sırasına alınacak. Emin misin?')"><?= csrf_field() ?><input type="hidden" name="action" value="single_sample_queue"><input type="hidden" name="request_id" value="<?= (int)$selectedRequest['id'] ?>"><button class="btn btn-secondary">Numune Üretim Sırasına Al</button></form>
      <form method="post" style="display:flex;gap:8px;align-items:end;flex-wrap:wrap;margin-bottom:10px"><?= csrf_field() ?><input type="hidden" name="action" value="link_single_product"><input type="hidden" name="request_id" value="<?= (int)$selectedRequest['id'] ?>"><select class="form-control" name="created_product_id" style="max-width:360px"><option value="0">Mevcut ürün kartı seç</option><?php foreach($productOptions as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['master_code'].' — '.$p['product_name']) ?></option><?php endforeach; ?></select><button class="btn btn-secondary">Ürün Kartına Bağla</button></form>
      <form method="post" style="margin-bottom:10px"><?= csrf_field() ?><input type="hidden" name="action" value="single_revision"><input type="hidden" name="request_id" value="<?= (int)$selectedRequest['id'] ?>"><input type="hidden" name="revision_type" value="admin"><textarea class="form-control" name="revision_note" rows="2" placeholder="Admin revize sebebi"></textarea><button class="btn btn-danger" style="margin-top:8px">Admin Revizesi Olarak Çizimciye Gönder</button></form>
      <form method="post" style="margin-bottom:10px"><?= csrf_field() ?><input type="hidden" name="action" value="single_revision"><input type="hidden" name="request_id" value="<?= (int)$selectedRequest['id'] ?>"><input type="hidden" name="revision_type" value="production"><textarea class="form-control" name="revision_note" rows="2" placeholder="Üretim revize sebebi"></textarea><button class="btn btn-danger" style="margin-top:8px">Üretimden Revize Olarak Çizimciye Gönder</button></form>
      <form method="post" style="margin-bottom:10px" onsubmit="return confirm('Talep reddedilecek. Emin misin?')"><?= csrf_field() ?><input type="hidden" name="action" value="reject_single"><input type="hidden" name="request_id" value="<?= (int)$selectedRequest['id'] ?>"><input class="form-control" name="reason" placeholder="Red sebebi"><button class="btn btn-danger" style="margin-top:8px">Talebi Reddet</button></form>
    </div></div>
    <div class="card"><div class="card-header"><span class="card-title">İşlem Geçmişi</span></div><div class="table-wrap"><table><thead><tr><th>Tarih</th><th>İşlem</th><th>Durum</th><th>Not</th></tr></thead><tbody><?php foreach(design_audit_rows((int)$selectedRequest['id']) as $a): ?><tr><td><?= e(substr((string)$a['created_at'],0,16)) ?></td><td><?= e(design_audit_action_label($a['action_type'])) ?></td><td><?= e(($a['old_status'] ?: '-').' → '.($a['new_status'] ?: '-')) ?></td><td><?= e($a['note']) ?></td></tr><?php endforeach; ?></tbody></table></div></div>
  </div>
</div></div>
<?php endif; ?>

<?php if($selectedGroup): ?>
<div class="card" style="margin-top:16px"><div class="card-header"><span class="card-title"><?= e($selectedGroup['group_no']) ?> — Çizim Dosyası Yönetimi</span><span class="c-mt"><?= e(design_file_kind_label((int)$selectedGroup['member_count'])) ?> / satış bedelleri mağaza sayısına bölünür.</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="update_group"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>">
<div style="grid-column:span 2"><label class="form-label">Çizim Dosyası Başlığı</label><input class="form-control" name="group_title" value="<?= e($selectedGroup['group_title']) ?>"></div>
<div><label class="form-label">Durum</label><select class="form-control" name="status"><?php foreach(['open','admin_review','revision_requested','production_revision','sample_queue','product_created','closed','cancelled','rejected'] as $st): ?><option value="<?= e($st) ?>" <?= $selectedGroup['status']===$st?'selected':'' ?>><?= e(design_group_status_label($st)) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Numune No</label><input class="form-control" name="sample_no" value="<?= e($selectedGroup['sample_no']) ?>" placeholder="Üretim sırasına alınca oluşur"></div>
<div><label class="form-label">Çizim gerçek maliyet $</label><input class="form-control" name="drawing_cost_actual_usd" value="<?= e($selectedGroup['drawing_cost_actual_usd']) ?>"></div>
<div><label class="form-label">Boylama gerçek maliyet $</label><input class="form-control" name="sizing_cost_actual_usd" value="<?= e($selectedGroup['sizing_cost_actual_usd']) ?>"></div>
<div><label class="form-label">Mağazaya çizim satış $</label><input class="form-control" name="drawing_charge_total_usd" value="<?= e($selectedGroup['drawing_charge_total_usd']) ?>"></div>
<div><label class="form-label">Mağazaya boylama satış $</label><input class="form-control" name="sizing_charge_total_usd" value="<?= e($selectedGroup['sizing_charge_total_usd']) ?>"></div>
<div><label class="form-label">Numune Durumu</label><select class="form-control" name="sample_status"><?php foreach($sampleStatusOptions as $k=>$v): ?><option value="<?= e($k) ?>" <?= ($selectedGroup['sample_status'] ?? '')===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Ürün Kartına Bağla</label><select class="form-control" name="created_product_id"><option value="0">Henüz yok</option><?php foreach($productOptions as $p): ?><option value="<?= (int)$p['id'] ?>" <?= (int)($selectedGroup['created_product_id'] ?? 0)===(int)$p['id']?'selected':'' ?>><?= e($p['master_code'].' — '.$p['product_name']) ?></option><?php endforeach; ?></select></div>
<div style="grid-column:span 2"><label class="form-label">Numune Notu</label><input class="form-control" name="sample_note" value="<?= e($selectedGroup['sample_note']) ?>"></div>
<div style="grid-column:span 4"><label class="form-label">Admin Notu</label><textarea class="form-control" name="admin_note" rows="3"><?= e($selectedGroup['admin_note']) ?></textarea></div>
<div><button class="btn btn-primary">Çizim Dosyasını Güncelle</button></div>
</form>
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:12px">
  <form method="post" onsubmit="return confirm('Numune üretim sırasına alınsın mı?')"><?= csrf_field() ?><input type="hidden" name="action" value="send_sample_queue"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>"><input type="hidden" name="sample_no" value="<?= e($selectedGroup['sample_no']) ?>"><button class="btn btn-secondary">Numune Üretim Sırasına Al</button></form>
  <form method="post" style="display:flex;gap:8px;align-items:center"><?= csrf_field() ?><input type="hidden" name="action" value="link_group_product"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>"><select class="form-control" name="created_product_id"><option value="0">Ürün seç</option><?php foreach($productOptions as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['master_code'].' — '.$p['product_name']) ?></option><?php endforeach; ?></select><button class="btn btn-secondary">Ürün Kartına Bağla</button></form>
</div>
<div class="grid" style="grid-template-columns:1fr 1fr;gap:16px;margin-top:14px">
<form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="send_revision"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>"><input type="hidden" name="revision_type" value="admin"><label class="form-label">Admin revize notu</label><textarea class="form-control" name="revision_note" rows="3" placeholder="Admin onayında fark edilen revize/değişiklik"></textarea><button class="btn btn-danger" style="margin-top:8px">Admin Revizesi Olarak Çizimciye Geri Gönder</button></form>
<form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="send_revision"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>"><input type="hidden" name="revision_type" value="production"><label class="form-label">Üretim revize notu</label><textarea class="form-control" name="revision_note" rows="3" placeholder="Örn: tırnak taşı tutmuyor, kalınlık yetersiz..."></textarea><button class="btn btn-danger" style="margin-top:8px">Üretimden Revize Olarak Çizimciye Geri Gönder</button></form>
</div>
<form method="post" style="margin-top:14px" onsubmit="return confirm('Bu çizim dosyası reddedilecek. Emin misin?')"><?= csrf_field() ?><input type="hidden" name="action" value="reject_group"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>"><input class="form-control" name="reason" placeholder="Red sebebi"><button class="btn btn-danger" style="margin-top:8px">Çizim Dosyasını Reddet</button></form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Bağlı Mağazalar ve Paylar</span><span class="c-mt">Aynı link her zaman aynı ürün demek değildir; yanlış bağlanan talebi çıkar.</span></div><div class="table-wrap"><table><thead><tr><th>Talep</th><th>Mağaza</th><th>Talep Notu</th><th>Çizim Bilgisi</th><th>Durum</th><th>Çizim Payı</th><th>Boylama Payı</th><th>İşlem</th></tr></thead><tbody><?php if(!$members): ?><tr><td colspan="8" class="c-mt">Bağlı talep yok.</td></tr><?php endif; ?><?php foreach($members as $m): ?><tr><td><strong><?= e($m['request_no'].' — '.$m['title']) ?></strong><div class="c-mt"><?= e(substr((string)$m['request_created_at'],0,16)) ?></div></td><td><span class="badge"><?= e($m['store_code']) ?></span></td><td style="max-width:260px"><?= nl2br(e(design_short_text($m['request_note'],160))) ?></td><td style="max-width:320px"><?= design_group_request_summary_card($m) ?><?php if($m['stone_slot_note']): ?><div class="c-mt">Taş notu: <?= e(design_short_text($m['stone_slot_note'],120)) ?></div><?php endif; ?></td><td><?= e(design_status_label($m['request_status'])) ?></td><td><?= $m['share_drawing_usd']!==null ? '$'.number_format((float)$m['share_drawing_usd'],2) : '-' ?></td><td><?= $m['share_sizing_usd']!==null ? '$'.number_format((float)$m['share_sizing_usd'],2) : '-' ?></td><td><a class="btn btn-secondary" href="design_admin.php?request_id=<?= (int)$m['design_request_id'] ?>">Talep</a><form method="post" style="display:inline" onsubmit="return confirm('Bu talep çizim dosyasından çıkarılsın mı?')"><?= csrf_field() ?><input type="hidden" name="action" value="detach_member"><input type="hidden" name="group_id" value="<?= (int)$selectedGroup['id'] ?>"><input type="hidden" name="request_id" value="<?= (int)$m['design_request_id'] ?>"><button class="btn btn-danger">Çıkar</button></form></td></tr><?php endforeach; ?></tbody></table></div></div>
<?php endif; ?>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
