<?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']);

$id = (int)($_GET['id'] ?? 0);
$stmt = db()->prepare("SELECT * FROM suppliers WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$supplier = $stmt->fetch();
if (!$supplier) {
    $_SESSION['flash'] = ['type'=>'error','msg'=>'Tedarikçi bulunamadı.'];
    redirect('suppliers.php');
}
$user = current_user();
$currencies = stone_currency_options();
if (is_post()) {
    verify_csrf();
    $currency = $_POST['currency'] ?? $supplier['default_currency'];
    if (!in_array($currency, $currencies, true)) $currency = 'USD';
    $amount = stone_parse_decimal($_POST['amount'] ?? 0);
    $type = $_POST['transaction_type'] ?? 'payment';
    $note = trim($_POST['note'] ?? '');
    $date = $_POST['transaction_date'] ?? date('Y-m-d');
    if ($amount <= 0) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Tutar sıfırdan büyük olmalı.'];
        redirect('supplier_detail.php?id='.$id);
    }
    if ($type === 'payment') {
        $debit = 0; $credit = $amount; $label = 'payment';
    } elseif ($type === 'manual_debit') {
        $debit = $amount; $credit = 0; $label = 'manual_debit';
    } else {
        $debit = 0; $credit = $amount; $label = 'manual_credit';
    }
    $stmt = db()->prepare("INSERT INTO supplier_transactions (supplier_id, transaction_date, transaction_type, debit_amount, credit_amount, currency, reference_type, reference_id, note, created_by) VALUES (?,?,?,?,?,?,?,?,?,?)");
    $stmt->execute([$id, $date, $label, $debit, $credit, $currency, 'manual', null, $note, $user['id']]);
    $_SESSION['flash'] = ['type'=>'success','msg'=>'Cari hareket işlendi.'];
    redirect('supplier_detail.php?id='.$id);
}

$stmt = db()->prepare("SELECT currency, SUM(debit_amount) debit, SUM(credit_amount) credit, SUM(debit_amount-credit_amount) balance FROM supplier_transactions WHERE supplier_id=? GROUP BY currency ORDER BY currency");
$stmt->execute([$id]);
$balances = $stmt->fetchAll();

$stmt = db()->prepare("SELECT * FROM supplier_transactions WHERE supplier_id=? ORDER BY transaction_date DESC, id DESC LIMIT 200");
$stmt->execute([$id]);
$txs = $stmt->fetchAll();

$stmt = db()->prepare("\n    SELECT l.*, st.stone_sku, sp.species_name, cu.cut_name, ss.size_label, co.color_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    WHERE l.supplier_id=?\n    ORDER BY l.purchase_date DESC, l.id DESC\n    LIMIT 100\n");
$stmt->execute([$id]);
$purchases = $stmt->fetchAll();

$page_title = 'Tedarikçi Cari';
$active_menu = 'suppliers';
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Tedarikçi Cari Kartı</h1><p><?= e($supplier['supplier_name']) ?><?= $supplier['contact_name'] ? ' — '.e($supplier['contact_name']) : '' ?></p></div><a class="btn btn-secondary" href="suppliers.php">Tedarikçilere Dön</a></div>

<div class="stats-grid">
<?php foreach($balances as $b): ?>
  <div class="stat-card"><div class="stat-label">Bakiye <?= e($b['currency']) ?></div><div class="stat-val <?= (float)$b['balance']>0?'gld':'' ?>"><?= stone_money((float)$b['balance']) ?></div><div class="c-mt">Borç: <?= stone_money((float)$b['debit']) ?> / Ödeme-Alacak: <?= stone_money((float)$b['credit']) ?></div></div>
<?php endforeach; if(!$balances): ?>
  <div class="stat-card"><div class="stat-label">Bakiye</div><div class="stat-val">0</div><div class="c-mt">Henüz cari hareket yok.</div></div>
<?php endif; ?>
</div>

<div class="card"><div class="card-header"><span class="card-title">Cari Hareket Ekle</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;align-items:end">
<?= csrf_field() ?>
<div><label class="form-label">Tarih</label><input type="date" class="form-control" name="transaction_date" value="<?= e(date('Y-m-d')) ?>"></div>
<div><label class="form-label">İşlem</label><select class="form-control" name="transaction_type"><option value="payment">Ödeme yaptık / alacak kapat</option><option value="manual_debit">Manuel borç ekle</option><option value="manual_credit">Manuel alacak/düzeltme</option></select></div>
<div><label class="form-label">Para</label><select class="form-control" name="currency"><?php foreach($currencies as $c): ?><option value="<?= e($c) ?>" <?= $supplier['default_currency']===$c?'selected':'' ?>><?= e($c) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Tutar</label><input class="form-control" name="amount" inputmode="decimal" placeholder="Örn: 250"></div>
<div><button class="btn btn-primary" type="submit">İşle</button></div>
<div style="grid-column:1/-1"><label class="form-label">Not</label><input class="form-control" name="note"></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Cari Hareketleri</span></div><div class="table-wrap"><table><thead><tr><th>Tarih</th><th>Tip</th><th>Para</th><th class="tr">Borç</th><th class="tr">Alacak/Ödeme</th><th>Referans</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><?= e($t['currency']) ?></td><td class="tr"><?= stone_money((float)$t['debit_amount']) ?></td><td class="tr"><?= stone_money((float)$t['credit_amount']) ?></td><td><?php if(in_array($t['reference_type'], ['stone_purchase_lot','stone_purchase_lot_void'], true) && $t['reference_id']): ?><a href="stone_lot_edit.php?id=<?= (int)$t['reference_id'] ?>"><?= e($t['reference_type'] . ' #' . $t['reference_id']) ?></a><?php else: ?><?= e($t['reference_type'] . ' #' . $t['reference_id']) ?><?php endif; ?></td><td><?= e($t['note']) ?></td></tr><?php endforeach; if(!$txs): ?><tr><td colspan="7" class="c-mt">Cari hareket yok.</td></tr><?php endif; ?>
</tbody></table></div></div>

<div class="card"><div class="card-header"><span class="card-title">Bu Tedarikçiden Taş Alımları</span></div><div class="table-wrap"><table><thead><tr><th>ID</th><th>Tarih</th><th>SKU</th><th>Taş</th><th class="tr">Ct</th><th class="tr">Adet</th><th>Para</th><th class="tr">Ct Fiyatı</th><th class="tr">Toplam</th><th>Durum</th></tr></thead><tbody>
<?php foreach($purchases as $p): ?><tr><td><a href="stone_lot_edit.php?id=<?= (int)$p['id'] ?>">#<?= (int)$p['id'] ?></a></td><td><?= e($p['purchase_date']) ?></td><td class="mn"><a href="stone_detail.php?id=<?= (int)$p['stone_id'] ?>"><?= e($p['stone_sku']) ?></a></td><td><?= e($p['species_name'] . ' / ' . $p['cut_name'] . ' / ' . $p['size_label'] . ' / ' . $p['color_name']) ?></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"><?= 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></tr><?php endforeach; if(!$purchases): ?><tr><td colspan="10" class="c-mt">Alım yok.</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
