<?php
require_once __DIR__.'/includes/functions.php';
verify_csrf();
mj_quote_ensure_schema();
if (function_exists('mj263_schema')) { mj263_schema(); }
if (function_exists('mj_trust_bundle_ensure_schema')) { mj_trust_bundle_ensure_schema(); }

$user = current_user();
$companyId = (int)($_GET['company_id'] ?? $_POST['company_id'] ?? 0);
$listingId = (int)($_GET['listing_id'] ?? $_POST['listing_id'] ?? 0);

$company = null;
$listing = null;
if ($listingId > 0) {
    $listing = safe_one_public('SELECT l.*, c.currency_code, c.name country_name, c.flag_emoji, ci.name city, cat.name category
        FROM mj_listings l
        LEFT JOIN mj_countries c ON c.id=l.country_id
        LEFT JOIN mj_cities ci ON ci.id=l.city_id
        LEFT JOIN mj_categories cat ON cat.id=l.category_id
        WHERE l.id=? LIMIT 1', [$listingId]);
    if ($listing && !$companyId && !empty($listing['company_id'])) { $companyId = (int)$listing['company_id']; }
}
if ($companyId > 0) {
    $company = safe_one_public('SELECT co.*, c.name country_name, c.flag_emoji, ci.name city_name, cat.name category_name
        FROM mj_companies co
        LEFT JOIN mj_countries c ON c.id=co.country_id
        LEFT JOIN mj_cities ci ON ci.id=co.city_id
        LEFT JOIN mj_categories cat ON cat.id=co.category_id
        WHERE co.id=? LIMIT 1', [$companyId]);
}
$companies = [];
if (!$company) {
    $companies = safe_all_rows_public('SELECT co.id,co.name,c.name country_name,ci.name city_name
        FROM mj_companies co
        LEFT JOIN mj_countries c ON c.id=co.country_id
        LEFT JOIN mj_cities ci ON ci.id=co.city_id
        WHERE co.status IN ("active","approved","published")
        ORDER BY co.is_featured DESC, co.is_verified DESC, co.name ASC
        LIMIT 250');
}

$success = false;
$requestId = 0;
$form = [
    'requester_name' => $user['name'] ?? '',
    'requester_email' => $user['email'] ?? '',
    'requester_phone' => $user['mobile'] ?? '',
    'title' => $listing ? ('Quotation request for '.$listing['title']) : '',
    'description' => '',
    'urgency' => 'normal',
    'budget' => '',
    'preferred_date' => '',
    'preferred_contact' => 'whatsapp',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($form as $k => $v) { $form[$k] = trim((string)($_POST[$k] ?? $v)); }
    $companyId = (int)($_POST['company_id'] ?? $companyId);
    $listingId = (int)($_POST['listing_id'] ?? $listingId);
    $errors = [];

    if ($companyId <= 0) { $errors[] = 'Please choose a company to request a quotation.'; }
    if ($form['requester_name'] === '') { $errors[] = 'Please enter your name.'; }
    if ($form['requester_email'] === '' || !filter_var($form['requester_email'], FILTER_VALIDATE_EMAIL)) { $errors[] = 'Please enter a valid email address.'; }
    if ($form['requester_phone'] === '') { $errors[] = 'Please enter your phone or WhatsApp number.'; }
    if ($form['title'] === '') { $errors[] = 'Please enter a quotation subject.'; }
    if ($form['description'] === '' || (function_exists('mb_strlen') ? mb_strlen($form['description']) < 10 : strlen($form['description']) < 10)) { $errors[] = 'Please describe what you need in at least 10 characters.'; }
    if (!in_array($form['urgency'], ['normal','urgent','this_week','flexible'], true)) { $form['urgency'] = 'normal'; }
    if (!in_array($form['preferred_contact'], ['whatsapp','phone','email'], true)) { $form['preferred_contact'] = 'whatsapp'; }

    if (!$errors) {
        try {
            $companyRow = one('SELECT id,user_id,name,country_id,city_id FROM mj_companies WHERE id=? LIMIT 1', [$companyId]);
            if (!$companyRow) { throw new Exception('Selected company was not found.'); }
            $leadScore = mj_quote_lead_score($form);
            $currency = $listing['currency_code'] ?? 'SGD';
            q('INSERT INTO mj_quote_requests(user_id,company_id,listing_id,country_id,city_id,title,description,urgency,requester_name,requester_email,requester_phone,budget,preferred_date,preferred_contact,status,currency_code,lead_score,source,ip_address,user_agent,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,? ,"new",?,?,?,?,?,NOW(),NOW())', [
                $user['id'] ?? null,
                $companyId,
                $listingId ?: null,
                $companyRow['country_id'] ?? null,
                $companyRow['city_id'] ?? null,
                $form['title'],
                $form['description'],
                $form['urgency'],
                $form['requester_name'],
                $form['requester_email'],
                $form['requester_phone'],
                $form['budget'] ?: null,
                $form['preferred_date'] ?: null,
                $form['preferred_contact'],
                $currency,
                $leadScore,
                $listingId ? 'listing_page' : 'company_page',
                $_SERVER['REMOTE_ADDR'] ?? '',
                substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255)
            ]);
            $requestId = (int)db()->lastInsertId();
            try { mj_quote_upload_attachment($requestId, (int)($user['id'] ?? 0), 'attachment'); } catch (Throwable $e) { flash('warning', $e->getMessage()); }
            mj_quote_timeline_add($requestId, $user ? 'user' : 'guest', (int)($user['id'] ?? 0), 'submitted', 'Quotation request submitted.', '', 'new');

            $quote = mj_quote_fetch($requestId);
            if ($quote && !empty($quote['user_id'])) {
                $chatId = mj_quote_create_or_open_chat($quote);
                if ($chatId > 0) { mj_quote_timeline_add($requestId, 'system', 0, 'chat_created', 'Chat conversation connected to this quote.'); }
            }

            mj_quote_safe_notify_user(
                (int)($companyRow['user_id'] ?? 0),
                'quote_request',
                'New quotation request',
                $form['title'],
                'company-quotes.php?status=new',
                $form['urgency']==='urgent' ? 'high' : 'normal'
            );
            try {
                mj_create_admin_alert([
                    'alert_key' => 'quote_request_'.$requestId,
                    'alert_type' => 'quote_request',
                    'module_name' => 'quotes',
                    'priority' => $form['urgency']==='urgent' ? 'high' : 'normal',
                    'title' => 'New quotation request',
                    'message' => $form['title'],
                    'action_url' => 'quote-requests.php',
                    'action_label' => 'Review',
                    'related_type' => 'quote_request',
                    'related_id' => $requestId
                ]);
            } catch (Throwable $e) {}

            $success = true;
            flash('success', 'Quotation request sent successfully. The company can review your request and reply soon.');
            $company = safe_one_public('SELECT co.*, c.name country_name, c.flag_emoji, ci.name city_name, cat.name category_name
                FROM mj_companies co
                LEFT JOIN mj_countries c ON c.id=co.country_id
                LEFT JOIN mj_cities ci ON ci.id=co.city_id
                LEFT JOIN mj_categories cat ON cat.id=co.category_id
                WHERE co.id=? LIMIT 1', [$companyId]);
        } catch (Throwable $e) {
            flash('error', $e->getMessage());
        }
    } else {
        foreach ($errors as $err) { flash('error', $err); }
    }
}

$scorePreview = mj_quote_lead_score($form);
$pageTitle = 'Request Quotation';
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <nav class="small mb-2"><a href="<?=e(base_url('/'))?>">Home</a> / <a href="<?=e(base_url('companies.php'))?>">Companies</a> / Request Quotation</nav>
    <span class="mj-badge mb-2"><i class="bi bi-receipt"></i> Request Quote</span>
    <h1 class="fw-bold display-5 mb-1">Request a Quotation</h1>
    <p class="text-muted mb-0">Tell the company what you need. Add clear details so they can reply with a useful quote.</p>
  </div>
</section>

<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>
    <?php if($success): ?>
      <div class="mj-card p-5 text-center mx-auto" style="max-width:820px">
        <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-check2-circle"></i></div>
        <h2 class="fw-bold">Quotation request sent</h2>
        <p class="text-muted">Your request number is <b>#<?=e($requestId)?></b>. The company can reply with quote details or continue the conversation in chat.</p>
        <div class="d-flex justify-content-center flex-wrap gap-2 mt-3">
          <a class="btn btn-primary rounded-pill" href="<?=e(base_url('my-quotes.php'))?>"><i class="bi bi-receipt me-1"></i>My Quotes</a>
          <?php if($company): ?><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('company.php?id='.(int)$company['id']))?>">View Company</a><?php endif; ?>
          <a class="btn btn-outline-secondary rounded-pill" href="<?=e(base_url('companies.php'))?>">Browse Companies</a>
        </div>
      </div>
    <?php else: ?>
      <div class="row g-4 align-items-start">
        <div class="col-lg-5">
          <?php if($company): ?>
            <div class="mj-card p-4 mb-4 mj-quote-side-card">
              <div class="d-flex gap-3 align-items-start">
                <div class="mj-icon-box flex-shrink-0"><i class="bi bi-building"></i></div>
                <div>
                  <div class="d-flex flex-wrap gap-1 mb-2">
                    <?php if(!empty($company['is_verified'])): ?><span class="mj-badge good"><i class="bi bi-patch-check-fill"></i>Verified</span><?php endif; ?>
                    <?php if(!empty($company['is_featured'])): ?><span class="mj-badge warn"><i class="bi bi-star-fill"></i>Featured</span><?php endif; ?>
                  </div>
                  <h3 class="fw-bold mb-1"><?=e($company['name'])?></h3>
                  <p class="text-muted mb-2"><?=e(trim(($company['flag_emoji'] ?? '').' '.($company['country_name'] ?? '').(!empty($company['city_name']) ? ' • '.$company['city_name'] : '')))?></p>
                  <p class="mb-0"><?=e(mj_company_short_description($company, 170))?></p>
                </div>
              </div>
              <hr>
              <div class="row g-3">
                <div class="col-6"><div class="mj-quote-mini"><span>Trust</span><b><?=e((int)($company['trust_score'] ?? 0))?>%</b></div></div>
                <div class="col-6"><div class="mj-quote-mini"><span>Profile</span><b><?=e((int)($company['profile_score'] ?? 0))?>%</b></div></div>
              </div>
              <a class="btn btn-outline-primary w-100 mt-3 rounded-pill" href="<?=e(base_url('company.php?id='.(int)$company['id']))?>"><i class="bi bi-building me-1"></i>View Company Profile</a>
            </div>
          <?php else: ?>
            <div class="mj-card p-4 mb-4"><h3 class="fw-bold">Choose a company</h3><p class="text-muted mb-0">Select the company you want to send this quotation request to.</p></div>
          <?php endif; ?>

          <?php if($listing): ?>
            <div class="mj-card p-4 mb-4">
              <span class="mj-badge mb-2"><i class="bi bi-box-seam"></i>Related listing</span>
              <h4 class="fw-bold mb-1"><?=e($listing['title'])?></h4>
              <p class="text-muted mb-2"><?=e($listing['category'] ?? 'Listing')?> <?=!empty($listing['city'])?'• '.e($listing['city']):''?></p>
              <div class="fw-bold fs-5 mb-3"><?=money($listing['price'] ?? 0, $listing['currency_code'] ?? 'SGD')?></div>
              <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('listing.php?id='.$listingId))?>">Open Listing</a>
            </div>
          <?php endif; ?>

          <div class="mj-card p-4 border-warning">
            <h5 class="fw-bold"><i class="bi bi-graph-up-arrow me-1"></i>Request quality</h5>
            <div class="d-flex justify-content-between small mb-1"><span><?=e(mj_quote_score_label($scorePreview))?></span><b><?=e($scorePreview)?>%</b></div>
            <div class="progress mb-3" style="height:8px"><div class="progress-bar" style="width:<?=e($scorePreview)?>%"></div></div>
            <ul class="small text-muted mb-0 ps-3"><li>Add phone/WhatsApp</li><li>Add budget or preferred date</li><li>Describe the problem clearly</li><li>Attach photo/PDF if useful</li></ul>
          </div>
        </div>

        <div class="col-lg-7">
          <div class="mj-card p-4 p-lg-5">
            <h2 class="fw-bold mb-2">Send quotation request</h2>
            <p class="text-muted mb-4">The more details you provide, the faster the company can reply.</p>
            <form method="post" enctype="multipart/form-data">
              <?=csrf_input()?>
              <input type="hidden" name="listing_id" value="<?=e($listingId)?>">
              <?php if($company): ?>
                <input type="hidden" name="company_id" value="<?=e((int)$company['id'])?>">
              <?php else: ?>
                <div class="mb-3"><label class="form-label fw-semibold">Company <span class="text-danger">*</span></label><select name="company_id" class="form-select" required><option value="">Select company</option><?php foreach($companies as $co): ?><option value="<?=e($co['id'])?>" <?=((int)$co['id']===$companyId)?'selected':''?>><?=e($co['name'].' - '.trim(($co['country_name'] ?? '').(!empty($co['city_name']) ? ' / '.$co['city_name'] : '')))?></option><?php endforeach; ?></select></div>
              <?php endif; ?>

              <div class="row g-3">
                <div class="col-md-6"><label class="form-label fw-semibold">Your name <span class="text-danger">*</span></label><input class="form-control" name="requester_name" maxlength="180" required value="<?=e($form['requester_name'])?>"></div>
                <div class="col-md-6"><label class="form-label fw-semibold">Email <span class="text-danger">*</span></label><input class="form-control" type="email" name="requester_email" maxlength="190" required value="<?=e($form['requester_email'])?>"></div>
                <div class="col-md-6"><label class="form-label fw-semibold">Phone / WhatsApp <span class="text-danger">*</span></label><input class="form-control" name="requester_phone" maxlength="80" required value="<?=e($form['requester_phone'])?>"></div>
                <div class="col-md-6"><label class="form-label fw-semibold">Preferred contact</label><select name="preferred_contact" class="form-select"><?php foreach(['whatsapp'=>'WhatsApp','phone'=>'Phone Call','email'=>'Email'] as $k=>$v): ?><option value="<?=e($k)?>" <?=$form['preferred_contact']===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select></div>
                <div class="col-12"><label class="form-label fw-semibold">Subject <span class="text-danger">*</span></label><input class="form-control" name="title" maxlength="255" required placeholder="Example: Quote for data recovery service" value="<?=e($form['title'])?>"></div>
                <div class="col-12"><label class="form-label fw-semibold">What do you need? <span class="text-danger">*</span></label><textarea class="form-control" name="description" rows="6" required minlength="10" maxlength="3000" placeholder="Describe your request, service needed, model/brand, problem, quantity, location, timeline or any important details."><?=e($form['description'])?></textarea></div>
                <div class="col-md-4"><label class="form-label fw-semibold">Urgency</label><select name="urgency" class="form-select"><?php foreach(['normal'=>'Normal','urgent'=>'Urgent','this_week'=>'This week','flexible'=>'Flexible'] as $k=>$v): ?><option value="<?=e($k)?>" <?=$form['urgency']===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select></div>
                <div class="col-md-4"><label class="form-label fw-semibold">Budget</label><input class="form-control" name="budget" maxlength="120" placeholder="Optional" value="<?=e($form['budget'])?>"></div>
                <div class="col-md-4"><label class="form-label fw-semibold">Preferred date</label><input class="form-control" type="date" name="preferred_date" value="<?=e($form['preferred_date'])?>"></div>
                <div class="col-12"><label class="form-label fw-semibold">Attachment <span class="text-muted small">optional</span></label><input class="form-control" type="file" name="attachment" accept=".jpg,.jpeg,.png,.webp,.pdf"><div class="form-text">Upload photo, screenshot or PDF. Max 8MB.</div></div>
              </div>

              <div class="alert alert-light border rounded-4 mt-4 small text-muted">By submitting, your request will be sent to the selected company. They can contact you using the details you provide.</div>
              <button class="btn btn-primary btn-lg rounded-pill px-4"><i class="bi bi-send me-1"></i>Send Request</button>
              <a class="btn btn-outline-secondary btn-lg rounded-pill px-4" href="<?=e($company ? base_url('company.php?id='.(int)$company['id']) : base_url('companies.php'))?>">Cancel</a>
            </form>
          </div>
        </div>
      </div>
    <?php endif; ?>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
