<?php
$adminTitle = 'RFQ / Quotations';
require_once __DIR__ . '/includes/header.php';

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quote_id'])) {
    $qId    = (int)$_POST['quote_id'];
    $status = sanitize($_POST['status'] ?? '');
    $notes  = sanitize($_POST['admin_notes'] ?? '');
    Database::execute("UPDATE quotations SET status=?, admin_notes=?, updated_at=NOW() WHERE id=?", [$status, $notes, $qId]);
    $_SESSION['flash']['success'] = 'Quotation updated.';
    $target = (SITE_URL ? rtrim(SITE_URL, '/') : '') . '/admin/quotes.php';
    header("Location: $target");
    exit;
}

// View single quote
$viewId = isset($_GET['view']) ? (int)$_GET['view'] : 0;
if ($viewId) {
    $quote = Database::fetchOne("SELECT q.*, c.contact_name, c.company_name, c.email, c.phone FROM quotations q LEFT JOIN customers c ON q.customer_id=c.id WHERE q.id=?", [$viewId]);
    $items = Database::fetchAll("SELECT qi.*, p.name as product_name, p.sku FROM quotation_items qi LEFT JOIN products p ON qi.product_id=p.id WHERE qi.quotation_id=?", [$viewId]);
    ?>
    <div class="flex items-center gap-4 mb-6">
      <a href="/admin/quotes.php" class="text-gray-400 hover:text-white">← All RFQs</a>
      <h2 class="font-semibold"><?= e($quote['quote_number']) ?></h2>
      <?= statusBadge($quote['status']) ?>
    </div>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div class="lg:col-span-2">
        <div class="card-dark overflow-hidden mb-4">
          <div class="p-4 border-b border-navy-500"><h3 class="font-semibold text-sm">Requested Items</h3></div>
          <table class="data-table">
            <thead><tr><th>Product</th><th>Qty</th><th>Notes</th></tr></thead>
            <tbody>
            <?php foreach ($items as $item): ?>
            <tr>
              <td>
                <div class="text-sm font-medium"><?= e($item['description']) ?></div>
                <?php if ($item['sku']): ?><div class="text-xs text-gray-400">SKU: <?= e($item['sku']) ?></div><?php endif; ?>
              </td>
              <td class="text-sm"><?= $item['quantity'] ?></td>
              <td class="text-xs text-gray-400"><?= e($item['notes'] ?? '—') ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php if ($quote['attachment']): ?>
        <div class="pdf-strip mb-4 text-sm">
          📎 Attachment: <a href="/uploads/<?= e($quote['attachment']) ?>" target="_blank" class="text-orange-400 hover:underline">Download</a>
        </div>
        <?php endif; ?>
        <div class="card-dark p-5">
          <h3 class="font-semibold text-sm mb-2">Customer Notes</h3>
          <p class="text-sm text-gray-300"><?= e($quote['notes'] ?: '—') ?></p>
        </div>
      </div>
      <div>
        <div class="card-dark p-5 mb-4">
          <h3 class="font-semibold text-sm mb-3">Customer</h3>
          <div class="text-sm font-semibold"><?= e($quote['company_name'] ?: $quote['contact_name']) ?></div>
          <div class="text-xs text-gray-400"><?= e($quote['contact_name']) ?></div>
          <div class="text-xs text-gray-400"><?= e($quote['email']) ?></div>
          <div class="text-xs text-gray-400"><?= e($quote['phone'] ?? '') ?></div>
          <div class="text-xs text-gray-500 mt-2"><?= formatDate($quote['created_at']) ?></div>
        </div>
        <div class="card-dark p-5">
          <h3 class="font-semibold text-sm mb-3">Update Status</h3>
          <form method="POST">
            <input type="hidden" name="quote_id" value="<?= $quote['id'] ?>">
            <div class="mb-3">
              <label class="text-xs text-gray-400 block mb-1">Status</label>
              <select name="status">
                <?php foreach (['pending','reviewed','sent','approved','rejected','expired'] as $s): ?>
                <option value="<?= $s ?>" <?= $quote['status']===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="text-xs text-gray-400 block mb-1">Admin Notes</label>
              <textarea name="admin_notes" rows="3"><?= e($quote['admin_notes'] ?? '') ?></textarea>
            </div>
            <button class="btn-primary w-full text-sm">Update</button>
          </form>
          <a href="/admin/estimates.php?from_quote=<?= $quote['id'] ?>" class="btn-outline w-full text-sm text-center block mt-2">📄 Create Estimate</a>
        </div>
      </div>
    </div>
    <?php
    include __DIR__ . '/includes/footer.php';
    exit;
}

// List
$filter = trim($_GET['status'] ?? '');
$params = $filter ? [$filter] : [];
$where  = $filter ? "WHERE q.status=?" : "";
$total  = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM quotations q $where", $params)['c'] ?? 0);
$pag    = paginate($total, ADMIN_PER_PAGE, (int)($_GET['page'] ?? 1), '/admin/quotes.php?' . http_build_query(array_filter(['status'=>$filter])));
$quotes = Database::fetchAll(
    "SELECT q.*, c.contact_name, c.company_name FROM quotations q LEFT JOIN customers c ON q.customer_id=c.id $where ORDER BY q.created_at DESC LIMIT ? OFFSET ?",
    array_merge($params, [$pag['per_page'], $pag['offset']])
);
?>
<div class="flex items-center justify-between mb-6">
  <h2 class="text-lg font-semibold">RFQ Requests (<?= $total ?>)</h2>
  <div class="flex gap-2">
    <?php foreach ([''=>'All','pending'=>'Pending','reviewed'=>'Reviewed','sent'=>'Sent','approved'=>'Approved'] as $v=>$l): ?>
    <a href="/admin/quotes.php<?= $v ? '?status='.$v : '' ?>" class="text-xs px-3 py-1.5 rounded <?= $filter===$v?'bg-orange-600 text-white':'bg-navy-700 text-gray-300 hover:bg-navy-600' ?>"><?= $l ?></a>
    <?php endforeach; ?>
  </div>
</div>
<div class="card-dark overflow-hidden">
  <table class="data-table">
    <thead><tr><th>Quote #</th><th>Customer</th><th>Status</th><th>Items</th><th>Date</th><th></th></tr></thead>
    <tbody>
    <?php foreach ($quotes as $q): ?>
    <?php $itemCount = Database::fetchOne("SELECT COUNT(*) as c FROM quotation_items WHERE quotation_id=?", [$q['id']])['c'] ?? 0; ?>
    <tr>
      <td class="font-mono text-xs text-orange-400"><?= e($q['quote_number']) ?></td>
      <td class="text-sm"><?= e($q['company_name'] ?: $q['contact_name']) ?></td>
      <td><?= statusBadge($q['status']) ?></td>
      <td class="text-xs"><?= $itemCount ?> items</td>
      <td class="text-xs text-gray-400"><?= formatDate($q['created_at']) ?></td>
      <td><a href="?view=<?= $q['id'] ?>" class="text-xs text-orange-500 hover:underline">Open →</a></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?= paginationHtml($pag) ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
