<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/csv_module_common.php';
require_login();
require_role(['admin','production_manager','workshop_staff','store_user']);

function od_h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function od_date($value): string {
    $value = trim((string)$value);
    if ($value === '' || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') return '-';
    return $value;
}

$user = current_user();
$role = (string)($user['role'] ?? '');
$userId = (int)($user['id'] ?? 0);
$userStoreId = (int)($user['store_id'] ?? 0);
$pdo = db();
$orderId = (int)($_GET['id'] ?? 0);
if ($orderId <= 0) { http_response_code(404); exit('Sipariş bulunamadı.'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($role, ['admin','production_manager','workshop_staff'], true)) {
    verify_csrf();
    $toStatusId = (int)($_POST['to_status_id'] ?? 0);
    $note = trim((string)($_POST['production_note'] ?? ''));
    if ($toStatusId > 0) {
        $st = $pdo->prepare("SELECT * FROM production_statuses WHERE id=? AND is_active=1 LIMIT 1");
        $st->execute([$toStatusId]);
        $toStatus = $st->fetch();
        if ($toStatus) {
            $pdo->beginTransaction();
            try {
                $sel = $pdo->prepare("SELECT id, current_status_id FROM order_items WHERE id=? FOR UPDATE");
                $sel->execute([$orderId]);
                $ord = $sel->fetch();
                if ($ord && (int)$ord['current_status_id'] !== $toStatusId) {
                    $from = (int)$ord['current_status_id'];
                    $pdo->prepare("UPDATE order_items SET current_status_id=?, updated_at=NOW() WHERE id=?")->execute([$toStatusId, $orderId]);
                    $pdo->prepare("INSERT INTO production_logs (order_item_id, from_status_id, to_status_id, changed_by, changed_at, note) VALUES (?,?,?,?,NOW(),?)")
                        ->execute([$orderId, $from ?: null, $toStatusId, $userId ?: null, $note ?: ('Durum güncellendi: '.$toStatus['status_name'])]);
                    $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Üretim durumu güncellendi.'];
                }
                $pdo->commit();
            } catch (Throwable $e) {
                $pdo->rollBack();
                http_response_code(500);
                echo 'Durum güncellenirken hata: '.od_h($e->getMessage());
                exit;
            }
        }
    }
    redirect('order_detail.php?id='.$orderId);
}

$sql = "
    SELECT
        oi.*,
        s.store_code, s.store_name,
        ps.status_code, ps.status_name, ps.sort_order AS status_sort_order, ps.is_final, ps.is_cancelled,
        p.master_code, p.product_name, p.category, p.production_note, p.quality_control_note, p.stone_info,
        specs.short_name, specs.width_mm, specs.length_mm, specs.height_mm, specs.band_width_mm,
        specs.gram_10k, specs.gram_14k, specs.gram_18k, specs.source_url,
        COALESCE(pi.file_path, oi.product_image_path) AS image_path
    FROM order_items oi
    JOIN stores s ON s.id = oi.store_id
    JOIN production_statuses ps ON ps.id = oi.current_status_id
    LEFT JOIN products p ON p.id = oi.product_id
    LEFT JOIN product_core_specs specs ON specs.product_id = p.id
    LEFT JOIN product_images pi ON pi.product_id = p.id AND pi.is_primary = 1
    WHERE oi.id = :id
    LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $orderId]);
$order = $stmt->fetch();
if (!$order) { http_response_code(404); exit('Sipariş bulunamadı.'); }
if ($role === 'store_user' && (int)$order['store_id'] !== $userStoreId) { http_response_code(403); exit('Yetki hatası.'); }

$statuses = $pdo->query("SELECT * FROM production_statuses WHERE is_active=1 ORDER BY sort_order, id")->fetchAll();
[$imageSelect, $imageJoin] = csv_mod_order_image_sql('oi', 'p', 'image_path');
$logsStmt = $pdo->prepare("\n    SELECT pl.*, fs.status_name AS from_status_name, ts.status_name AS to_status_name, u.full_name\n    FROM production_logs pl\n    LEFT JOIN production_statuses fs ON fs.id=pl.from_status_id\n    JOIN production_statuses ts ON ts.id=pl.to_status_id\n    LEFT JOIN users u ON u.id=pl.changed_by\n    WHERE pl.order_item_id=?\n    ORDER BY pl.changed_at DESC, pl.id DESC\n");
$logsStmt->execute([$orderId]);
$logs = $logsStmt->fetchAll();
$img = csv_mod_image_url($order['image_path'] ?? '');

$page_title = 'Sipariş Detayı';
$active_menu = $role === 'store_user' ? 'my_orders' : 'production';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div>
    <h1>Sipariş Detayı</h1>
    <p><span class="badge bg-gld"><?= od_h($order['store_code']) ?></span> <?= od_h($order['sku'] ?: '-') ?> · Transaction <?= od_h($order['transaction_id']) ?></p>
  </div>
  <div class="fc gap8">
    <?php if ($role === 'store_user'): ?>
      <a href="my_orders.php" class="btn btn-secondary">← Siparişlerim</a>
    <?php else: ?>
      <a href="production.php" class="btn btn-secondary">← Üretim Listesi</a>
    <?php endif; ?>
  </div>
</div>

<div class="card mb16">
  <div class="card-body" style="display:grid;grid-template-columns:140px 1fr 1fr;gap:18px;align-items:start">
    <div class="csv-photo" style="width:140px;height:140px">
      <?php if ($img): ?><img src="<?= od_h($img) ?>" alt="" loading="lazy"><?php else: ?><div class="p-thumb-empty">◻</div><?php endif; ?>
    </div>
    <div>
      <h2 style="margin:0 0 8px;font-size:18px"><?= od_h($order['listing_title'] ?: $order['product_name'] ?: '-') ?></h2>
      <div class="fc gap8 mb16" style="flex-wrap:wrap">
        <span class="badge bg-mt"><?= od_h($order['status_name']) ?></span>
        <?php if ((int)($order['product_card_missing'] ?? 0) === 1): ?><span class="badge bg-yl">Ürün kartı yok</span><?php endif; ?>
        <?php if ((int)($order['is_custom'] ?? 0) === 1): ?><span class="badge bg-yl">CUSTOM</span><?php endif; ?>
        <?php if (csv_mod_quantity_label($order)): ?><span class="badge bg-yl">Adet <?= od_h(csv_mod_quantity_label($order)) ?></span><?php endif; ?>
        <?php if ((int)$order['flagged_customer_id'] > 0): ?><span class="badge bg-rd">Riskli müşteri</span><?php endif; ?>
      </div>
      <div class="csv-field"><div class="csv-fl">Ürün Kartı</div><div class="csv-fv">
        <?php if (!empty($order['product_id'])): ?>
          <a href="product_detail.php?id=<?= (int)$order['product_id'] ?>"><?= od_h(($order['master_code'] ?: '').' '.$order['product_name']) ?></a>
        <?php else: ?>
          <span class="c-red">SKU ürün kartıyla eşleşmedi.</span>
        <?php endif; ?>
      </div></div>
      <div class="csv-field"><div class="csv-fl">Karat / Renk / Ölçü</div><div class="csv-fv"><?= od_h(($order['parsed_karat'] ?: '-').' / '.($order['parsed_color'] ?: '-').' / '.($order['parsed_size'] ?: '-')) ?></div></div>
      <div class="csv-field"><div class="csv-fl">Kişiselleştirme</div><div class="csv-fv" style="white-space:pre-wrap"><?= od_h($order['personalization'] ?: '-') ?></div></div>
    </div>
    <div>
      <div class="csv-field"><div class="csv-fl">Müşteri</div><div class="csv-fv"><?= od_h($order['ship_name'] ?: $order['buyer_name'] ?: '-') ?></div></div>
      <div class="csv-field"><div class="csv-fl">Adres</div><div class="csv-fv mt"><?= od_h(trim(($order['ship_address1'] ?: '').' '.($order['ship_address2'] ?: '').' · '.($order['ship_city'] ?: '').' '.($order['ship_state'] ?: '').' '.($order['ship_zip'] ?: '').' · '.($order['ship_country'] ?: '')) ?: '-') ?></div></div>
      <div class="csv-field"><div class="csv-fl">Order / Listing</div><div class="csv-fv mn"><?= od_h($order['etsy_order_id'] ?: '-') ?> / <?= od_h($order['listing_id'] ?: '-') ?></div></div>
      <div class="csv-field"><div class="csv-fl">Üretim Parçası</div><div class="csv-fv"><?= csv_mod_quantity_label($order) ? od_h(csv_mod_quantity_label($order)) : 'Tek adet' ?><?= !empty($order['source_transaction_id']) && $order['source_transaction_id'] !== $order['transaction_id'] ? ' · Kaynak TID: '.od_h($order['source_transaction_id']) : '' ?></div></div>
      <div class="csv-field"><div class="csv-fl">Satış Tarihi</div><div class="csv-fv"><?= od_h(od_date($order['sale_date'])) ?></div></div>
      <div class="csv-field"><div class="csv-fl">Tutar</div><div class="csv-fv"><?= od_h(($order['order_total'] ?? '') !== '' ? $order['order_total'].' '.$order['currency'] : '-') ?></div></div>
    </div>
  </div>
</div>

<?php if (in_array($role, ['admin','production_manager','workshop_staff'], true)): ?>
<div class="card mb16">
  <div class="card-header"><span class="card-title">Üretim Durumu Güncelle</span></div>
  <div class="card-body">
    <form method="post" class="fc gap8" style="align-items:end;flex-wrap:wrap">
      <?= csrf_field() ?>
      <div>
        <label class="form-label">Yeni Durum</label>
        <select name="to_status_id" class="form-control" required style="min-width:220px">
          <?php foreach ($statuses as $s): ?>
            <option value="<?= (int)$s['id'] ?>" <?= (int)$s['id']===(int)$order['current_status_id']?'selected':'' ?>><?= od_h($s['status_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div style="flex:1;min-width:260px">
        <label class="form-label">Not</label>
        <input name="production_note" class="form-control" placeholder="Üretim notu...">
      </div>
      <button class="btn btn-success" type="submit">Durumu Güncelle</button>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="card mb16">
  <div class="card-header"><span class="card-title">Üretim / Ürün Bilgisi</span></div>
  <div class="card-body" style="display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px">
    <div class="csv-field"><div class="csv-fl">Ölçüler</div><div class="csv-fv">G <?= od_h($order['width_mm'] ?: '-') ?> · U <?= od_h($order['length_mm'] ?: '-') ?> · Y <?= od_h($order['height_mm'] ?: '-') ?> · Kol <?= od_h($order['band_width_mm'] ?: '-') ?></div></div>
    <div class="csv-field"><div class="csv-fl">Gramlar</div><div class="csv-fv">10K <?= od_h($order['gram_10k'] ?: '-') ?> · 14K <?= od_h($order['gram_14k'] ?: '-') ?> · 18K <?= od_h($order['gram_18k'] ?: '-') ?></div></div>
    <div class="csv-field"><div class="csv-fl">Kaynak</div><div class="csv-fv"><?= $order['source_url'] ? '<a href="'.od_h($order['source_url']).'" target="_blank">Kaynak Link</a>' : '-' ?></div></div>
    <div class="csv-field"><div class="csv-fl">Mağaza Notu</div><div class="csv-fv" style="white-space:pre-wrap"><?= od_h($order['store_note'] ?: '-') ?></div></div>
    <div class="csv-field"><div class="csv-fl">Admin Notu</div><div class="csv-fv" style="white-space:pre-wrap"><?= od_h($order['admin_note'] ?: '-') ?></div></div>
    <div class="csv-field"><div class="csv-fl">Taş / Üretim Notu</div><div class="csv-fv" style="white-space:pre-wrap"><?= od_h(trim(($order['stone_info'] ?: '').' '.($order['production_note'] ?: '').' '.($order['quality_control_note'] ?: '')) ?: '-') ?></div></div>
  </div>
</div>

<div class="card">
  <div class="card-header"><span class="card-title">İşlem Geçmişi</span></div>
  <?php if (!$logs): ?>
    <div class="empty"><div class="empty-ico">∅</div><div class="empty-title">Henüz üretim logu yok</div></div>
  <?php else: ?>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Tarih</th><th>Durum</th><th>Kullanıcı</th><th>Not</th></tr></thead>
        <tbody>
          <?php foreach ($logs as $log): ?>
            <tr>
              <td class="mn"><?= od_h($log['changed_at']) ?></td>
              <td><?= od_h(($log['from_status_name'] ?: 'Başlangıç').' → '.$log['to_status_name']) ?></td>
              <td><?= od_h($log['full_name'] ?: '-') ?></td>
              <td><?= od_h($log['note'] ?: '-') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/layout_end.php'; ?>
