<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireCustomer();
$pageTitle = 'My Quotes & Orders';

$custId = $_SESSION['customer_id'];
$tab = $_GET['tab'] ?? 'rfq';

// Load data based on tab
$rfqs = Database::fetchAll("SELECT * FROM quotations WHERE customer_id=? ORDER BY created_at DESC", [$custId]);
$estimates = Database::fetchAll("SELECT * FROM estimates WHERE customer_id=? ORDER BY created_at DESC", [$custId]);
$orders = Database::fetchAll("SELECT * FROM purchase_orders WHERE customer_id=? ORDER BY created_at DESC", [$custId]);

// View single estimate approval
if (isset($_GET['approve_estimate']) && $_GET['approve_estimate']) {
    $estId = (int)$_GET['approve_estimate'];
    $est = Database::fetchOne("SELECT * FROM estimates WHERE id=? AND customer_id=?", [$estId, $custId]);
    if ($est && $est['status'] === 'sent') {
        Database::execute("UPDATE estimates SET status='approved', updated_at=NOW() WHERE id=?", [$estId]);
        $_SESSION['flash']['success'] = 'Estimate approved! We will prepare your purchase order.';
    }
    header('Location: /customer/quotes.php?tab=estimates');
    exit;
}

include dirname(__DIR__) . '/includes/header.php';
?>

<div class="max-w-5xl mx-auto px-4 py-10">
  <div class="flex items-center justify-between mb-8">
    <div>
      <nav class="text-xs text-gray-400 mb-1"><a href="/customer/dashboard.php" class="hover:text-orange-500">Dashboard</a> / Quotes & Orders</nav>
      <h1 class="text-2xl font-bold">My Quotes & Orders</h1>
    </div>
  </div>

  <!-- Tabs -->
  <div class="flex gap-1 border-b border-navy-500 mb-6">
    <?php foreach (['rfq'=>'RFQ Requests','estimates'=>'Estimates','pos'=>'Purchase Orders'] as $t=>$label): ?>
    <a href="?tab=<?= $t ?>" class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px <?= $tab===$t?'border-orange-600 text-orange-500':'border-transparent text-gray-400 hover:text-white' ?>"><?= $label ?></a>
    <?php endforeach; ?>
  </div>

  <?php if ($tab === 'rfq'): ?>
  <div class="card-dark overflow-hidden">
    <div class="p-4 border-b border-navy-500 flex justify-between items-center">
      <h3 class="font-semibold text-sm">RFQ Requests</h3>
      <a href="/shop.php" class="btn-primary text-xs py-1.5">+ New RFQ</a>
    </div>
    <?php if (empty($rfqs)): ?>
    <div class="p-8 text-center text-gray-400">
      <div class="text-4xl mb-3">📋</div>
      <p>No RFQ requests yet.</p>
      <a href="/shop.php" class="btn-primary mt-4 inline-block text-sm">Browse Products</a>
    </div>
    <?php else: ?>
    <table class="data-table">
      <thead><tr><th>Quote #</th><th>Status</th><th>Date</th><th>Valid Until</th></tr></thead>
      <tbody>
      <?php foreach ($rfqs as $q): ?>
      <tr>
        <td class="font-mono text-xs text-orange-400"><?= e($q['quote_number']) ?></td>
        <td><?= statusBadge($q['status']) ?></td>
        <td class="text-xs text-gray-400"><?= formatDate($q['created_at']) ?></td>
        <td class="text-xs text-gray-400"><?= $q['valid_until'] ? formatDate($q['valid_until']) : '—' ?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <?php elseif ($tab === 'estimates'): ?>
  <div class="card-dark overflow-hidden">
    <div class="p-4 border-b border-navy-500">
      <h3 class="font-semibold text-sm">Estimates</h3>
    </div>
    <?php if (empty($estimates)): ?>
    <div class="p-8 text-center text-gray-400"><div class="text-4xl mb-3">📄</div><p>No estimates yet. Submit an RFQ to receive an estimate.</p></div>
    <?php else: ?>
    <table class="data-table">
      <thead><tr><th>Estimate #</th><th>Total</th><th>Status</th><th>Valid Until</th><th>Action</th></tr></thead>
      <tbody>
      <?php foreach ($estimates as $est): ?>
      <tr>
        <td class="font-mono text-xs text-orange-400"><?= e($est['estimate_number']) ?></td>
        <td class="font-semibold text-sm"><?= formatPrice($est['total']) ?></td>
        <td><?= statusBadge($est['status']) ?></td>
        <td class="text-xs text-gray-400"><?= $est['valid_until'] ? formatDate($est['valid_until']) : '—' ?></td>
        <td>
          <div class="flex gap-2">
            <?php if ($est['pdf_path']): ?>
            <a href="/pdf/<?= e($est['pdf_path']) ?>" target="_blank" class="text-xs text-blue-400 hover:underline">📄 PDF</a>
            <?php endif; ?>
            <?php if ($est['status'] === 'sent'): ?>
            <a href="?approve_estimate=<?= $est['id'] ?>" class="text-xs text-green-400 hover:underline" onclick="return confirm('Approve this estimate and proceed with order?')">✅ Approve</a>
            <?php endif; ?>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <?php elseif ($tab === 'pos'): ?>
  <div class="card-dark overflow-hidden">
    <div class="p-4 border-b border-navy-500">
      <h3 class="font-semibold text-sm">Purchase Orders</h3>
    </div>
    <?php if (empty($orders)): ?>
    <div class="p-8 text-center text-gray-400"><div class="text-4xl mb-3">🛒</div><p>No purchase orders yet.</p></div>
    <?php else: ?>
    <table class="data-table">
      <thead><tr><th>PO #</th><th>Total</th><th>Status</th><th>Delivery Date</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($orders as $po): ?>
      <tr>
        <td class="font-mono text-xs text-orange-400"><?= e($po['po_number']) ?></td>
        <td class="font-semibold text-sm"><?= formatPrice($po['total']) ?></td>
        <td><?= statusBadge($po['status']) ?></td>
        <td class="text-xs text-gray-400"><?= $po['delivery_date'] ? formatDate($po['delivery_date']) : '—' ?></td>
        <td>
          <?php if ($po['pdf_path']): ?><a href="/pdf/<?= e($po['pdf_path']) ?>" target="_blank" class="text-xs text-blue-400 hover:underline">📄 PDF</a><?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>
  <?php endif; ?>
</div>

<?php include dirname(__DIR__) . '/includes/footer.php'; ?>
