<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
mj_quote_ensure_schema();

$status = trim((string)($_GET['status'] ?? ''));
$qstr = trim((string)($_GET['q'] ?? ''));

$where = ['qr.user_id=?'];
$params = [(int)$u['id']];
if ($status !== '' && array_key_exists($status, mj_quote_statuses())) { $where[]='qr.status=?'; $params[]=$status; }
if ($qstr !== '') {
    $where[]='(qr.title LIKE ? OR co.name LIKE ? OR l.title LIKE ?)';
    $params[]='%'.$qstr.'%'; $params[]='%'.$qstr.'%'; $params[]='%'.$qstr.'%';
}

$rows = safe_all_rows_public('SELECT qr.*, co.name company_name, co.logo company_logo, co.is_verified, l.title listing_title, l.price listing_price, c.currency_code, ci.name city_name
    FROM mj_quote_requests qr
    LEFT JOIN mj_companies co ON co.id=qr.company_id
    LEFT JOIN mj_listings l ON l.id=qr.listing_id
    LEFT JOIN mj_countries c ON c.id=qr.country_id
    LEFT JOIN mj_cities ci ON ci.id=qr.city_id
    WHERE '.implode(' AND ', $where).'
    ORDER BY qr.created_at DESC LIMIT 200', $params);

$counts=[];
try { foreach(all_rows('SELECT status, COUNT(*) c FROM mj_quote_requests WHERE user_id=? GROUP BY status', [(int)$u['id']]) as $r) { $counts[$r['status']] = (int)$r['c']; } } catch(Throwable $e) {}

$receivedCounts=[];
$receivedTotal=0;
try {
    foreach(all_rows('SELECT qr.status, COUNT(*) c
        FROM mj_quote_requests qr
        INNER JOIN mj_companies co ON co.id=qr.company_id
        WHERE co.user_id=?
        GROUP BY qr.status', [(int)$u['id']]) as $r) {
        $receivedCounts[$r['status']] = (int)$r['c'];
    }
    $receivedTotal = array_sum($receivedCounts);
} catch(Throwable $e) {}

$pageTitle='My Quotes';
include __DIR__.'/includes/header.php';
?>
<div class="container py-5">
  <div class="sidebar-layout">
    <?php include __DIR__.'/includes/account-sidebar.php'; ?>
    <section>
      <div class="mj-page-hero rounded-4 mb-4">
        <div class="container-fluid">
          <span class="mj-badge mb-2"><i class="bi bi-receipt"></i>My Quotes</span>
          <h1 class="fw-bold mb-1">My Quote Requests</h1>
          <p class="text-muted mb-0">Quotes you requested from companies. If you own a company, received customer quote requests are in Company Quote Inbox.</p>
        </div>
      </div>

      <?php show_flash(); ?>

      <div class="mj-card p-3 mb-4">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
          <div>
            <h5 class="fw-bold mb-1">Quote area</h5>
            <p class="text-muted mb-0 small">Choose whether you want to view quotes you requested or quote requests received by your companies.</p>
          </div>
          <div class="d-flex flex-wrap gap-2">
            <a class="btn btn-primary rounded-pill" href="<?=e(base_url('my-quotes.php'))?>"><i class="bi bi-person-lines-fill me-1"></i>Requested by Me</a>
            <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('company-quotes.php'))?>"><i class="bi bi-building-check me-1"></i>Received by My Company<?= $receivedTotal ? ' ('.e($receivedTotal).')' : '' ?></a>
          </div>
        </div>
        <?php if($receivedTotal): ?>
          <div class="alert alert-info rounded-4 mt-3 mb-0">
            <i class="bi bi-info-circle me-1"></i>
            Your company has <b><?=e($receivedTotal)?></b> received quote request<?= $receivedTotal==1?'':'s' ?>.
            <a href="<?=e(base_url('company-quotes.php'))?>" class="fw-bold">Open Company Quote Inbox</a>
          </div>
        <?php endif; ?>
      </div>

      <div class="row g-3 mb-4">
        <div class="col-md-3"><div class="mj-quote-stat"><span>Total requested</span><b><?=e(count($rows))?></b></div></div>
        <div class="col-md-3"><div class="mj-quote-stat"><span>Waiting</span><b><?=e(($counts['new'] ?? 0)+($counts['reviewed'] ?? 0))?></b></div></div>
        <div class="col-md-3"><div class="mj-quote-stat"><span>Quoted</span><b><?=e($counts['quoted'] ?? 0)?></b></div></div>
        <div class="col-md-3"><div class="mj-quote-stat"><span>Accepted</span><b><?=e($counts['accepted'] ?? 0)?></b></div></div>
      </div>

      <form class="mj-card p-3 mb-4" method="get">
        <div class="row g-2">
          <div class="col-lg-6"><input class="form-control" name="q" value="<?=e($qstr)?>" placeholder="Search company, listing or request"></div>
          <div class="col-lg-3"><select class="form-select" name="status"><option value="">All statuses</option><?php foreach(mj_quote_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select></div>
          <div class="col-lg-3 d-grid"><button class="btn btn-primary rounded-pill">Search</button></div>
        </div>
      </form>

      <?php if(!$rows): ?>
        <div class="mj-card p-5 text-center">
          <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-receipt"></i></div>
          <h3 class="fw-bold">No quote requests sent by you yet</h3>
          <p class="text-muted">When you request quotations from companies as a customer, you can track them here.</p>
          <div class="d-flex flex-wrap justify-content-center gap-2">
            <a class="btn btn-primary rounded-pill" href="<?=e(base_url('companies.php'))?>">Browse Companies</a>
            <?php if($receivedTotal): ?><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('company-quotes.php'))?>">View Received Quotes</a><?php endif; ?>
          </div>
        </div>
      <?php else: ?>
        <?php foreach($rows as $r): ?>
          <div class="mj-card p-3 mb-3 mj-quote-row">
            <div class="row g-3 align-items-center">
              <div class="col-lg-8">
                <div class="d-flex flex-wrap gap-2 mb-2">
                  <span class="badge text-bg-<?=e(mj_quote_status_class((string)$r['status']))?> rounded-pill"><?=e(mj_quote_status_label((string)$r['status']))?></span>
                  <?php if($r['urgency']==='urgent'): ?><span class="mj-badge warn">Urgent</span><?php endif; ?>
                </div>
                <h4 class="fw-bold mb-1"><a href="<?=e(base_url('quote-view.php?id='.(int)$r['id']))?>" class="text-dark text-decoration-none"><?=e($r['title'] ?: 'Quotation request')?></a></h4>
                <p class="text-muted mb-2"><?=e($r['company_name'] ?: 'Company')?><?=!empty($r['listing_title'])?' • '.e($r['listing_title']):''?></p>
                <small class="text-muted">Submitted <?=e(local_datetime($r['created_at'] ?? '', 'UTC'))?></small>
              </div>
              <div class="col-lg-4 text-lg-end">
                <a class="btn btn-primary rounded-pill" href="<?=e(base_url('quote-view.php?id='.(int)$r['id']))?>">View Quote</a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>
  </div>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
