<?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ı';
$active_menu = 'stone_purchase';
$user = current_user();
$options = stone_active_options();
$currencies = stone_currency_options();
$inline_error = null;

$selected = [
    'purchase_date' => $_POST['purchase_date'] ?? ($_GET['purchase_date'] ?? date('Y-m-d')),
    'supplier_id' => (int)($_POST['supplier_id'] ?? ($_GET['supplier_id'] ?? 0)),
    'currency' => $_POST['currency'] ?? ($_GET['currency'] ?? 'USD'),
    'invoice_no' => $_POST['invoice_no'] ?? '',
    'species_id' => (int)($_POST['species_id'] ?? ($_GET['species_id'] ?? 0)),
    'cut_id' => (int)($_POST['cut_id'] ?? ($_GET['cut_id'] ?? 0)),
    'size_id' => (int)($_POST['size_id'] ?? ($_GET['size_id'] ?? 0)),
    'color_id' => (int)($_POST['color_id'] ?? ($_GET['color_id'] ?? 0)),
    'total_carat' => stone_parse_decimal($_POST['total_carat'] ?? ($_GET['total_carat'] ?? 0)),
    'price_per_carat' => stone_parse_decimal($_POST['price_per_carat'] ?? ($_GET['price_per_carat'] ?? 0)),
    'note' => $_POST['note'] ?? '',
    'request_size_text' => trim($_POST['request_size_text'] ?? ''),
];
if (!in_array($selected['currency'], $currencies, true)) $selected['currency'] = 'USD';

if (!empty($_GET['stone_id'])) {
    $pre = stone_get_by_id((int)$_GET['stone_id']);
    if ($pre) {
        $selected['species_id'] = (int)$pre['species_id'];
        $selected['cut_id'] = (int)$pre['cut_id'];
        $selected['size_id'] = (int)$pre['size_id'];
        $selected['color_id'] = (int)$pre['color_id'];
    }
}

$preview = null;
$stone = null;
if ($selected['species_id'] && $selected['cut_id'] && $selected['size_id'] && $selected['color_id']) {
    $stone = stone_lookup_by_combo($selected['species_id'], $selected['cut_id'], $selected['size_id'], $selected['color_id']);
}

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';

    if ($action === 'request_stone') {
        $speciesText = '';
        foreach ($options['species'] as $o) if ((int)$o['id'] === $selected['species_id']) $speciesText = $o['species_name'];
        $cutText = '';
        foreach ($options['cuts'] as $o) if ((int)$o['id'] === $selected['cut_id']) $cutText = $o['cut_name'];
        $sizeText = $selected['request_size_text'];
        if ($sizeText === '') {
            foreach ($options['sizes'] as $o) if ((int)$o['id'] === $selected['size_id']) $sizeText = $o['size_label'];
        }
        $colorText = '';
        foreach ($options['colors'] as $o) if ((int)$o['id'] === $selected['color_id']) $colorText = $o['color_name'];
        if ($speciesText === '' && $cutText === '' && $sizeText === '' && $colorText === '') {
            $_SESSION['flash'] = ['type'=>'error','msg'=>'Talep için en azından cins/kesim/ölçü/renk bilgilerinden birini seç veya yaz.'];
            redirect('stone_purchase.php');
        }
        $stmt = db()->prepare("INSERT INTO stone_open_requests (requested_by, species_text, cut_text, size_text, color_text, note) VALUES (?,?,?,?,?,?)");
        $stmt->execute([$user['id'], $speciesText, $cutText, $sizeText, $colorText, $selected['note']]);
        $_SESSION['flash'] = ['type'=>'success','msg'=>'Taş açma talebi admin ekranına gönderildi.'];
        redirect('stone_requests.php');
    }

    if ($action === 'preview') {
        if (!$stone) {
            $inline_error = 'Bu kombinasyon için taş kartı bulunamadı. Seçtiğiniz değerler ekranda kaldı; isterseniz Taş Bulunamadıysa Admin\'e Talep Gönder butonuyla talep oluşturabilirsiniz.';
        } else {
            $qty = stone_qty_from_carat($selected['total_carat'], (float)$stone['carat_each']);
            $preview = ['stone'=>$stone, 'qty'=>$qty, 'total_cost'=>$selected['total_carat'] * $selected['price_per_carat']];
        }
    }

    if ($action === 'save_purchase') {
        if (!$stone) {
            $inline_error = 'Taş kartı bulunamadı. Önce Taşı Bul / Hesapla ile taşı bulmalısınız veya admin\'e taş açma talebi göndermelisiniz.';
        } else {
        $pdo = db();
        $pdo->beginTransaction();
        try {
            $lotId = stone_insert_purchase_lot_in_tx($pdo, $selected, (int)$user['id']);
            $pdo->commit();
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Taş alımı kaydedildi. Stok ve tedarikçi cari işlendi.'];
            redirect('stone_lot_edit.php?id='.$lotId);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $inline_error = 'Taş alımı kaydedilemedi: '.$e->getMessage();
        }
        }
    }
}

$recent = db()->query("\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    ORDER BY l.created_at DESC, l.id DESC\n    LIMIT 20\n")->fetchAll();
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Taş Alımı</h1><p>Operatör SKU bilmeden dropdown ile taşı bulur; sistem SKU ve adet hesabını gösterir.</p></div><a class="btn btn-secondary" href="stone_transactions.php">Tüm Taş İşlemleri</a></div>

<div class="card"><div class="card-header"><span class="card-title">Alım Bilgileri</span></div><div class="card-body">
<?php if ($inline_error): ?><div class="flash flash-error"><?= e($inline_error) ?></div><?php endif; ?>
<?php if (empty($options['suppliers'])): ?><div class="flash flash-info">Önce admin tarafından tedarikçi oluşturulmalı.</div><?php endif; ?>
<form method="post" id="purchaseForm" novalidate>
<?= csrf_field() ?>
<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;align-items:end">
<div><label class="form-label">Tarih</label><input class="form-control" type="date" name="purchase_date" value="<?= e($selected['purchase_date']) ?>"></div>
<div><label class="form-label">Tedarikçi</label><select class="form-control" name="supplier_id"><option value="">Seçin</option><?php foreach($options['suppliers'] as $s): ?><option value="<?= (int)$s['id'] ?>" <?= $selected['supplier_id']==$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) ?>" <?= $selected['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($selected['invoice_no']) ?>"></div>
<div><label class="form-label">Cins</label><select class="form-control" name="species_id"><option value="">Seçin</option><?php foreach($options['species'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $selected['species_id']==$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"><option value="">Seçin</option><?php foreach($options['cuts'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $selected['cut_id']==$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"><option value="">Önce kesim seçin</option><?php foreach($options['sizes'] as $o): ?><option data-cut="<?= (int)$o['cut_id'] ?>" value="<?= (int)$o['id'] ?>" <?= $selected['size_id']==$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"><option value="">Seçin</option><?php foreach($options['colors'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $selected['color_id']==$o['id']?'selected':'' ?>><?= e($o['color_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Toplam Carat</label><input class="form-control" type="text" inputmode="decimal" name="total_carat" value="<?= e((string)($_POST['total_carat'] ?? ($selected['total_carat'] ?: ''))) ?>" placeholder="Örn: 1,45"></div>
<div><label class="form-label">Carat Fiyatı</label><input class="form-control" type="text" inputmode="decimal" name="price_per_carat" value="<?= e((string)($_POST['price_per_carat'] ?? ($selected['price_per_carat'] ?: ''))) ?>" placeholder="Örn: 250"></div>
<div><label class="form-label">Listede Yoksa Ölçü Yaz</label><input class="form-control" name="request_size_text" value="<?= e($selected['request_size_text']) ?>" placeholder="Örn: 1.25 mm veya 4x2 mm"></div>
<div><label class="form-label">Not</label><input class="form-control" name="note" value="<?= e($selected['note']) ?>"></div>
</div>
<div style="margin-top:16px;display:flex;gap:10px;flex-wrap:wrap">
<button class="btn btn-secondary" name="action" value="preview" type="submit">Taşı Bul / Hesapla</button>
<?php if ($preview): ?><button class="btn btn-primary" name="action" value="save_purchase" type="submit">Alımı Kaydet</button><?php endif; ?>
<button class="btn btn-secondary" name="action" value="request_stone" type="submit" formnovalidate>Taş Bulunamadıysa Admin'e Talep Gönder</button>
</div>
</form>
</div></div>
<?php if ($preview): $s=$preview['stone']; ?>
<div class="card"><div class="card-header"><span class="card-title">Bulunan Taş</span></div><div class="card-body">
<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px">
<div><div class="stat-label">SKU</div><div class="fw6 mn"><a href="stone_detail.php?id=<?= (int)$s['id'] ?>"><?= e($s['stone_sku']) ?></a></div></div>
<div><div class="stat-label">Taş</div><div><?= e($s['species_name'].' / '.$s['cut_name'].' / '.$s['size_label'].' / '.$s['color_name']) ?></div></div>
<div><div class="stat-label">1 adet carat</div><div><?= number_format((float)$s['carat_each'],5) ?> ct</div></div>
<div><div class="stat-label">Hesaplanan adet</div><div class="stat-val gld" style="font-size:22px"><?= (int)$preview['qty'] ?></div></div>
<div><div class="stat-label">Toplam maliyet</div><div><?= e($selected['currency']) ?> <?= stone_money((float)$preview['total_cost']) ?></div></div>
</div>
</div></div>
<?php endif; ?>

<div class="card"><div class="card-header"><span class="card-title">Son Taş Alımları</span></div><div class="table-wrap"><table><thead><tr><th>ID</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($recent as $r): ?><tr><td>#<?= (int)$r['id'] ?></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"><?= 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(!$recent): ?><tr><td colspan="11" class="c-mt">Henüz alım kaydı yok.</td></tr><?php endif; ?>
</tbody></table></div></div>
<script>
function filterSizes(){
 const cut=document.getElementById('cutSelect').value;
 const size=document.getElementById('sizeSelect');
 [...size.options].forEach((o,i)=>{ if(i===0){o.hidden=false;return;} 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'; ?>
