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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $id = (int)($_POST['quote_id'] ?? 0);
        $status = trim((string)($_POST['status'] ?? 'reviewed'));
        $note = trim((string)($_POST['admin_note'] ?? ''));
        if ($id <= 0) { throw new Exception('Invalid quote request.'); }
        if (!array_key_exists($status, mj_quote_statuses())) { throw new Exception('Invalid status.'); }
        $old = one('SELECT status FROM mj_quote_requests WHERE id=? LIMIT 1', [$id]);
        q('UPDATE mj_quote_requests SET status=?, internal_note=?, updated_at=NOW() WHERE id=?', [$status, $note ?: null, $id]);
        mj_quote_timeline_add($id, 'admin', (int)($admin['id'] ?? 0), 'admin_status_update', $note, (string)($old['status'] ?? ''), $status);
        flash('success', 'Quote request updated.');
    } catch (Throwable $e) { flash('error', $e->getMessage()); }
    redirect('quote-requests.php');
}

$status = trim((string)($_GET['status'] ?? ''));
$qstr = trim((string)($_GET['q'] ?? ''));
$where = [];
$params = [];
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.user_id company_user_id, l.title listing_title, c.name country_name, 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?' WHERE '.implode(' AND ', $where):'').' ORDER BY qr.created_at DESC LIMIT 300';
$rows = safe_all_rows_public($sql,$params);
$counts=[];
try { foreach(all_rows('SELECT status, COUNT(*) c FROM mj_quote_requests GROUP BY status') as $r) { $counts[$r['status']] = (int)$r['c']; } } catch(Throwable $e) {}
$count = array_sum($counts);
$adminTitle = 'Quote Requests';
include __DIR__ . '/_header.php';
?>
<div class="content-header"><div class="container-fluid"><div class="row mb-2"><div class="col-sm-8"><h1 class="m-0"><i class="fas fa-file-invoice-dollar mr-2"></i>Quote Requests</h1><p class="text-muted mb-0">Manage RFQ, company quotation replies, lead quality and follow-up status.</p></div></div></div></div>
<section class="content"><div class="container-fluid"><?php show_flash(); ?>
<div class="row">
  <div class="col-lg-3 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=e($count)?></h3><p>Total Quotes</p></div><div class="icon"><i class="fas fa-receipt"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-primary"><div class="inner"><h3><?=e($counts['new'] ?? 0)?></h3><p>New</p></div><div class="icon"><i class="fas fa-inbox"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=e(($counts['quoted'] ?? 0)+($counts['accepted'] ?? 0)+($counts['won'] ?? 0))?></h3><p>Quoted / Won</p></div><div class="icon"><i class="fas fa-check-circle"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-warning"><div class="inner"><h3><?=e($counts['follow_up'] ?? 0)?></h3><p>Follow Up</p></div><div class="icon"><i class="fas fa-clock"></i></div></div></div>
</div>
<div class="card card-primary card-outline"><div class="card-body"><form method="get"><div class="row"><div class="col-md-5"><input class="form-control" name="q" value="<?=e($qstr)?>" placeholder="Search quote, customer, company or listing"></div><div class="col-md-4"><select class="form-control" 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-md-3"><button class="btn btn-primary btn-block"><i class="fas fa-search mr-1"></i>Filter</button></div></div></form></div></div>
<div class="card"><div class="card-header"><h3 class="card-title">Quote Requests</h3></div><div class="card-body table-responsive">
<?php if(!$rows): ?><div class="mj-empty"><i class="fas fa-inbox fa-2x text-muted mb-2"></i><h5>No quote requests found</h5><p class="text-muted">Quote requests submitted from company/listing pages will appear here.</p></div><?php else: ?>
<table class="table table-striped table-hover mj-datatable"><thead><tr><th>ID</th><th>Request</th><th>Company</th><th>Customer</th><th>Lead</th><th>Status</th><th>Created</th><th>Update</th></tr></thead><tbody>
<?php foreach($rows as $r): ?><tr><td>#<?=e($r['id'])?></td><td><b><?=e($r['title'] ?: 'Quotation request')?></b><br><small class="text-muted"><?=e(mj_quote_excerpt($r['description'] ?? '',90))?></small><?php if($r['listing_title']): ?><br><small><i class="fas fa-tag"></i> <?=e($r['listing_title'])?></small><?php endif; ?></td><td><?=e($r['company_name'] ?: '-')?><br><small class="text-muted"><?=e($r['country_name'] ?? '')?> <?=!empty($r['city_name'])?' / '.e($r['city_name']):''?></small></td><td><?=e($r['requester_name'] ?: '-')?><br><small><?=e($r['requester_email'] ?: '')?><br><?=e($r['requester_phone'] ?: '')?></small></td><td><span class="badge badge-<?=((int)$r['lead_score']>=70?'success':((int)$r['lead_score']>=40?'warning':'secondary'))?>"><?=e(mj_quote_score_label((int)($r['lead_score'] ?? 0)))?> <?=e((int)$r['lead_score'])?>%</span><br><small><?=e(mj_quote_urgency_label((string)$r['urgency']))?></small></td><td><span class="badge badge-<?=e(mj_quote_status_class((string)$r['status']))?>"><?=e(mj_quote_status_label((string)$r['status']))?></span><?php if($r['quoted_amount']): ?><br><small><?=money($r['quoted_amount'],$r['currency_code'] ?: 'SGD')?></small><?php endif; ?></td><td><?=e($r['created_at'])?></td><td><form method="post" style="min-width:210px"><?=csrf_input()?><input type="hidden" name="quote_id" value="<?=e($r['id'])?>"><select class="form-control form-control-sm mb-1" name="status"><?php foreach(mj_quote_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$r['status']===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select><input class="form-control form-control-sm mb-1" name="admin_note" placeholder="Admin note" value="<?=e($r['internal_note'] ?? '')?>"><button class="btn btn-sm btn-primary btn-block">Save</button></form></td></tr><?php endforeach; ?>
</tbody></table><?php endif; ?></div></div>
</div></section>
<?php include __DIR__ . '/_footer.php'; ?>
