<?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'] ?? '');
$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($id <= 0) { $_SESSION['flash']=['type'=>'error','msg'=>'Tasarım talebi bulunamadı.']; redirect('design_requests.php'); }
$req = design_find_by_id($id);
if (!$req) { $_SESSION['flash']=['type'=>'error','msg'=>'Tasarım talebi bulunamadı.']; redirect('design_requests.php'); }
if (!design_current_user_can_view($req, $user)) { $_SESSION['flash']=['type'=>'error','msg'=>'Bu talebi görme yetkin yok.']; redirect('design_requests.php'); }
$canWork = in_array($role, ['admin','production_manager','workshop_staff','designer'], true);
$canAdmin = in_array($role, ['admin','production_manager'], true);
$page_title = 'Tasarım Talebi';
$active_menu = $canWork ? 'design_queue' : 'design_requests';
$types = design_product_type_options();
$designers = design_users_for_designer();
$editableStatuses = ['submitted','designer_review','in_design','revision_requested','production_revision'];
$canEditDrawing = $canWork && in_array((string)$req['status'], $editableStatuses, true);

if (is_post()) {
    verify_csrf();
    $action = (string)($_POST['action'] ?? '');
    try {
        $req = design_find_by_id($id);
        if (!$req) throw new RuntimeException('Talep bulunamadı.');

        if ($action === 'store_cancel' && $role === 'store_user') {
            if ((int)$req['store_id'] !== (int)($user['store_id'] ?? 0)) throw new RuntimeException('Yetkin yok.');
            if (!in_array($req['status'], ['submitted','designer_review'], true)) throw new RuntimeException('Bu aşamada mağaza iptali kapalı.');
            db()->prepare("UPDATE design_requests SET status='cancelled', rejection_reason=?, updated_at=NOW() WHERE id=?")->execute([trim((string)($_POST['reason'] ?? 'Mağaza iptali')), $id]);
            design_audit($id, $user['id'] ?? null, 'store_cancel', $req['status'], 'cancelled', $_POST['reason'] ?? '');
            $_SESSION['flash']=['type'=>'success','msg'=>'Talep iptal edildi.'];
        }

        if ($action === 'save_designer' && $canWork) {
            if (!in_array((string)$req['status'], $editableStatuses, true)) throw new RuntimeException('Bu talep artık admin onayında/kapanmış; çizim bilgisi değiştirilemez.');
            $designerId = $canAdmin ? (int)($_POST['designer_user_id'] ?? 0) : (int)($req['designer_user_id'] ?: ($user['id'] ?? 0));
            if ($designerId <= 0 && in_array($role, ['designer','workshop_staff'], true)) $designerId = (int)($user['id'] ?? 0);
            design_update_request_work_fields($id, [
                'title' => trim((string)($_POST['title'] ?? $req['title'])),
                'product_type_code' => trim((string)($_POST['product_type_code'] ?? '')) ?: null,
                'designer_user_id' => $designerId > 0 ? $designerId : null,
                'designer_note' => trim((string)($_POST['designer_note'] ?? '')),
                'drawing_cost_actual_usd' => design_parse_decimal($_POST['drawing_cost_actual_usd'] ?? null),
                'sizing_cost_actual_usd' => design_parse_decimal($_POST['sizing_cost_actual_usd'] ?? null),
                'width_mm' => design_parse_decimal($_POST['width_mm'] ?? null),
                'length_mm' => design_parse_decimal($_POST['length_mm'] ?? null),
                'height_mm' => design_parse_decimal($_POST['height_mm'] ?? null),
                'band_width_mm' => design_parse_decimal($_POST['band_width_mm'] ?? null),
                'gram_10k' => design_parse_decimal($_POST['gram_10k'] ?? null),
                'gram_14k' => design_parse_decimal($_POST['gram_14k'] ?? null),
                'gram_18k' => design_parse_decimal($_POST['gram_18k'] ?? null),
                'stone_slot_note' => trim((string)($_POST['stone_slot_note'] ?? '')),
                'is_sizing_required' => !empty($_POST['is_sizing_required']) ? 1 : 0,
            ], $user);
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizim bilgileri kaydedildi.'];
        }

        if ($action === 'take_review' && $canWork) {
            if (!in_array((string)$req['status'], ['submitted'], true)) throw new RuntimeException('Bu talep bu aşamada incelemeye alınamaz.');
            db()->prepare("UPDATE design_requests SET designer_user_id=COALESCE(designer_user_id, ?), status='designer_review', updated_at=NOW() WHERE id=?")->execute([$user['id'] ?? null, $id]);
            design_audit($id, $user['id'] ?? null, 'take_review', $req['status'], 'designer_review', 'Çizimci incelemeye aldı');
            $_SESSION['flash']=['type'=>'success','msg'=>'Talep incelemeye alındı.'];
        }

        if ($action === 'start_design' && $canWork) {
            if (!in_array((string)$req['status'], ['submitted','designer_review','revision_requested','production_revision'], true)) throw new RuntimeException('Bu talep bu aşamada çizime başlatılamaz.');
            db()->prepare("UPDATE design_requests SET designer_user_id=COALESCE(designer_user_id, ?), status='in_design', design_started_at=COALESCE(design_started_at, NOW()), updated_at=NOW() WHERE id=?")->execute([$user['id'] ?? null, $id]);
            design_audit($id, $user['id'] ?? null, 'start_design', $req['status'], 'in_design', 'Çizime başlandı');
            $_SESSION['flash']=['type'=>'success','msg'=>'Çizime başlandı olarak işaretlendi.'];
        }

        if ($action === 'send_admin' && $canWork) {
            if (!in_array((string)$req['status'], ['in_design','revision_requested','production_revision'], true)) throw new RuntimeException('Bu talep zaten admin onayında ya da çizime başlanmamış.');
            $note = trim((string)($_POST['send_note'] ?? 'Çizimci admin onayına gönderdi'));
            db()->prepare("UPDATE design_requests SET status='design_completed', design_completed_at=NOW(), updated_at=NOW() WHERE id=?")->execute([$id]);
            design_audit($id, $user['id'] ?? null, 'send_admin', $req['status'], 'design_completed', $note);
            $_SESSION['flash']=['type'=>'success','msg'=>'Talep admin onayına gönderildi. Artık Admine Gönderilenler sekmesinde görünür.'];
        }
    } catch (Throwable $e) {
        $_SESSION['flash']=['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('design_request_detail.php?id='.$id);
}

$req = design_find_by_id($id);
$dups = design_duplicate_requests((string)$req['source_url'], $id);
$existing = design_find_existing_product_by_url((string)$req['source_url']);
$audit = design_audit_rows($id);
$group = design_group_for_request($id);
$groupMembers = $group ? design_group_members((int)$group['id']) : [];
$canEditDrawing = $canWork && in_array((string)$req['status'], $editableStatuses, true);
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1><?= e($req['request_no']) ?> — Tasarım Talebi</h1><p><span class="badge"><?= e($req['store_code']) ?></span> <?= e($req['title']) ?> <?php if($group): ?><?= design_file_badge_html($group['group_no'] ?? null, isset($group['member_count']) ? (int)$group['member_count'] : null, $group['status'] ?? null) ?><?php endif; ?></p></div><div style="display:flex;gap:10px"><a class="btn btn-secondary" href="<?= $canWork ? 'design_queue.php' : 'design_requests.php' ?>">Listeye Dön</a><?php if($canAdmin): ?><a class="btn btn-secondary" href="design_admin.php">Tasarım Admin Takibi</a><?php endif; ?></div></div>

<?php if($existing): ?><div class="flash flash-info">Bu kaynak link ürün kartında mevcut görünüyor: <strong><?= e($existing['master_code']) ?></strong> — <?= e($existing['short_name'] ?: $existing['product_name']) ?>. Çizimci bunu admin’e bildirebilir; ürüne bağlama işlemini admin yapar.</div><?php endif; ?>
<?php if($dups): ?><div class="flash flash-info">Aynı kaynak link başka <?= count($dups) ?> talepte de var. Çizim dosyası bağlama/çıkarma işlemi sadece admin ekranındadır.</div><?php endif; ?>

<div class="grid" style="grid-template-columns:1fr 2fr;gap:16px">
  <div class="card"><div class="card-header"><span class="card-title">Referans</span></div><div class="card-body">
    <?php if($req['reference_image_path']): ?><img src="<?= e($req['reference_image_path']) ?>" style="width:100%;max-height:360px;object-fit:contain;border-radius:12px;border:1px solid var(--border)"><?php else: ?><div class="c-mt">Görsel yok.</div><?php endif; ?>
    <?php if($req['source_url']): ?><p style="margin-top:12px"><a class="btn btn-secondary" href="<?= e($req['source_url']) ?>" target="_blank" rel="noopener">Kaynak Linki Aç</a></p><?php endif; ?>
    <p><strong>Durum:</strong> <span class="<?= e(design_status_badge_class($req['status'])) ?>"><?= e(design_status_label($req['status'])) ?></span></p>
    <p><strong>Talep eden:</strong> <?= e($req['requested_by_name'] ?: '-') ?></p>
    <p><strong>Talep tarihi:</strong> <?= e(substr((string)$req['created_at'],0,16)) ?></p>
    <?php if($req['design_started_at']): ?><p><strong>Çizime başlama:</strong> <?= e(substr((string)$req['design_started_at'],0,16)) ?></p><?php endif; ?>
    <?php if($req['design_completed_at']): ?><p><strong>Admin’e gönderme:</strong> <?= e(substr((string)$req['design_completed_at'],0,16)) ?></p><?php endif; ?>
  </div></div>

  <div class="card"><div class="card-header"><span class="card-title">Çizimci Çalışma Ekranı</span><span class="c-mt">Admin çizim dosyası, red/revize, ürün kartı bağlantısı ve mağaza satış bedelleri burada yoktur.</span></div><div class="card-body">
    <?php if($canWork): ?>
      <?php if(!$canEditDrawing): ?>
        <div class="flash flash-info">Bu çizim artık <strong><?= e(design_status_label($req['status'])) ?></strong> aşamasında. Revize gelirse “Revize Dönenler” sekmesine düşer; bu ekranda tekrar admin onayına gönderilemez.</div>
      <?php else: ?>
      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px">
        <?php if($req['status']==='submitted'): ?><form method="post"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$id ?>"><input type="hidden" name="action" value="take_review"><button class="btn btn-secondary">İncelemeye Aldım</button></form><?php endif; ?>
        <?php if(in_array($req['status'], ['submitted','designer_review','revision_requested','production_revision'], true)): ?><form method="post"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$id ?>"><input type="hidden" name="action" value="start_design"><button class="btn btn-secondary">Çizime Başladım</button></form><?php endif; ?>
        <?php if(in_array($req['status'], ['in_design','revision_requested','production_revision'], true)): ?><form method="post" onsubmit="return confirm('Bu talep admin onayına gönderilecek. Emin misin?')"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$id ?>"><input type="hidden" name="action" value="send_admin"><button class="btn btn-primary">Çizim Bitti — Admin Onayına Gönder</button></form><?php endif; ?>
      </div>
      <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="save_designer"><input type="hidden" name="id" value="<?= (int)$id ?>">
        <div><label class="form-label">Talep Adı</label><input class="form-control" name="title" value="<?= e($req['title']) ?>"></div>
        <div><label class="form-label">Ürün Tipi</label><select class="form-control" name="product_type_code"><option value="">Bilinmiyor</option><?php foreach($types as $k=>$t): ?><option value="<?= e($k) ?>" <?= $req['product_type_code']===$k?'selected':'' ?>><?= e($t['label']) ?> — <?= e($t['letter']) ?></option><?php endforeach; ?></select></div>
        <div><label class="form-label">Çizimci/Sorumlu</label><?php if($canAdmin): ?><select class="form-control" name="designer_user_id"><option value="">Seç</option><?php foreach($designers as $d): ?><option value="<?= (int)$d['id'] ?>" <?= (int)$req['designer_user_id']===(int)$d['id']?'selected':'' ?>><?= e($d['full_name'].' — '.$d['role']) ?></option><?php endforeach; ?></select><?php else: ?><input class="form-control" value="<?= e($req['designer_name'] ?: ($user['full_name'] ?? '')) ?>" readonly><input type="hidden" name="designer_user_id" value="<?= (int)($req['designer_user_id'] ?: ($user['id'] ?? 0)) ?>"><?php endif; ?></div>
        <div><label class="form-label">Boylama?</label><label style="display:block;padding:11px"><input type="checkbox" name="is_sizing_required" value="1" <?= !empty($req['is_sizing_required'])?'checked':'' ?>> Gerekli</label></div>
        <div style="grid-column:span 4"><label class="form-label">Kaynak Link</label><input class="form-control" value="<?= e($req['source_url']) ?>" readonly></div>
        <div style="grid-column:span 4"><label class="form-label">Mağaza Talep Notu</label><textarea class="form-control" rows="3" readonly><?= e($req['request_note']) ?></textarea></div>
        <div><label class="form-label">Genişlik mm</label><input class="form-control" name="width_mm" value="<?= e($req['width_mm']) ?>"></div>
        <div><label class="form-label">Uzunluk mm</label><input class="form-control" name="length_mm" value="<?= e($req['length_mm']) ?>"></div>
        <div><label class="form-label">Yükseklik mm</label><input class="form-control" name="height_mm" value="<?= e($req['height_mm']) ?>"></div>
        <div><label class="form-label">Band Kalınlığı mm</label><input class="form-control" name="band_width_mm" value="<?= e($req['band_width_mm']) ?>"></div>
        <div><label class="form-label">10K Matrix Gram</label><input class="form-control" name="gram_10k" value="<?= e($req['gram_10k']) ?>"></div>
        <div><label class="form-label">14K Matrix Gram</label><input class="form-control" name="gram_14k" value="<?= e($req['gram_14k']) ?>"></div>
        <div><label class="form-label">18K Matrix Gram</label><input class="form-control" name="gram_18k" value="<?= e($req['gram_18k']) ?>"></div>
        <div><label class="form-label">Çizim gerçek maliyet $</label><input class="form-control" name="drawing_cost_actual_usd" value="<?= e($req['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($req['sizing_cost_actual_usd']) ?>"></div>
        <div style="grid-column:span 4"><label class="form-label">Çizimci Taş / Slot Notu</label><textarea class="form-control" name="stone_slot_note" rows="3" placeholder="Örn: 5 adet 4x2 marquise, 4 adet 2mm round. Admin bunu okuyup ürün kartı/numune aşamasında gerçek slotları açacak."><?= e($req['stone_slot_note']) ?></textarea></div>
        <div style="grid-column:span 4"><label class="form-label">Çizimci Notu</label><textarea class="form-control" name="designer_note" rows="3"><?= e($req['designer_note']) ?></textarea></div>
        <?php if($req['admin_note'] || $req['rejection_reason']): ?><div style="grid-column:span 4" class="flash flash-info"><strong>Admin notu / red-revize sebebi:</strong><br><?= nl2br(e($req['admin_note'] ?: $req['rejection_reason'])) ?></div><?php endif; ?>
        <div><button class="btn btn-primary" type="submit">Çizim Bilgilerini Kaydet</button></div>
      </form>
      <?php endif; ?>
    <?php else: ?>
      <p><strong>Ürün tipi:</strong> <?= e(design_product_type_label($req['product_type_code'])) ?></p>
      <p><strong>Talep notu:</strong><br><?= nl2br(e($req['request_note'] ?: '-')) ?></p>
      <?php if(in_array($req['status'], ['submitted','designer_review'], true)): ?><form method="post" onsubmit="return confirm('Bu talebi iptal etmek istiyor musun?')"><?= csrf_field() ?><input type="hidden" name="action" value="store_cancel"><input type="hidden" name="id" value="<?= (int)$id ?>"><input class="form-control" name="reason" placeholder="İptal sebebi" style="max-width:360px"><button class="btn btn-danger" style="margin-top:8px">Talebi İptal Et</button></form><?php endif; ?>
    <?php endif; ?>
  </div></div>
</div>

<?php if($dups): ?><div class="card"><div class="card-header"><span class="card-title">Aynı Link / Benzer Talep Uyarısı</span><span class="c-mt">Çizim dosyası kararı admin ekranında verilir.</span></div><div class="table-wrap"><table><thead><tr><th>No</th><th>Mağaza</th><th>Talep</th><th>Durum</th><th>Grup</th><th>İşlem</th></tr></thead><tbody><?php foreach($dups as $d): ?><tr><td><?= e($d['request_no']) ?></td><td><?= e($d['store_code']) ?></td><td><?= e($d['title']) ?></td><td><?= e(design_status_label($d['status'])) ?></td><td><?= e($d['design_group_id'] ? 'Gruba bağlı' : '-') ?></td><td><a class="btn btn-secondary" href="design_request_detail.php?id=<?= (int)$d['id'] ?>">Aç</a></td></tr><?php endforeach; ?></tbody></table></div></div><?php endif; ?>

<?php if($group && $groupMembers): ?><div class="card"><div class="card-header"><span class="card-title">Bağlı Çizim Dosyası / Mağazalar</span><span class="c-mt">Çizim dosyasından çıkarma ve paylaştırma admin ekranındadır.</span></div><div class="table-wrap"><table><thead><tr><th>Talep</th><th>Mağaza</th><th>Durum</th><th>Çizim Payı</th><th>Boylama Payı</th></tr></thead><tbody><?php foreach($groupMembers as $m): ?><tr><td><?= e($m['request_no'].' — '.$m['title']) ?></td><td><span class="badge"><?= e($m['store_code']) ?></span></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></tr><?php endforeach; ?></tbody></table></div></div><?php endif; ?>

<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>Kullanıcı</th><th>İşlem</th><th>Durum</th><th>Not</th></tr></thead><tbody><?php if(!$audit): ?><tr><td colspan="5" class="c-mt">Geçmiş yok.</td></tr><?php endif; ?><?php foreach($audit as $a): ?><tr><td><?= e(substr((string)$a['created_at'],0,16)) ?></td><td><?= e($a['full_name'] ?: '-') ?></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>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
