<?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']);
$page_title = 'Taş İşlemleri';
$active_menu = 'stone_transactions';
$user = current_user();

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'void_lot') {
            require_role(['admin']);
            $lotId = (int)($_POST['lot_id'] ?? 0);
            $reason = trim($_POST['void_reason'] ?? '');
            stone_void_purchase_lot($lotId, $reason, (int)$user['id']);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Alım kaydı iptal edildi. Stok ve cari ters hareketle düzeltildi.'];
        }
    } catch (Throwable $e) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('stone_transactions.php');
}

$q = trim($_GET['q'] ?? '');
$status = $_GET['status'] ?? '';
$params = [];
$sql = "\n    SELECT l.*, st.stone_sku, sp.species_name, cu.cut_name, ss.size_label, co.color_name, su.supplier_name\n    FROM stone_purchase_lots l\n    JOIN stones st ON st.id=l.stone_id\n    JOIN stone_species sp ON sp.id=st.species_id\n    JOIN stone_cuts cu ON cu.id=st.cut_id\n    JOIN stone_sizes ss ON ss.id=st.size_id\n    JOIN stone_colors co ON co.id=st.color_id\n    JOIN suppliers su ON su.id=l.supplier_id\n    WHERE 1=1\n";
if ($q !== '') {
    $sql .= " AND (st.stone_sku LIKE :q1 OR su.supplier_name LIKE :q2 OR sp.species_name LIKE :q3 OR cu.cut_name LIKE :q4 OR co.color_name LIKE :q5 OR l.invoice_no LIKE :q6) ";
    $like = '%'.$q.'%';
    foreach(['q1','q2','q3','q4','q5','q6'] as $k) $params[$k] = $like;
}
if ($status === 'active') $sql .= " AND COALESCE(l.is_voided,0)=0 ";
if ($status === 'voided') $sql .= " AND COALESCE(l.is_voided,0)=1 ";
$sql .= " ORDER BY l.created_at DESC, l.id DESC LIMIT 300";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Taş İşlemleri</h1><p>Tüm taş alım kayıtları. Admin burada yanlış kayıtları iptal eder veya düzeltir.</p></div><a class="btn btn-primary" href="stone_purchase.php">＋ Yeni Taş Alımı</a></div>

<div class="card"><div class="card-body">
<form method="get" style="display:grid;grid-template-columns:1fr 180px 120px;gap:10px;align-items:end">
<div><label class="form-label">Ara</label><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="SKU / tedarikçi / fatura / taş ara"></div>
<div><label class="form-label">Durum</label><select class="form-control" name="status"><option value="" <?= $status===''?'selected':'' ?>>Tümü</option><option value="active" <?= $status==='active'?'selected':'' ?>>Aktif</option><option value="voided" <?= $status==='voided'?'selected':'' ?>>İptal</option></select></div>
<div><button class="btn btn-secondary" type="submit">Filtrele</button></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Alım Kayıtları</span><span class="c-mt"><?= count($rows) ?> kayıt</span></div><div class="table-wrap"><table><thead><tr><th>ID</th><th>Kayıt</th><th>Tarih</th><th>Taş</th><th>SKU</th><th>Tedarikçi</th><th class="tr">Ct</th><th class="tr">Adet</th><th>Para</th><th class="tr">Toplam</th><th>Durum</th><th>İşlem</th></tr></thead><tbody>
<?php foreach($rows as $r): ?>
<tr>
<td>#<?= (int)$r['id'] ?></td>
<td><?= e($r['created_at']) ?></td>
<td><?= e($r['purchase_date']) ?></td>
<td><?= e($r['species_name'].' / '.$r['cut_name'].' / '.$r['size_label'].' / '.$r['color_name']) ?></td>
<td class="mn"><a href="stone_detail.php?id=<?= (int)$r['stone_id'] ?>"><?= e($r['stone_sku']) ?></a></td>
<td><a href="supplier_detail.php?id=<?= (int)$r['supplier_id'] ?>"><?= e($r['supplier_name']) ?></a></td>
<td class="tr"><?= number_format((float)$r['total_carat'],4) ?></td>
<td class="tr"><?= (int)$r['calculated_qty'] ?></td>
<td><?= e($r['currency']) ?></td>
<td class="tr fw6"><?= stone_money((float)$r['total_cost']) ?></td>
<td><?= (int)($r['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)$r['id'] ?>">Detay/Düzelt</a></td>
</tr>
<?php endforeach; if(!$rows): ?><tr><td colspan="12" class="c-mt">Kayıt yok.</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
