<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/stone_core_common.php';
require_login();
require_role(['admin']);
$page_title = 'Taş Ölçüleri';
$active_menu = 'stone_sizes';
$user = current_user();

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    $sizeId = (int)($_POST['size_id'] ?? 0);
    try {
        $pdo = db();
        if ($action === 'update_carat') {
            $carat = stone_parse_decimal($_POST['carat_each'] ?? 0);
            if ($sizeId <= 0 || $carat <= 0) throw new RuntimeException('Ölçü ve carat zorunlu.');
            $stmt = $pdo->prepare("SELECT cut_id FROM stone_sizes WHERE id=?");
            $stmt->execute([$sizeId]);
            $cutId = (int)$stmt->fetchColumn();
            if (!$cutId) throw new RuntimeException('Ölçü bulunamadı.');
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO stone_carat_references (cut_id, size_id, carat_each, source_note) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE carat_each=VALUES(carat_each), source_note=VALUES(source_note), is_active=1");
            $stmt->execute([$cutId, $sizeId, $carat, 'Admin update via stone_sizes_admin.php']);
            $stmt = $pdo->prepare("UPDATE stones SET carat_each=? WHERE size_id=?");
            $stmt->execute([$carat, $sizeId]);
            $pdo->commit();
            stone_admin_audit('size_carat_update', 'stone_size', $sizeId, null, ['carat_each'=>$carat], 'Taş ölçü carat güncelleme');
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Ölçü carat bilgisi ve bağlı taş kartları güncellendi.'];
        }
        if ($action === 'toggle_active') {
            $newActive = (int)($_POST['new_active'] ?? 0);
            if ($sizeId <= 0) throw new RuntimeException('Ölçü seçilmedi.');
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("UPDATE stone_sizes SET is_active=? WHERE id=?");
            $stmt->execute([$newActive, $sizeId]);
            $stmt = $pdo->prepare("UPDATE stone_carat_references SET is_active=? WHERE size_id=?");
            $stmt->execute([$newActive, $sizeId]);
            $stmt = $pdo->prepare("UPDATE stones SET is_active=? WHERE size_id=?");
            $stmt->execute([$newActive, $sizeId]);
            $pdo->commit();
            stone_admin_audit($newActive ? 'size_reactivate' : 'size_deactivate', 'stone_size', $sizeId, null, ['is_active'=>$newActive], 'Ölçü seri aktif/pasif');
            $_SESSION['flash'] = ['type'=>'success','msg'=>$newActive ? 'Ölçü serisi aktifleştirildi.' : 'Ölçü serisi pasifleştirildi.'];
        }
        if ($action === 'delete_series') {
            if ($sizeId <= 0) throw new RuntimeException('Ölçü seçilmedi.');
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM stone_stock_movements m JOIN stones st ON st.id=m.stone_id WHERE st.size_id=?");
            $stmt->execute([$sizeId]);
            if ((int)$stmt->fetchColumn() > 0) throw new RuntimeException('Bu ölçüde stok/cari hareketi var. Silinemez; Taş Düzeltmeleri ekranından doğru ölçüye taşı veya pasifleştir.');
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM stone_purchase_lots l JOIN stones st ON st.id=l.stone_id WHERE st.size_id=?");
            $stmt->execute([$sizeId]);
            if ((int)$stmt->fetchColumn() > 0) throw new RuntimeException('Bu ölçüde alım kaydı var. Silinemez; Taş Düzeltmeleri ekranından doğru ölçüye taşı veya pasifleştir.');
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("DELETE FROM stones WHERE size_id=?");
            $stmt->execute([$sizeId]);
            $stmt = $pdo->prepare("DELETE FROM stone_carat_references WHERE size_id=?");
            $stmt->execute([$sizeId]);
            $stmt = $pdo->prepare("DELETE FROM stone_sizes WHERE id=?");
            $stmt->execute([$sizeId]);
            $pdo->commit();
            stone_admin_audit('size_series_delete', 'stone_size', $sizeId, null, null, 'Kullanılmamış ölçü serisi silindi');
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Kullanılmamış ölçü serisi ve bağlı taş kartları silindi.'];
        }
    } catch (Throwable $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('stone_sizes_admin.php');
}

$options = stone_active_options();
$cutFilter = (int)($_GET['cut_id'] ?? 0);
$q = trim($_GET['q'] ?? '');
$params = [];
$sql = "\nSELECT ss.*, cu.cut_name, cu.cut_code, ref.carat_each,\n       COUNT(DISTINCT st.id) stone_count,\n       COUNT(DISTINCT m.id) movement_count\nFROM stone_sizes ss\nJOIN stone_cuts cu ON cu.id=ss.cut_id\nLEFT JOIN stone_carat_references ref ON ref.size_id=ss.id AND ref.cut_id=ss.cut_id\nLEFT JOIN stones st ON st.size_id=ss.id\nLEFT JOIN stone_stock_movements m ON m.stone_id=st.id\nWHERE 1=1\n";
if ($cutFilter > 0) { $sql .= " AND ss.cut_id=:cut_id "; $params['cut_id']=$cutFilter; }
if ($q !== '') { $sql .= " AND (ss.size_label LIKE :q OR ss.size_code LIKE :q2) "; $params['q']='%'.$q.'%'; $params['q2']='%'.$q.'%'; }
$sql .= " GROUP BY ss.id ORDER BY cu.cut_name, COALESCE(ss.diameter_mm, ss.length_mm), ss.width_mm LIMIT 500";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Taş Ölçüleri</h1><p>Yanlış açılmış ölçü serilerini pasifleştir; hareket varsa Taş Düzeltmeleri ekranından doğru ölçüye taşı.</p></div><div style="display:flex;gap:8px"><a class="btn btn-secondary" href="stone_corrections.php">Taş Düzeltmeleri</a><a class="btn btn-secondary" href="stone_requests.php">Taş Açma Talepleri</a></div></div>

<div class="card"><div class="card-body"><form method="get" style="display:grid;grid-template-columns:220px 1fr 120px;gap:10px;align-items:end">
<div><label class="form-label">Kesim</label><select class="form-control" name="cut_id"><option value="0">Tümü</option><?php foreach($options['cuts'] as $c): ?><option value="<?= (int)$c['id'] ?>" <?= $cutFilter===(int)$c['id']?'selected':'' ?>><?= e($c['cut_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Ölçü ara</label><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="2.35 / 4x2 / 0235"></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">Ölçü Listesi</span><span class="c-mt"><?= count($rows) ?> kayıt</span></div><div class="table-wrap"><table><thead><tr><th>Kesim</th><th>Kod</th><th>Ölçü</th><th class="tr">1 Adet Ct</th><th class="tr">Taş Kartı</th><th class="tr">Hareket</th><th>Aktif</th><th>İşlem</th></tr></thead><tbody>
<?php foreach($rows as $r): ?>
<tr>
<form method="post">
<?= csrf_field() ?><input type="hidden" name="size_id" value="<?= (int)$r['id'] ?>">
<td><?= e($r['cut_name']) ?></td>
<td class="mn"><?= e($r['size_code']) ?></td>
<td><?= e($r['size_label']) ?></td>
<td class="tr"><input class="form-control" style="width:110px;text-align:right" name="carat_each" value="<?= e((string)$r['carat_each']) ?>"></td>
<td class="tr"><?= (int)$r['stone_count'] ?></td>
<td class="tr"><?= (int)$r['movement_count'] ?></td>
<td><?= (int)$r['is_active']?'<span class="badge badge-green">Aktif</span>':'<span class="badge badge-red">Pasif</span>' ?></td>
<td><div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-secondary" name="action" value="update_carat">Ct Kaydet</button><?php if((int)$r['is_active']): ?><button class="btn btn-secondary" name="action" value="toggle_active" onclick="this.form.new_active.value=0">Pasifleştir</button><?php else: ?><button class="btn btn-secondary" name="action" value="toggle_active" onclick="this.form.new_active.value=1">Aktifleştir</button><?php endif; ?><input type="hidden" name="new_active" value="0"><button class="btn btn-danger" name="action" value="delete_series" onclick="return confirm('Bu ölçü serisi silinecek. Sadece hiç kullanılmadıysa silinir. Emin misiniz?')">Sil</button></div></td>
</form>
</tr>
<?php endforeach; if(!$rows): ?><tr><td colspan="8" class="c-mt">Kayıt yok.</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
