<?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ş Açma Talepleri';
$active_menu = 'stone_requests';

$user = current_user();
$options = stone_active_options();

function stone_req_norm(string $s): string
{
    $s = trim($s);
    $s = str_replace(['İ','I','ı'], ['i','i','i'], $s);
    return mb_strtolower($s, 'UTF-8');
}

function stone_req_find_option_id(array $rows, string $nameKey, string $text): int
{
    $needle = stone_req_norm($text);
    if ($needle === '') return 0;
    foreach ($rows as $r) {
        if (stone_req_norm((string)$r[$nameKey]) === $needle) return (int)$r['id'];
    }
    return 0;
}

function stone_req_parse_size_text(string $text): array
{
    $text = trim(str_replace(['×','X','*',' mm','MM'], ['x','x','x','',''], $text));
    $text = str_replace(',', '.', $text);
    if ($text === '') return ['diameter'=>0.0,'length'=>0.0,'width'=>0.0];
    if (preg_match('/([0-9]+(?:\.[0-9]+)?)\s*x\s*([0-9]+(?:\.[0-9]+)?)/', $text, $m)) {
        return ['diameter'=>0.0,'length'=>(float)$m[1],'width'=>(float)$m[2]];
    }
    if (preg_match('/([0-9]+(?:\.[0-9]+)?)/', $text, $m)) {
        return ['diameter'=>(float)$m[1],'length'=>0.0,'width'=>0.0];
    }
    return ['diameter'=>0.0,'length'=>0.0,'width'=>0.0];
}

function stone_req_upsert_size_and_carat(PDO $pdo, int $cutId, string $sizeText, float $carat, int $userId): array
{
    $vals = stone_req_parse_size_text($sizeText);
    if ($carat <= 0) throw new RuntimeException('1 adet carat zorunlu.');
    if ($cutId <= 0) throw new RuntimeException('Kesim seçilmedi.');
    if ($vals['diameter'] <= 0 && ($vals['length'] <= 0 || $vals['width'] <= 0)) {
        throw new RuntimeException('Ölçü okunamadı. Örn: 1.25 veya 8x4 yaz.');
    }
    $sizeCode = stone_size_code_from_values($vals['diameter'], $vals['length'], $vals['width']);
    $sizeLabel = stone_size_label_from_values($vals['diameter'], $vals['length'], $vals['width']);
    if ($sizeCode === '' || $sizeLabel === '') throw new RuntimeException('Ölçü kodu oluşturulamadı.');

    $stmt = $pdo->prepare("INSERT INTO stone_sizes (cut_id, size_code, size_label, diameter_mm, length_mm, width_mm) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE size_label=VALUES(size_label), diameter_mm=VALUES(diameter_mm), length_mm=VALUES(length_mm), width_mm=VALUES(width_mm), is_active=1");
    $stmt->execute([$cutId, $sizeCode, $sizeLabel, $vals['diameter'] > 0 ? $vals['diameter'] : null, $vals['length'] > 0 ? $vals['length'] : null, $vals['width'] > 0 ? $vals['width'] : null]);

    $stmt = $pdo->prepare("SELECT id FROM stone_sizes WHERE cut_id=? AND size_code=? LIMIT 1");
    $stmt->execute([$cutId, $sizeCode]);
    $sizeId = (int)$stmt->fetchColumn();

    $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 request approval via stone_requests.php']);

    stone_admin_audit('request_size_upsert', 'stone_size', $sizeId, null, ['cut_id'=>$cutId,'size_code'=>$sizeCode,'size_label'=>$sizeLabel,'carat'=>$carat], 'Taş açma talebi üzerinden ölçü/carat açıldı');
    return ['size_id'=>$sizeId, 'size_code'=>$sizeCode, 'size_label'=>$sizeLabel];
}

function stone_req_create_single_stone(PDO $pdo, int $speciesId, int $cutId, int $sizeId, int $colorId, float $carat, int $userId): string
{
    if (!$speciesId || !$cutId || !$sizeId || !$colorId || $carat <= 0) throw new RuntimeException('Cins, kesim, ölçü, renk ve 1 adet carat zorunlu.');
    $stmt = $pdo->prepare("SELECT species_code FROM stone_species WHERE id=?");
    $stmt->execute([$speciesId]);
    $spCode = (string)$stmt->fetchColumn();
    $stmt = $pdo->prepare("SELECT cut_code FROM stone_cuts WHERE id=?");
    $stmt->execute([$cutId]);
    $cutCode = (string)$stmt->fetchColumn();
    $stmt = $pdo->prepare("SELECT size_code FROM stone_sizes WHERE id=?");
    $stmt->execute([$sizeId]);
    $sizeCode = (string)$stmt->fetchColumn();
    $stmt = $pdo->prepare("SELECT color_code FROM stone_colors WHERE id=?");
    $stmt->execute([$colorId]);
    $colorCode = (string)$stmt->fetchColumn();
    $sku = stone_generate_sku($spCode, $cutCode, $sizeCode, $colorCode);
    $stmt = $pdo->prepare("INSERT INTO stones (stone_sku, species_id, cut_id, size_id, color_id, carat_each, critical_stock_qty, created_by) VALUES (?,?,?,?,?,?,0,?) ON DUPLICATE KEY UPDATE carat_each=VALUES(carat_each), is_active=1");
    $stmt->execute([$sku, $speciesId, $cutId, $sizeId, $colorId, $carat, $userId]);
    stone_admin_audit('request_single_stone_upsert', 'stone', null, null, ['stone_sku'=>$sku,'species_id'=>$speciesId,'cut_id'=>$cutId,'size_id'=>$sizeId,'color_id'=>$colorId,'carat'=>$carat], 'Taş açma talebi üzerinden tek taş açıldı');
    return $sku;
}

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    $pdo = db();
    try {
        if ($action === 'mark_done' || $action === 'reject') {
            $id = (int)($_POST['id'] ?? 0);
            $status = $action === 'mark_done' ? 'resolved' : 'rejected';
            $stmt = $pdo->prepare("UPDATE stone_open_requests SET status=?, admin_note=?, resolved_at=NOW() WHERE id=?");
            $stmt->execute([$status, trim($_POST['admin_note'] ?? ''), $id]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>$action === 'mark_done' ? 'Talep kapatıldı.' : 'Talep reddedildi.'];
        }

        if ($action === 'delete_request') {
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $pdo->prepare("UPDATE stone_open_requests SET deleted_at=NOW(), deleted_by=?, status='deleted', admin_note=? WHERE id=? AND status='pending'");
            $stmt->execute([$user['id'], trim($_POST['admin_note'] ?? 'Admin tarafından silindi'), $id]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Talep silindi.'];
        }

        if ($action === 'create_size_series') {
            $cutId = (int)($_POST['cut_id'] ?? 0);
            $diameter = stone_parse_decimal($_POST['diameter_mm'] ?? 0);
            $length = stone_parse_decimal($_POST['length_mm'] ?? 0);
            $width = stone_parse_decimal($_POST['width_mm'] ?? 0);
            $carat = stone_parse_decimal($_POST['carat_each'] ?? 0);
            if (!$cutId || $carat <= 0 || (($diameter <= 0) && ($length <= 0 || $width <= 0))) {
                throw new RuntimeException('Kesim, ölçü ve 1 adet carat zorunlu. Round için çap; fantezi kesimler için uzunluk+genişlik gir.');
            }
            $sizeCode = stone_size_code_from_values($diameter, $length, $width);
            $sizeLabel = stone_size_label_from_values($diameter, $length, $width);
            if ($sizeCode === '' || $sizeLabel === '') throw new RuntimeException('Ölçü kodu oluşturulamadı.');
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO stone_sizes (cut_id, size_code, size_label, diameter_mm, length_mm, width_mm) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE size_label=VALUES(size_label), diameter_mm=VALUES(diameter_mm), length_mm=VALUES(length_mm), width_mm=VALUES(width_mm), is_active=1");
            $stmt->execute([$cutId, $sizeCode, $sizeLabel, $diameter > 0 ? $diameter : null, $length > 0 ? $length : null, $width > 0 ? $width : null]);
            $stmt = $pdo->prepare("SELECT id FROM stone_sizes WHERE cut_id=? AND size_code=? LIMIT 1");
            $stmt->execute([$cutId, $sizeCode]);
            $sizeId = (int)$stmt->fetchColumn();
            $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 manual add via stone_requests.php']);
            $created = stone_create_missing_stones_for_size($cutId, $sizeId);
            $pdo->commit();
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Yeni ölçü/carat kaydedildi. Eksik taş kartları otomatik açıldı. Yeni açılan kart sayısı: '.$created];
        }

        if ($action === 'create_single_stone') {
            $speciesId = (int)($_POST['species_id'] ?? 0);
            $cutId = (int)($_POST['single_cut_id'] ?? 0);
            $sizeId = (int)($_POST['size_id'] ?? 0);
            $colorId = (int)($_POST['color_id'] ?? 0);
            $carat = stone_parse_decimal($_POST['single_carat_each'] ?? 0);
            $sku = stone_req_create_single_stone($pdo, $speciesId, $cutId, $sizeId, $colorId, $carat, (int)$user['id']);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Taş kartı açıldı/güncellendi: '.$sku];
        }

        if ($action === 'approve_request_series' || $action === 'approve_request_single') {
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $pdo->prepare("SELECT * FROM stone_open_requests WHERE id=? AND status='pending' AND deleted_at IS NULL LIMIT 1");
            $stmt->execute([$id]);
            $req = $stmt->fetch();
            if (!$req) throw new RuntimeException('Bekleyen talep bulunamadı.');

            $cutId = (int)($_POST['req_cut_id'] ?? 0);
            $speciesId = (int)($_POST['req_species_id'] ?? 0);
            $colorId = (int)($_POST['req_color_id'] ?? 0);
            $sizeText = trim((string)($_POST['req_size_text'] ?? $req['size_text']));
            $carat = stone_parse_decimal($_POST['req_carat_each'] ?? 0);
            $adminNote = trim((string)($_POST['admin_note'] ?? ''));

            if ($cutId <= 0) throw new RuntimeException('Talepteki kesim sistemde bulunamadı; kesim seçmelisin.');
            if ($action === 'approve_request_single' && ($speciesId <= 0 || $colorId <= 0)) throw new RuntimeException('Tek taş açmak için cins ve renk seçmelisin.');

            $pdo->beginTransaction();
            $size = stone_req_upsert_size_and_carat($pdo, $cutId, $sizeText, $carat, (int)$user['id']);
            if ($action === 'approve_request_series') {
                $created = stone_create_missing_stones_for_size($cutId, (int)$size['size_id']);
                $note = trim('Ölçü serisi açıldı: '.$size['size_label'].' / yeni kart: '.$created.' '.$adminNote);
                $stmt = $pdo->prepare("UPDATE stone_open_requests SET status='resolved', admin_note=?, resolved_at=NOW() WHERE id=?");
                $stmt->execute([$note, $id]);
                $pdo->commit();
                $_SESSION['flash'] = ['type'=>'success','msg'=>'Talep onaylandı. Ölçü serisi açıldı/güncellendi. Yeni açılan kart sayısı: '.$created];
            } else {
                $sku = stone_req_create_single_stone($pdo, $speciesId, $cutId, (int)$size['size_id'], $colorId, $carat, (int)$user['id']);
                $note = trim('Tek taş kartı açıldı: '.$sku.' '.$adminNote);
                $stmt = $pdo->prepare("UPDATE stone_open_requests SET status='resolved', admin_note=?, resolved_at=NOW() WHERE id=?");
                $stmt->execute([$note, $id]);
                $pdo->commit();
                $_SESSION['flash'] = ['type'=>'success','msg'=>'Talep onaylandı. Taş kartı açıldı/güncellendi: '.$sku];
            }
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('stone_requests.php');
}
$rows = db()->query("SELECT r.*, u.full_name FROM stone_open_requests r LEFT JOIN users u ON u.id=r.requested_by WHERE r.status='pending' AND r.deleted_at IS NULL ORDER BY r.created_at ASC")->fetchAll();
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Taş Açma Talepleri</h1><p>Operatörün dropdown içinde bulamadığı taşlar. Admin burada talebi doğrudan onaylayabilir, ölçüyü düzelterek açabilir veya reddedebilir.</p></div><div style="display:flex;gap:8px"><a class="btn btn-secondary" href="stone_sizes_admin.php">Taş Ölçüleri</a><a class="btn btn-secondary" href="stones.php">Taş Kartları</a></div></div>

<div class="card"><div class="card-header"><span class="card-title">Yeni Ölçü + Seri Taş Kartı Aç</span></div><div class="card-body">
<p class="c-mt">Yeni ölçü listede yoksa buradan aç. Round için sadece çap gir; fantezi kesimler için uzunluk+genişlik gir. Sistem bu ölçü için izin verilen tüm taş kartlarını otomatik oluşturur.</p>
<form method="post" style="display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="create_size_series">
<div><label class="form-label">Kesim</label><select class="form-control" name="cut_id"><option value="">Seç</option><?php foreach($options['cuts'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['cut_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Çap mm</label><input class="form-control" name="diameter_mm" placeholder="Round: 1.25"></div>
<div><label class="form-label">Uzunluk mm</label><input class="form-control" name="length_mm" placeholder="4"></div>
<div><label class="form-label">Genişlik mm</label><input class="form-control" name="width_mm" placeholder="2"></div>
<div><label class="form-label">1 Adet Carat</label><input class="form-control" name="carat_each" placeholder="0.08"></div>
<div><button class="btn btn-primary" type="submit">Ölçüyü Aç</button></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Tek Taş Kartı Aç / Güncelle</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="create_single_stone">
<div><label class="form-label">Cins</label><select class="form-control" name="species_id"><option value="">Seç</option><?php foreach($options['species'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['species_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Kesim</label><select class="form-control" name="single_cut_id" id="singleCut"><option value="">Seç</option><?php foreach($options['cuts'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['cut_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Ölçü</label><select class="form-control" name="size_id" id="singleSize"><option value="">Önce kesim seç</option><?php foreach($options['sizes'] as $o): ?><option data-cut="<?= (int)$o['cut_id'] ?>" value="<?= (int)$o['id'] ?>"><?= 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ç</option><?php foreach($options['colors'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['color_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">1 Adet Carat</label><input class="form-control" name="single_carat_each" placeholder="0.08"></div>
<div><button class="btn btn-primary" type="submit">Tek Taşı Aç</button></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Bekleyen Talepler</span></div><div class="table-wrap"><table><thead><tr><th>Tarih</th><th>Talep</th><th>Admin Onayı / Düzeltme</th><th>İşlem</th></tr></thead><tbody>
<?php foreach($rows as $r):
    $reqSpeciesId = stone_req_find_option_id($options['species'], 'species_name', (string)$r['species_text']);
    $reqCutId = stone_req_find_option_id($options['cuts'], 'cut_name', (string)$r['cut_text']);
    $reqColorId = stone_req_find_option_id($options['colors'], 'color_name', (string)$r['color_text']);
?>
<tr><form method="post"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
<td><?= e($r['created_at']) ?><br><span class="c-mt"><?= e($r['full_name']) ?></span></td>
<td>
<div><strong><?= e($r['species_text'] ?: '-') ?> / <?= e($r['cut_text'] ?: '-') ?> / <?= e($r['size_text'] ?: '-') ?> / <?= e($r['color_text'] ?: '-') ?></strong></div>
<?php if(trim((string)$r['note']) !== ''): ?><div class="c-mt" style="margin-top:6px"><?= nl2br(e($r['note'])) ?></div><?php endif; ?>
</td>
<td>
<div style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px;align-items:end;min-width:720px">
<div><label class="form-label">Cins</label><select class="form-control" name="req_species_id"><option value="">Seç</option><?php foreach($options['species'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $reqSpeciesId===(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="req_cut_id"><option value="">Seç</option><?php foreach($options['cuts'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $reqCutId===(int)$o['id']?'selected':'' ?>><?= e($o['cut_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Ölçü</label><input class="form-control" name="req_size_text" value="<?= e($r['size_text']) ?>" placeholder="7x3.5 veya 8x4"></div>
<div><label class="form-label">Renk</label><select class="form-control" name="req_color_id"><option value="">Seç</option><?php foreach($options['colors'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $reqColorId===(int)$o['id']?'selected':'' ?>><?= e($o['color_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">1 Adet Ct</label><input class="form-control" name="req_carat_each" placeholder="0.08"></div>
</div>
<input class="form-control" style="margin-top:8px" name="admin_note" placeholder="Admin notu">
</td>
<td><div style="display:flex;flex-direction:column;gap:6px;min-width:180px">
<button class="btn btn-primary" name="action" value="approve_request_series">Ölçü Serisini Aç + Kapat</button>
<button class="btn btn-secondary" name="action" value="approve_request_single">Tek Taşı Aç + Kapat</button>
<button class="btn btn-secondary" name="action" value="mark_done">Sadece Kapat</button>
<button class="btn btn-danger" name="action" value="reject">Reddet</button>
<button class="btn btn-danger" name="action" value="delete_request" onclick="return confirm('Bu talep silinsin mi?')">Sil</button>
</div></td>
</form></tr>
<?php endforeach; if(!$rows): ?><tr><td colspan="4" class="c-mt">Bekleyen talep yok.</td></tr><?php endif; ?>
</tbody></table></div></div>
<script>
function filterSingleSizes(){
 const cut=document.getElementById('singleCut').value;
 const size=document.getElementById('singleSize');
 [...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('singleCut').addEventListener('change', filterSingleSizes); filterSingleSizes();
</script>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
