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

$customer = getCurrentCustomer();
$custId = $customer['id'];

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: /customer/login.php');
    exit;
}

// Summary counts
$quoteCount    = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM quotations WHERE customer_id=?", [$custId])['c'] ?? 0);
$estimateCount = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM estimates WHERE customer_id=?", [$custId])['c'] ?? 0);
$poCount       = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM purchase_orders WHERE customer_id=?", [$custId])['c'] ?? 0);
$invoiceCount  = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM invoices WHERE customer_id=?", [$custId])['c'] ?? 0);
$pendingAmount = (float)(Database::fetchOne("SELECT COALESCE(SUM(total-amount_paid),0) as a FROM invoices WHERE customer_id=? AND status IN ('sent','partial','overdue')", [$custId])['a'] ?? 0);
$repairCount   = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM repair_requests WHERE customer_id=?", [$custId])['c'] ?? 0);
$wishlistCount = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM wishlist WHERE customer_id=?", [$custId])['c'] ?? 0);

// Recent quotations
$recentQuotes = Database::fetchAll("SELECT * FROM quotations WHERE customer_id=? ORDER BY created_at DESC LIMIT 5", [$custId]);
// Recent invoices
$recentInvoices = Database::fetchAll("SELECT * FROM invoices WHERE customer_id=? ORDER BY created_at DESC LIMIT 5", [$custId]);

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

<div class="max-w-6xl mx-auto px-4 py-10">
  <!-- Header -->
  <div class="flex items-center justify-between mb-8">
    <div>
      <h1 class="text-2xl font-bold">My Dashboard</h1>
      <p class="text-gray-400 text-sm mt-0.5">Welcome back, <?= e($customer['contact_name']) ?></p>
    </div>
    <a href="?logout=1" class="text-sm text-gray-400 hover:text-red-400">Sign Out</a>
  </div>

  <!-- Stats -->
  <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
    <?php foreach ([
      ['📋', 'RFQ Requests', $quoteCount,    '/customer/quotes.php'],
      ['📄', 'Estimates',    $estimateCount, '/customer/quotes.php?tab=estimates'],
      ['🛒', 'Purchase Orders', $poCount,    '/customer/quotes.php?tab=pos'],
      ['💰', 'Invoices',    $invoiceCount,   '/customer/invoices.php'],
      ['🛠️', 'Repairs',     $repairCount,    '/customer/repair.php'],
      ['❤️', 'Wishlist',    $wishlistCount,  '/customer/wishlist.php'],
    ] as [$icon, $label, $count, $link]): ?>
    <a href="<?= $link ?>" class="card-dark p-4 text-center hover:border-orange-600 transition-colors">
      <div class="text-2xl mb-1"><?= $icon ?></div>
      <div class="text-2xl font-bold text-orange-500"><?= $count ?></div>
      <div class="text-xs text-gray-400 mt-1"><?= $label ?></div>
    </a>
    <?php endforeach; ?>
  </div>

  <?php if ($pendingAmount > 0): ?>
  <div class="pdf-strip mb-6 flex items-center justify-between">
    <div>
      <div class="font-semibold text-sm">Outstanding Balance</div>
      <div class="text-xs text-gray-400">You have unpaid invoices</div>
    </div>
    <div class="text-xl font-bold text-orange-500"><?= formatPrice($pendingAmount) ?></div>
    <a href="/customer/invoices.php" class="btn-primary text-sm">View Invoices</a>
  </div>
  <?php endif; ?>

  <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
    <!-- Recent Quotes -->
    <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">Recent RFQ Requests</h3>
        <a href="/customer/quotes.php" class="text-xs text-orange-500 hover:underline">View All</a>
      </div>
      <?php if (empty($recentQuotes)): ?>
      <div class="p-6 text-center text-gray-400 text-sm">
        No RFQ requests yet. <a href="/shop.php" class="text-orange-500">Browse products →</a>
      </div>
      <?php else: ?>
      <table class="data-table">
        <tbody>
        <?php foreach ($recentQuotes 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>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>

    <!-- Recent Invoices -->
    <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">Recent Invoices</h3>
        <a href="/customer/invoices.php" class="text-xs text-orange-500 hover:underline">View All</a>
      </div>
      <?php if (empty($recentInvoices)): ?>
      <div class="p-6 text-center text-gray-400 text-sm">No invoices yet.</div>
      <?php else: ?>
      <table class="data-table">
        <tbody>
        <?php foreach ($recentInvoices as $inv): ?>
        <tr>
          <td class="font-mono text-xs text-orange-400"><?= e($inv['invoice_number']) ?></td>
          <td class="text-xs font-semibold"><?= formatPrice($inv['total']) ?></td>
          <td><?= statusBadge($inv['status']) ?></td>
          <?php if ($inv['pdf_path']): ?>
          <td><a href="/pdf/<?= e($inv['pdf_path']) ?>" class="text-xs text-blue-400 hover:underline" target="_blank">📄 PDF</a></td>
          <?php else: ?><td></td><?php endif; ?>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>
  </div>

  <!-- Quick Actions -->
  <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-8">
    <a href="/shop.php" class="card-dark p-4 text-center hover:border-orange-600 transition-colors text-sm">
      🛍️<br><span class="text-xs text-gray-300 mt-1 block">Browse Products</span>
    </a>
    <a href="/quote-cart.php" class="card-dark p-4 text-center hover:border-orange-600 transition-colors text-sm">
      📋<br><span class="text-xs text-gray-300 mt-1 block">My RFQ Cart</span>
    </a>
    <a href="/repair-request.php" class="card-dark p-4 text-center hover:border-orange-600 transition-colors text-sm">
      🛠️<br><span class="text-xs text-gray-300 mt-1 block">Request Repair</span>
    </a>
    <a href="/contact.php" class="card-dark p-4 text-center hover:border-orange-600 transition-colors text-sm">
      📞<br><span class="text-xs text-gray-300 mt-1 block">Contact Us</span>
    </a>
  </div>
</div>

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