<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
verify_csrf();
mj_quote_ensure_schema();
if (function_exists('mj_realtime_chat_ensure_schema')) { mj_realtime_chat_ensure_schema(); }

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$quote = mj_quote_fetch($id);
if (!$quote || !mj_quote_can_view($quote, $u, null)) {
    flash('error', 'Quote request not found or you do not have permission to view it.');
    redirect('my-quotes.php');
}
$isCompanyOwner = (int)($quote['company_user_id'] ?? 0) === (int)$u['id'];
$isCustomer = (int)($quote['user_id'] ?? 0) === (int)$u['id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));
    try {
        if ($isCompanyOwner && $action === 'send_quote') {
            $amount = trim((string)($_POST['amount'] ?? ''));
            $currency = trim((string)($_POST['currency_code'] ?? ($quote['currency_code'] ?: 'SGD')));
            $validUntil = trim((string)($_POST['valid_until'] ?? ''));
            $message = trim((string)($_POST['message'] ?? ''));
            if ($message === '') { throw new Exception('Please enter your quotation message.'); }
            if ($amount !== '' && !is_numeric($amount)) { throw new Exception('Quotation amount must be a valid number.'); }
            $old = (string)($quote['status'] ?? 'new');
            q('UPDATE mj_quote_requests SET status="quoted", quoted_amount=?, currency_code=?, quote_message=?, valid_until=?, replied_at=NOW(), updated_at=NOW() WHERE id=?', [$amount !== '' ? (float)$amount : null, $currency ?: 'SGD', $message, $validUntil ?: null, $id]);
            q('INSERT INTO mj_quote_replies(quote_id,sender_type,sender_user_id,message,amount,currency_code,valid_until,created_at) VALUES(?,?,?,?,?,?,?,NOW())', [$id,'company',(int)$u['id'],$message,$amount !== '' ? (float)$amount : null,$currency ?: 'SGD',$validUntil ?: null]);
            $replyId = (int)db()->lastInsertId();
            try { $att = mj_quote_upload_attachment($id, (int)$u['id'], 'attachment'); if ($att) { q('UPDATE mj_quote_replies SET attachment_path=? WHERE id=?', [$att,$replyId]); } } catch (Throwable $e) { flash('warning', $e->getMessage()); }
            mj_quote_timeline_add($id,'company',(int)$u['id'],'quoted','Quotation reply sent.',$old,'quoted');
            mj_quote_safe_notify_user((int)($quote['user_id'] ?? 0), 'quote_reply', 'Quotation received', (string)$quote['title'], 'quote-view.php?id='.$id, 'high');
            flash('success', 'Quotation sent to customer.');
            redirect('quote-view.php?id='.$id);
        }

        if ($isCompanyOwner && $action === 'update_status') {
            $status = trim((string)($_POST['status'] ?? 'reviewed'));
            $note = trim((string)($_POST['internal_note'] ?? ''));
            $allowed = array_keys(mj_quote_statuses());
            if (!in_array($status, $allowed, true)) { throw new Exception('Invalid quote status.'); }
            $old = (string)($quote['status'] ?? 'new');
            $closedAt = in_array($status, ['won','lost','spam','closed'], true) ? ', closed_at=NOW()' : '';
            q('UPDATE mj_quote_requests SET status=?, internal_note=?, updated_at=NOW()'.$closedAt.' WHERE id=?', [$status, $note ?: null, $id]);
            mj_quote_timeline_add($id,'company',(int)$u['id'],'status_update',$note,$old,$status);
            flash('success', 'Quote status updated.');
            redirect('quote-view.php?id='.$id);
        }

        if ($isCustomer && in_array($action, ['accept_quote','reject_quote'], true)) {
            $new = $action === 'accept_quote' ? 'accepted' : 'rejected';
            $old = (string)($quote['status'] ?? 'new');
            q('UPDATE mj_quote_requests SET status=?, '.($new==='accepted'?'accepted_at=NOW(),':'closed_at=NOW(),').' updated_at=NOW() WHERE id=?', [$new,$id]);
            mj_quote_timeline_add($id,'customer',(int)$u['id'],$new,$new==='accepted'?'Customer accepted quotation.':'Customer rejected quotation.',$old,$new);
            if ($new === 'accepted') {
                $freshQuote = mj_quote_fetch($id);
                if ($freshQuote) { $orderId = mj_order_create_from_quote($freshQuote); if ($orderId) { mj_quote_timeline_add($id,'system',0,'enquiry_created','Enquiry record created from accepted quotation. No customer payment is collected by MJ Marketplace.'); } }
            }
            mj_quote_safe_notify_user((int)($quote['company_user_id'] ?? 0), 'quote_status', 'Quote '.mj_quote_status_label($new), (string)$quote['title'], 'quote-view.php?id='.$id, 'normal');
            flash('success', $new==='accepted' ? 'Quotation accepted. Enquiry record created and company has been notified. No payment is collected by MJ Marketplace.' : 'Quotation rejected. The company has been notified.');
            redirect('quote-view.php?id='.$id);
        }

        if ($action === 'customer_message' && $isCustomer) {
            $message = trim((string)($_POST['message'] ?? ''));
            if ($message === '') { throw new Exception('Please type a message.'); }
            q('INSERT INTO mj_quote_replies(quote_id,sender_type,sender_user_id,message,created_at) VALUES(?,?,?,?,NOW())', [$id,'customer',(int)$u['id'],$message]);
            mj_quote_timeline_add($id,'customer',(int)$u['id'],'message','Customer added a message.');
            flash('success','Message added to quote.');
            redirect('quote-view.php?id='.$id);
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
    $quote = mj_quote_fetch($id);
}

$replies = safe_all_rows_public('SELECT r.*, u.name sender_name FROM mj_quote_replies r LEFT JOIN mj_users u ON u.id=r.sender_user_id WHERE r.quote_id=? ORDER BY r.id ASC', [$id]);
$timeline = safe_all_rows_public('SELECT * FROM mj_quote_timeline WHERE quote_id=? ORDER BY id DESC LIMIT 30', [$id]);
$attachments = safe_all_rows_public('SELECT * FROM mj_quote_attachments WHERE quote_id=? ORDER BY id DESC', [$id]);
$chatId = mj_quote_create_or_open_chat($quote);
$chatUrl = $chatId ? base_url('chat.php?listing_id='.(int)($quote['listing_id']??0).'&company_id='.(int)($quote['company_id']??0).'&seller_id='.(int)($quote['company_user_id']??0).'&buyer_id='.(int)($quote['user_id']??0)) : '';
$pageTitle = 'Quote #'.$id;
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero"><div class="container"><nav class="small mb-2"><a href="<?=base_url('/')?>">Home</a> / <a href="<?=base_url($isCompanyOwner?'company-quotes.php':'my-quotes.php')?>">Quotes</a> / Quote #<?=e($id)?></nav><span class="mj-badge mb-2"><i class="bi bi-receipt"></i> <?=e(mj_quote_status_label((string)$quote['status']))?></span><h1 class="fw-bold display-6 mb-1"><?=e($quote['title'] ?? 'Quotation request')?></h1><p class="text-muted mb-0">Manage quotation details, replies, status and conversation in one place.</p></div></section>
<section class="mj-section"><div class="container"><?php show_flash(); ?><div class="row g-4 align-items-start"><div class="col-lg-8">
  <div class="mj-card p-4 mb-4"><div class="d-flex flex-wrap justify-content-between gap-2"><div><span class="badge text-bg-<?=e(mj_quote_status_class((string)$quote['status']))?> rounded-pill mb-2"><?=e(mj_quote_status_label((string)$quote['status']))?></span><h3 class="fw-bold mb-1">Request Details</h3><p class="text-muted mb-0">Submitted <?=e(local_datetime($quote['created_at'] ?? '', 'UTC'))?></p></div><div class="text-lg-end"><div class="small text-muted">Lead quality</div><b><?=e(mj_quote_score_label((int)($quote['lead_score'] ?? 0)))?> • <?=e((int)($quote['lead_score'] ?? 0))?>%</b></div></div><hr><p><?=nl2br(e($quote['description'] ?? ''))?></p><div class="row g-3 mt-2"><div class="col-md-4"><div class="mj-quote-mini"><span>Urgency</span><b><?=e(mj_quote_urgency_label((string)($quote['urgency'] ?? 'normal')))?></b></div></div><div class="col-md-4"><div class="mj-quote-mini"><span>Budget</span><b><?=e($quote['budget'] ?: '-')?></b></div></div><div class="col-md-4"><div class="mj-quote-mini"><span>Preferred date</span><b><?=e($quote['preferred_date'] ?: '-')?></b></div></div></div></div>

  <?php if($quote['quoted_amount'] || $quote['quote_message']): ?><div class="mj-card p-4 mb-4 border-success"><span class="mj-badge good mb-2"><i class="bi bi-send-check"></i> Quotation Sent</span><h3 class="fw-bold"><?= $quote['quoted_amount'] ? money($quote['quoted_amount'], $quote['currency_code'] ?: 'SGD') : 'Quotation reply' ?></h3><p><?=nl2br(e($quote['quote_message'] ?? ''))?></p><?php if($quote['valid_until']): ?><p class="text-muted mb-0">Valid until <?=e($quote['valid_until'])?></p><?php endif; ?><?php if($isCustomer && !in_array($quote['status'], ['accepted','rejected','won','lost','closed'], true)): ?><form method="post" class="d-flex flex-wrap gap-2 mt-3"><?=csrf_input()?><button name="action" value="accept_quote" class="btn btn-success rounded-pill"><i class="bi bi-check2-circle me-1"></i>Accept Quote</button><button name="action" value="reject_quote" class="btn btn-outline-danger rounded-pill"><i class="bi bi-x-circle me-1"></i>Reject Quote</button></form><?php endif; ?></div><?php endif; ?>

  <div class="mj-card p-4 mb-4"><h3 class="fw-bold">Replies & Timeline</h3><?php if(!$replies): ?><p class="text-muted">No replies yet.</p><?php else: foreach($replies as $r): ?><div class="mj-quote-reply"><div class="d-flex justify-content-between"><b><?=e(ucfirst($r['sender_type']))?> <?=!empty($r['sender_name'])?'• '.e($r['sender_name']):''?></b><small class="text-muted"><?=e(local_datetime($r['created_at'] ?? '', 'UTC'))?></small></div><p class="mb-1"><?=nl2br(e($r['message']))?></p><?php if($r['amount']): ?><span class="mj-badge good"><?=money($r['amount'],$r['currency_code'] ?: 'SGD')?></span><?php endif; ?><?php if($r['attachment_path']): ?><a class="small ms-2" target="_blank" href="<?=e(base_url($r['attachment_path']))?>">View attachment</a><?php endif; ?></div><?php endforeach; endif; ?></div>

  <?php if($isCompanyOwner): ?><div class="mj-card p-4 mb-4"><h3 class="fw-bold">Send quotation reply</h3><form method="post" enctype="multipart/form-data"><input type="hidden" name="action" value="send_quote"><?=csrf_input()?><div class="row g-3"><div class="col-md-4"><label class="form-label">Amount</label><input class="form-control" name="amount" type="number" step="0.01" min="0" value="<?=e($quote['quoted_amount'] ?? '')?>"></div><div class="col-md-4"><label class="form-label">Currency</label><input class="form-control" name="currency_code" maxlength="10" value="<?=e($quote['currency_code'] ?: 'SGD')?>"></div><div class="col-md-4"><label class="form-label">Valid until</label><input class="form-control" name="valid_until" type="date" value="<?=e($quote['valid_until'] ?? '')?>"></div><div class="col-12"><label class="form-label">Message <span class="text-danger">*</span></label><textarea class="form-control" name="message" rows="5" required placeholder="Explain your quotation, terms, warranty, timeline or what details you still need."><?=e($quote['quote_message'] ?? '')?></textarea></div><div class="col-12"><label class="form-label">Attachment</label><input class="form-control" type="file" name="attachment" accept=".jpg,.jpeg,.png,.webp,.pdf"></div></div><button class="btn btn-primary rounded-pill mt-3"><i class="bi bi-send me-1"></i>Send Quote</button></form></div><?php endif; ?>

  <?php if($isCustomer): ?><div class="mj-card p-4"><h3 class="fw-bold">Ask a question</h3><form method="post"><input type="hidden" name="action" value="customer_message"><?=csrf_input()?><textarea class="form-control" name="message" rows="4" required placeholder="Ask a question about this quotation..."></textarea><button class="btn btn-primary rounded-pill mt-3">Send Message</button></form></div><?php endif; ?>
</div><div class="col-lg-4">
  <div class="mj-card p-4 mb-4"><h5 class="fw-bold">Company</h5><p class="mb-1"><b><?=e($quote['company_name'] ?? 'Company')?></b></p><p class="text-muted small mb-3"><?=e($quote['country_name'] ?? '')?> <?=!empty($quote['city_name'])?'• '.e($quote['city_name']):''?></p><?php if($quote['listing_title']): ?><p class="small"><i class="bi bi-box-seam me-1"></i><?=e($quote['listing_title'])?></p><?php endif; ?><a class="btn btn-outline-primary w-100 rounded-pill" href="<?=e(base_url('company.php?id='.(int)$quote['company_id']))?>">View Company</a><?php if($chatUrl): ?><a class="btn btn-primary w-100 rounded-pill mt-2" href="<?=e($chatUrl)?>"><i class="bi bi-chat-dots me-1"></i>Open Chat</a><?php endif; ?></div>
  <div class="mj-card p-4 mb-4"><h5 class="fw-bold">Customer contact</h5><p class="mb-1"><b><?=e($quote['requester_name'])?></b></p><p class="small text-muted mb-1"><?=e($quote['requester_email'])?></p><p class="small text-muted mb-0"><?=e($quote['requester_phone'])?> • <?=e(ucfirst((string)$quote['preferred_contact']))?></p></div>
  <?php if($attachments): ?><div class="mj-card p-4 mb-4"><h5 class="fw-bold">Attachments</h5><?php foreach($attachments as $a): ?><a target="_blank" class="d-block mb-2" href="<?=e(base_url($a['file_path']))?>"><i class="bi bi-paperclip me-1"></i><?=e($a['original_name'] ?: basename($a['file_path']))?></a><?php endforeach; ?></div><?php endif; ?>
  <?php if($isCompanyOwner): ?><div class="mj-card p-4"><h5 class="fw-bold">Status & notes</h5><form method="post"><input type="hidden" name="action" value="update_status"><?=csrf_input()?><label class="form-label">Status</label><select class="form-select" name="status"><?php foreach(mj_quote_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$quote['status']===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select><label class="form-label mt-3">Private note</label><textarea class="form-control" name="internal_note" rows="4"><?=e($quote['internal_note'] ?? '')?></textarea><button class="btn btn-outline-primary rounded-pill mt-3">Update Status</button></form></div><?php endif; ?>
</div></div></div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
