<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/stone_core_common.php';
require_login();
require_role(['admin','production_manager','workshop_staff']);

$id = (int)($_GET['id'] ?? 0);
$sku = trim($_GET['sku'] ?? '');
$stone = $id ? stone_get_by_id($id) : ($sku !== '' ? stone_get_by_sku($sku) : null);
if (!$stone) {
    $_SESSION['flash'] = ['type'=>'error','msg'=>'Taş kartı bulunamadı.'];
    redirect('stones.php');
}

$user = current_user();

// Admin-only hard delete for unused/test stone cards.
// If the stone has any purchase lot or stock movement, do NOT delete it from DB.
// Those cases must be corrected through Taş İşlemleri / Taş Düzeltmeleri so stock/cari history stays clean.
if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    try {
        if ($action !== 'delete_unused_stone') {
            throw new RuntimeException('Bilinmeyen işlem.');
        }
        require_role(['admin']);
        $stoneId = (int)$stone['id'];
        $confirmSku = trim((string)($_POST['confirm_sku'] ?? ''));
        if ($confirmSku !== (string)$stone['stone_sku']) {
            throw new RuntimeException('Güvenlik kontrolü başarısız. Silmek için taş SKU aynen gönderilmeli.');
        }

        $pdo = db();
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM stone_purchase_lots WHERE stone_id=?');
        $stmt->execute([$stoneId]);
        $purchaseCount = (int)$stmt->fetchColumn();

        $stmt = $pdo->prepare('SELECT COUNT(*) FROM stone_stock_movements WHERE stone_id=?');
        $stmt->execute([$stoneId]);
        $movementCount = (int)$stmt->fetchColumn();

        if ($purchaseCount > 0 || $movementCount > 0) {
            throw new RuntimeException('Bu taş kartında alım/stok hareketi var. Silinemez; Taş Düzeltmeleri veya Taş İşlemleri ekranından iptal/taşıma yap.');
        }

        $oldData = [
            'stone_sku' => $stone['stone_sku'],
            'species' => $stone['species_name'] ?? null,
            'cut' => $stone['cut_name'] ?? null,
            'size' => $stone['size_label'] ?? null,
            'color' => $stone['color_name'] ?? null,
            'carat_each' => $stone['carat_each'] ?? null,
        ];

        $pdo->beginTransaction();
        // If any request was resolved to this test stone, detach it first so FK/history does not block the delete.
        $stmt = $pdo->prepare("UPDATE stone_open_requests SET resolved_stone_id=NULL, admin_note=CONCAT(COALESCE(admin_note,''), ' | Silinen test taş kartı: ', ?) WHERE resolved_stone_id=?");
        $stmt->execute([$stone['stone_sku'], $stoneId]);
        $stmt = $pdo->prepare('DELETE FROM stones WHERE id=?');
        $stmt->execute([$stoneId]);
        $pdo->commit();

        stone_admin_audit('stone_delete_unused', 'stone', $stoneId, $oldData, null, 'Kullanılmamış/test taş kartı silindi');
        $_SESSION['flash'] = ['type'=>'success','msg'=>'Kullanılmamış taş kartı silindi: '.$stone['stone_sku']];
        redirect('stones.php');
    } catch (Throwable $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Taş kartı silinemedi: '.$e->getMessage()];
        redirect('stone_detail.php?id='.(int)$stone['id']);
    }
}

$page_title = 'Taş Kartı';
$active_menu = 'stones';
$balance = stone_balance_for_stone((int)$stone['id']);
$avgRows = stone_avg_costs_for_stone((int)$stone['id']);

$stmt = db()->prepare("\n    SELECT l.*, s.supplier_name\n    FROM stone_purchase_lots l\n    JOIN suppliers s ON s.id=l.supplier_id\n    WHERE l.stone_id=?\n    ORDER BY l.purchase_date DESC, l.id DESC\n    LIMIT 100\n");
$stmt->execute([(int)$stone['id']]);
$purchases = $stmt->fetchAll();

$stmt = db()->prepare("\n    SELECT * FROM stone_stock_movements\n    WHERE stone_id=?\n    ORDER BY movement_date DESC, id DESC\n    LIMIT 100\n");
$stmt->execute([(int)$stone['id']]);
$movements = $stmt->fetchAll();

$hasPurchases = count($purchases) > 0;
$hasMovements = count($movements) > 0;
$canDeleteUnusedStone = (($user['role'] ?? '') === 'admin') && !$hasPurchases && !$hasMovements;
include __DIR__ . '/includes/layout.php';
?>
<div class="ph">
  <div><h1>Taş Kartı</h1><p class="mn"><?= e($stone['stone_sku']) ?></p></div>
  <div style="display:flex;gap:8px"><a class="btn btn-secondary" href="stones.php?q=<?= urlencode($stone['stone_sku']) ?>">Listeye Dön</a><a class="btn btn-primary" href="stone_purchase.php?stone_id=<?= (int)$stone['id'] ?>">＋ Bu Taşa Alım Gir</a></div>
</div>

<div class="stats-grid">
  <div class="stat-card"><div class="stat-label">Taş</div><div class="stat-val" style="font-size:18px"><?= e($stone['species_name'].' / '.$stone['cut_name'].' / '.$stone['size_label'].' / '.$stone['color_name']) ?></div></div>
  <div class="stat-card"><div class="stat-label">1 Adet Carat</div><div class="stat-val gld"><?= number_format((float)$stone['carat_each'],5) ?> ct</div></div>
  <div class="stat-card"><div class="stat-label">Stok Adet</div><div class="stat-val"><?= (int)$balance['qty'] ?></div></div>
  <div class="stat-card"><div class="stat-label">Stok Carat</div><div class="stat-val"><?= number_format((float)$balance['carat'],4) ?> ct</div></div>
</div>

<?php if (($user['role'] ?? '') === 'admin'): ?>
<div class="card">
  <div class="card-header"><span class="card-title">Admin İşlemleri</span></div>
  <div style="padding:14px 16px">
    <?php if ($canDeleteUnusedStone): ?>
      <form method="post" onsubmit="return confirm('Bu kullanılmamış taş kartı tamamen silinecek. Devam edilsin mi?');" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="delete_unused_stone">
        <input type="hidden" name="confirm_sku" value="<?= e($stone['stone_sku']) ?>">
        <button class="btn btn-danger" type="submit">Bu Kullanılmamış Taş Kartını Sil</button>
        <span class="c-mt">Bu kartta alım, stok hareketi veya cari hareket yok. Silinebilir.</span>
      </form>
    <?php else: ?>
      <div class="c-mt">Bu taş kartında alım veya stok hareketi olduğu için silme kapalı. Gerekirse Taş İşlemleri / Taş Düzeltmeleri ekranından iptal, taşıma veya pasifleştirme yapılmalı.</div>
    <?php endif; ?>
  </div>
</div>
<?php endif; ?>

<div class="card"><div class="card-header"><span class="card-title">Ortalama Alım Maliyeti</span></div><div class="table-wrap"><table><thead><tr><th>Para</th><th class="tr">Toplam Ct</th><th class="tr">Toplam Maliyet</th><th class="tr">Ortalama / Ct</th></tr></thead><tbody>
<?php foreach($avgRows as $a): ?><tr><td><?= e($a['currency']) ?></td><td class="tr"><?= number_format((float)$a['total_carat'],4) ?></td><td class="tr"><?= stone_money((float)$a['total_cost']) ?></td><td class="tr fw6"><?= stone_money((float)$a['avg_per_carat']) ?></td></tr><?php endforeach; if(!$avgRows): ?><tr><td colspan="4" class="c-mt">Henüz alım kaydı yok.</td></tr><?php endif; ?>
</tbody></table></div></div>

<div class="card"><div class="card-header"><span class="card-title">Alım Geçmişi</span></div><div class="table-wrap"><table><thead><tr><th>ID</th><th>Tarih</th><th>Tedarikçi</th><th>Fatura/Not</th><th class="tr">Toplam Ct</th><th class="tr">Adet</th><th>Para</th><th class="tr">Ct Fiyatı</th><th class="tr">Toplam</th><th>Durum</th><th>İşlem</th></tr></thead><tbody>
<?php foreach($purchases as $p): ?><tr><td>#<?= (int)$p['id'] ?></td><td><?= e($p['purchase_date']) ?></td><td><a href="supplier_detail.php?id=<?= (int)$p['supplier_id'] ?>"><?= e($p['supplier_name']) ?></a></td><td><?= e($p['invoice_no']) ?></td><td class="tr"><?= number_format((float)$p['total_carat'],4) ?></td><td class="tr"><?= (int)$p['calculated_qty'] ?></td><td><?= e($p['currency']) ?></td><td class="tr"><?= stone_money((float)$p['price_per_carat']) ?></td><td class="tr fw6"><?= stone_money((float)$p['total_cost']) ?></td><td><?= (int)($p['is_voided']??0)?'<span class="badge badge-red">İptal</span>':'<span class="badge badge-green">Aktif</span>' ?></td><td><a class="btn btn-secondary" href="stone_lot_edit.php?id=<?= (int)$p['id'] ?>">Detay/Düzelt</a></td></tr><?php endforeach; if(!$purchases): ?><tr><td colspan="11" class="c-mt">Alım yok.</td></tr><?php endif; ?>
</tbody></table></div></div>

<div class="card"><div class="card-header"><span class="card-title">Stok Hareketleri</span></div><div class="table-wrap"><table><thead><tr><th>Tarih</th><th>Tip</th><th class="tr">Adet</th><th class="tr">Carat</th><th class="tr">Birim Ct Maliyet</th><th>Referans</th><th>Not</th></tr></thead><tbody>
<?php foreach($movements as $m): ?><tr><td><?= e($m['movement_date']) ?></td><td><?= e($m['movement_type']) ?></td><td class="tr"><?= (int)$m['qty_change'] ?></td><td class="tr"><?= number_format((float)$m['carat_change'],4) ?></td><td class="tr"><?= $m['unit_cost_per_carat']!==null ? stone_money((float)$m['unit_cost_per_carat']) : '-' ?></td><td><?= e($m['reference_type'].' #'.$m['reference_id']) ?></td><td><?= e($m['note']) ?></td></tr><?php endforeach; if(!$movements): ?><tr><td colspan="7" class="c-mt">Stok hareketi yok.</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
