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

$status = trim((string)($_GET['status'] ?? ''));
$qstr = trim((string)($_GET['q'] ?? ''));
$companyFilterId = (int)($_GET['company_id'] ?? 0);
$where = ['co.user_id=?'];
$params = [(int)$u['id']];
if ($companyFilterId > 0) { $where[] = 'co.id=?'; $params[] = $companyFilterId; }
if ($status !== '' && array_key_exists($status, mj_quote_statuses())) { $where[] = 'qr.status=?'; $params[] = $status; }
if ($qstr !== '') { $where[] = '(qr.title LIKE ? OR qr.requester_name LIKE ? OR qr.requester_email LIKE ? OR co.name LIKE ? OR l.title LIKE ?)'; for($i=0;$i<5;$i++) $params[] = '%'.$qstr.'%'; }
$sql = '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
        INNER 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 FIELD(qr.status,"new","reviewed","quoted","follow_up","accepted","won","lost","rejected","spam","closed"), qr.created_at DESC
        LIMIT 200';
$rows = safe_all_rows_public($sql, $params);
$counts = [];
try {
    $countWhere = ['co.user_id=?'];
    $countParams = [(int)$u['id']];
    if ($companyFilterId > 0) { $countWhere[]='co.id=?'; $countParams[]=$companyFilterId; }
    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 '.implode(' AND ', $countWhere).' GROUP BY qr.status', $countParams) as $r) { $counts[$r['status']] = (int)$r['c']; }
} catch(Throwable $e) {}
$total = array_sum($counts);
$userCompanies = safe_all_rows_public('SELECT id,name FROM mj_companies WHERE user_id=? ORDER BY name', [(int)$u['id']]);
$activeCompanyName = '';
foreach($userCompanies as $uc){ if((int)$uc['id']===$companyFilterId){ $activeCompanyName = (string)$uc['name']; break; } }
$pageTitle='Company Quote Inbox';
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-cutoff"></i>Company Quotes</span><h1 class="fw-bold mb-1">Company Quote Inbox</h1><p class="text-muted mb-0">These are quotation requests received by companies you own. Customer requests you personally sent are under My Quote Requests.</p><?php if($activeCompanyName): ?><div class="mt-2"><span class="mj-badge warn"><i class="bi bi-building me-1"></i>Filtered: <?=e($activeCompanyName)?></span> <a class="small fw-bold ms-2" href="<?=e(base_url('company-quotes.php'))?>">Show all companies</a></div><?php endif; ?></div></div>
  <?php show_flash(); ?>
  <div class="row g-3 mb-4">
    <div class="col-md-3"><div class="mj-quote-stat"><span>Total</span><b><?=e($total)?></b></div></div>
    <div class="col-md-3"><div class="mj-quote-stat"><span>New</span><b><?=e($counts['new'] ?? 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/Won</span><b><?=e(($counts['accepted'] ?? 0)+($counts['won'] ?? 0))?></b></div></div>
  </div>
  <form class="mj-card p-3 mb-4" method="get"><div class="row g-2 align-items-center"><div class="col-lg-4"><input class="form-control" name="q" value="<?=e($qstr)?>" placeholder="Search customer, company, listing or request"></div><div class="col-lg-3"><select class="form-select" name="company_id"><option value="">All my companies</option><?php foreach($userCompanies as $uc): ?><option value="<?=e($uc['id'])?>" <?=$companyFilterId===(int)$uc['id']?'selected':''?>><?=e($uc['name'])?></option><?php endforeach; ?></select></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)?><?=isset($counts[$k])?' ('.(int)$counts[$k].')':''?></option><?php endforeach; ?></select></div><div class="col-lg-2 d-grid"><button class="btn btn-primary rounded-pill"><i class="bi bi-search me-1"></i>Filter</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-inbox"></i></div><h3 class="fw-bold">No quote requests found</h3><p class="text-muted">When customers request quotations from your companies, they will appear here.</p><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-companies.php'))?>">View My Companies</a></div><?php else: ?>
  <div class="mj-quote-list"><?php foreach($rows as $r): ?><div class="mj-quote-row mj-card p-3 mb-3"><div class="row g-3 align-items-center"><div class="col-lg-7"><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"><i class="bi bi-lightning-fill"></i>Urgent</span><?php endif; ?><span class="mj-badge"><i class="bi bi-graph-up"></i><?=e(mj_quote_score_label((int)($r['lead_score'] ?? 0)))?> <?=e((int)($r['lead_score'] ?? 0))?>%</span></div><h4 class="fw-bold mb-1"><a class="text-dark text-decoration-none" href="<?=e(base_url('quote-view.php?id='.(int)$r['id']))?>"><?=e($r['title'] ?: 'Quotation request')?></a></h4><p class="text-muted mb-2"><?=e($r['requester_name'] ?: 'Customer')?> • <?=e($r['requester_phone'] ?: $r['requester_email'])?><?=!empty($r['listing_title'])?' • '.e($r['listing_title']):''?></p><p class="small mb-0"><?=e(mj_quote_excerpt($r['description'] ?? '',180))?></p></div><div class="col-lg-3"><div class="small text-muted">Budget</div><b><?=e($r['budget'] ?: '-')?></b><div class="small text-muted mt-2">Preferred date</div><b><?=e($r['preferred_date'] ?: '-')?></b></div><div class="col-lg-2 text-lg-end"><a class="btn btn-primary rounded-pill mb-2" href="<?=e(base_url('quote-view.php?id='.(int)$r['id']))?>">Open</a><br><small class="text-muted"><?=e(local_datetime($r['created_at'] ?? '', 'UTC'))?></small></div></div></div><?php endforeach; ?></div>
  <?php endif; ?>
</section></div></div>
<?php include __DIR__.'/includes/footer.php'; ?>
