<?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ş Alım Kaydı';
$active_menu = 'stone_transactions';
$user = current_user();
$lotId = (int)($_GET['id'] ?? $_POST['lot_id'] ?? 0);
$lot = stone_purchase_lot_full($lotId);
if (!$lot) {
    $_SESSION['flash'] = ['type'=>'error','msg'=>'Taş alım kaydı bulunamadı.'];
    redirect('stone_transactions.php');
}
$options = stone_active_options();
$currencies = stone_currency_options();

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'void_lot') {
            require_role(['admin']);
            stone_void_purchase_lot($lotId, trim($_POST['void_reason'] ?? ''), (int)$user['id']);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Alım kaydı iptal edildi. Stok ve cari ters hareketle düzeltildi.'];
            redirect('stone_lot_edit.php?id='.$lotId);
        }
        if ($action === 'save_correction') {
            require_role(['admin']);
            if ((int)($lot['is_voided'] ?? 0) === 1) throw new RuntimeException('İptal edilmiş kayıt tekrar düzeltilemez. Yeni alım gir.');
            $reason = trim($_POST['correction_reason'] ?? '');
            if ($reason === '') throw new RuntimeException('Düzeltme nedeni zorunlu.');
            $data = [
                'purchase_date' => $_POST['purchase_date'] ?? date('Y-m-d'),
                'supplier_id' => (int)($_POST['supplier_id'] ?? 0),
                'currency' => $_POST['currency'] ?? 'USD',
                'invoice_no' => trim($_POST['invoice_no'] ?? ''),
                'species_id' => (int)($_POST['species_id'] ?? 0),
                'cut_id' => (int)($_POST['cut_id'] ?? 0),
                'size_id' => (int)($_POST['size_id'] ?? 0),
                'color_id' => (int)($_POST['color_id'] ?? 0),
                'total_carat' => $_POST['total_carat'] ?? 0,
                'price_per_carat' => $_POST['price_per_carat'] ?? 0,
                'note' => trim($_POST['note'] ?? ''),
            ];
            $pdo = db();
            $pdo->beginTransaction();
            try {
                stone_void_purchase_lot_in_tx($pdo, $lotId, 'Düzeltme: '.$reason, (int)$user['id']);
                $newLotId = stone_insert_purchase_lot_in_tx($pdo, $data, (int)$user['id'], $lotId);
                $pdo->commit();
                $_SESSION['flash'] = ['type'=>'success','msg'=>'Kayıt düzeltildi. Eski kayıt iptal edildi, yeni doğru kayıt oluşturuldu.'];
                redirect('stone_lot_edit.php?id='.$newLotId);
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                throw $e;
            }
        }
    } catch (Throwable $e) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
        redirect('stone_lot_edit.php?id='.$lotId);
    }
}

$lot = stone_purchase_lot_full($lotId);
$stmt = db()->prepare("SELECT * FROM stone_stock_movements WHERE purchase_lot_id=? ORDER BY id DESC");
$stmt->execute([$lotId]);
$movements = $stmt->fetchAll();
$stmt = db()->prepare("SELECT * FROM supplier_transactions WHERE reference_id=? AND reference_type IN ('stone_purchase_lot','stone_purchase_lot_void') ORDER BY id DESC");
$stmt->execute([$lotId]);
$txs = $stmt->fetchAll();
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Taş Alım Kaydı #<?= (int)$lot['id'] ?></h1><p class="mn"><?= e($lot['stone_sku']) ?></p></div><div style="display:flex;gap:8px"><a class="btn btn-secondary" href="stone_transactions.php">Tüm İşlemler</a><a class="btn btn-secondary" href="stone_detail.php?id=<?= (int)$lot['stone_id'] ?>">Taş Kartı</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($lot['species_name'].' / '.$lot['cut_name'].' / '.$lot['size_label'].' / '.$lot['color_name']) ?></div></div>
  <div class="stat-card"><div class="stat-label">Tedarikçi</div><div class="stat-val" style="font-size:18px"><a href="supplier_detail.php?id=<?= (int)$lot['supplier_id'] ?>"><?= e($lot['supplier_name']) ?></a></div></div>
  <div class="stat-card"><div class="stat-label">Adet / Carat</div><div class="stat-val gld"><?= (int)$lot['calculated_qty'] ?> adet / <?= number_format((float)$lot['total_carat'],4) ?> ct</div></div>
  <div class="stat-card"><div class="stat-label">Durum</div><div class="stat-val"><?= (int)($lot['is_voided']??0)?'<span class="badge badge-red">İptal</span>':'<span class="badge badge-green">Aktif</span>' ?></div></div>
</div>

<?php if ((int)($lot['is_voided']??0) === 1): ?>
<div class="flash flash-info">Bu kayıt iptal edilmiş. Sebep: <?= e($lot['void_reason']) ?> — <?= e($lot['voided_at']) ?></div>
<?php endif; ?>

<div class="card"><div class="card-header"><span class="card-title">Kayıt Detayı</span></div><div class="table-wrap"><table><tbody>
<tr><th>Tarih</th><td><?= e($lot['purchase_date']) ?></td><th>Fatura/Not No</th><td><?= e($lot['invoice_no']) ?></td></tr>
<tr><th>Para</th><td><?= e($lot['currency']) ?></td><th>Ct Fiyatı</th><td><?= stone_money((float)$lot['price_per_carat']) ?></td></tr>
<tr><th>Toplam Maliyet</th><td><?= e($lot['currency']) ?> <?= stone_money((float)$lot['total_cost']) ?></td><th>Not</th><td><?= e($lot['note']) ?></td></tr>
</tbody></table></div></div>

<?php if ((int)($lot['is_voided']??0) === 0 && ($user['role'] ?? '') === 'admin'): ?>
<div class="card"><div class="card-header"><span class="card-title">Kaydı Düzelt</span></div><div class="card-body">
<p class="c-mt">Düzeltme gerçek silme yapmaz. Eski kayıt ters stok/cari hareketiyle iptal edilir; aşağıdaki bilgilerle yeni doğru kayıt açılır.</p>
<form method="post">
<?= csrf_field() ?><input type="hidden" name="lot_id" value="<?= (int)$lot['id'] ?>"><input type="hidden" name="action" value="save_correction">
<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;align-items:end">
<div><label class="form-label">Tarih</label><input class="form-control" type="date" name="purchase_date" value="<?= e($lot['purchase_date']) ?>"></div>
<div><label class="form-label">Tedarikçi</label><select class="form-control" name="supplier_id"><?php foreach($options['suppliers'] as $s): ?><option value="<?= (int)$s['id'] ?>" <?= (int)$lot['supplier_id']===(int)$s['id']?'selected':'' ?>><?= e($s['supplier_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Para</label><select class="form-control" name="currency"><?php foreach($currencies as $c): ?><option value="<?= e($c) ?>" <?= $lot['currency']===$c?'selected':'' ?>><?= e($c) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Fatura/Not No</label><input class="form-control" name="invoice_no" value="<?= e($lot['invoice_no']) ?>"></div>
<div><label class="form-label">Cins</label><select class="form-control" name="species_id"><?php foreach($options['species'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= (int)$lot['species_id']===(int)$o['id']?'selected':'' ?>><?= e($o['species_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Kesim</label><select class="form-control" name="cut_id" id="cutSelect"><?php foreach($options['cuts'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= (int)$lot['cut_id']===(int)$o['id']?'selected':'' ?>><?= e($o['cut_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Ölçü</label><select class="form-control" name="size_id" id="sizeSelect"><?php foreach($options['sizes'] as $o): ?><option data-cut="<?= (int)$o['cut_id'] ?>" value="<?= (int)$o['id'] ?>" <?= (int)$lot['size_id']===(int)$o['id']?'selected':'' ?>><?= e($o['cut_name'].' — '.$o['size_label']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Renk</label><select class="form-control" name="color_id"><?php foreach($options['colors'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= (int)$lot['color_id']===(int)$o['id']?'selected':'' ?>><?= e($o['color_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Toplam Carat</label><input class="form-control" name="total_carat" value="<?= e((string)$lot['total_carat']) ?>"></div>
<div><label class="form-label">Carat Fiyatı</label><input class="form-control" name="price_per_carat" value="<?= e((string)$lot['price_per_carat']) ?>"></div>
<div style="grid-column:span 2"><label class="form-label">Düzeltme Nedeni</label><input class="form-control" name="correction_reason" required placeholder="Örn: Diamond yerine Lab Diamond seçilmiş"></div>
<div style="grid-column:1/-1"><label class="form-label">Not</label><input class="form-control" name="note" value="<?= e($lot['note']) ?>"></div>
</div>
<div style="margin-top:14px"><button class="btn btn-primary" type="submit">Düzelt ve Yeni Kayıt Aç</button></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Kaydı İptal Et</span></div><div class="card-body">
<form method="post" onsubmit="return confirm('Bu alım kaydı iptal edilecek. Stok ve cari ters hareketle düzeltilecek. Emin misiniz?')">
<?= csrf_field() ?><input type="hidden" name="lot_id" value="<?= (int)$lot['id'] ?>"><input type="hidden" name="action" value="void_lot">
<div style="display:grid;grid-template-columns:1fr 160px;gap:10px;align-items:end"><div><label class="form-label">İptal Nedeni</label><input class="form-control" name="void_reason" required placeholder="Örn: Deneme kaydı / yanlış taş seçildi"></div><div><button class="btn btn-danger" type="submit">İptal Et</button></div></div>
</form>
</div></div>
<?php endif; ?>

<div class="card"><div class="card-header"><span class="card-title">Bu Kayıt 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>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><?= e($m['note']) ?></td></tr><?php endforeach; ?>
</tbody></table></div></div>

<div class="card"><div class="card-header"><span class="card-title">Bu Kayıt Cari Hareketleri</span></div><div class="table-wrap"><table><thead><tr><th>Tarih</th><th>Tip</th><th class="tr">Borç</th><th class="tr">Alacak</th><th>Para</th><th>Not</th></tr></thead><tbody>
<?php foreach($txs as $t): ?><tr><td><?= e($t['transaction_date']) ?></td><td><?= e($t['transaction_type']) ?></td><td class="tr"><?= stone_money((float)$t['debit_amount']) ?></td><td class="tr"><?= stone_money((float)$t['credit_amount']) ?></td><td><?= e($t['currency']) ?></td><td><?= e($t['note']) ?></td></tr><?php endforeach; ?>
</tbody></table></div></div>
<script>
function filterSizes(){
 const cut=document.getElementById('cutSelect')?.value;
 const size=document.getElementById('sizeSelect'); if(!size) return;
 [...size.options].forEach((o)=>{ o.hidden = cut && o.dataset.cut !== cut; });
 if(size.selectedOptions[0] && size.selectedOptions[0].hidden) size.value='';
}
document.getElementById('cutSelect')?.addEventListener('change', filterSizes); filterSizes();
</script>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
