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

$id = (int)($_GET['id'] ?? $_POST['order_id'] ?? 0);
$order = mj_order_fetch($id);
if (!$order || !mj_order_can_view($order, (int)$u['id'])) {
    $pageTitle = 'Enquiry not found';
    include __DIR__.'/includes/header.php';
    echo '<section class="mj-section"><div class="container"><div class="mj-card p-5 text-center"><h1 class="fw-bold">Enquiry not found</h1><p class="text-muted">This record is not available or you do not have access.</p><a class="btn btn-primary" href="'.e(base_url('my-orders.php')).'">Back</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}

$uid = (int)$u['id'];
$isBuyer = $uid === (int)$order['buyer_id'];
$isSeller = $uid === (int)$order['seller_id'];
$old = (string)($order['status'] ?? 'processing');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));
    try {
        if ($action === 'upload_payment') {
            throw new Exception(mj_payment_scope_notice());
        } elseif ($action === 'mark_processing' && $isSeller) {
            q('UPDATE mj_orders SET status="processing", payment_status="payment_disabled", updated_at=NOW() WHERE id=?', [$id]);
            mj_order_timeline_add($id, 'seller', $uid, 'processing', 'Seller marked enquiry as in discussion.', $old, 'processing');
            $order['status'] = 'processing'; $order['last_action_by'] = $uid;
            mj_order_create_chat_event($order, 'Enquiry marked as in discussion.');
            flash('success', 'Enquiry updated.');
        } elseif ($action === 'mark_ready' && $isSeller) {
            q('UPDATE mj_orders SET status="ready", payment_status="payment_disabled", updated_at=NOW() WHERE id=?', [$id]);
            mj_order_timeline_add($id, 'seller', $uid, 'ready', 'Seller marked enquiry as ready/arranged.', $old, 'ready');
            $order['status'] = 'ready'; $order['last_action_by'] = $uid;
            mj_order_create_chat_event($order, 'Enquiry marked as ready/arranged.');
            flash('success', 'Enquiry marked ready.');
        } elseif ($action === 'mark_completed' && ($isSeller || $isBuyer)) {
            q('UPDATE mj_orders SET status="completed", payment_status="payment_disabled", completed_at=NOW(), updated_at=NOW() WHERE id=?', [$id]);
            mj_order_timeline_add($id, $isSeller ? 'seller' : 'buyer', $uid, 'completed', 'Enquiry completed.', $old, 'completed');
            $order['status'] = 'completed'; $order['last_action_by'] = $uid;
            mj_order_create_chat_event($order, 'Enquiry completed.');
            flash('success', 'Enquiry completed.');
        } elseif ($action === 'cancel' && ($isSeller || $isBuyer) && !in_array($old, ['completed','cancelled'], true)) {
            $reason = trim((string)($_POST['cancel_reason'] ?? ''));
            q('UPDATE mj_orders SET status="cancelled", payment_status="payment_disabled", cancelled_at=NOW(), updated_at=NOW() WHERE id=?', [$id]);
            mj_order_timeline_add($id, $isSeller ? 'seller' : 'buyer', $uid, 'cancelled', $reason ?: 'Enquiry cancelled.', $old, 'cancelled');
            $order['status'] = 'cancelled'; $order['last_action_by'] = $uid;
            mj_order_create_chat_event($order, 'Enquiry cancelled.'.($reason ? ' Reason: '.$reason : ''));
            flash('success', 'Enquiry cancelled.');
        } elseif ($action === 'dispute' && ($isSeller || $isBuyer)) {
            $reason = trim((string)($_POST['dispute_reason'] ?? ''));
            q('UPDATE mj_orders SET status="disputed", payment_status="payment_disabled", disputed_at=NOW(), updated_at=NOW() WHERE id=?', [$id]);
            mj_order_timeline_add($id, $isSeller ? 'seller' : 'buyer', $uid, 'disputed', $reason ?: 'Issue reported.', $old, 'disputed');
            $order['status'] = 'disputed'; $order['last_action_by'] = $uid;
            mj_order_create_chat_event($order, 'Issue reported for enquiry '.($order['order_number'] ?: '#'.$id));
            flash('success', 'Issue reported. Admin can review this record.');
        } else {
            flash('warning', 'This action is not available for this enquiry.');
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
    redirect('order-view.php?id='.$id);
}

$order = mj_order_fetch($id);
$timeline = [];
try { $timeline = all_rows('SELECT * FROM mj_order_timeline WHERE order_id=? ORDER BY id DESC', [$id]); } catch (Throwable $e) {}
$img = !empty($order['listing_image']) ? base_url($order['listing_image']) : asset('images/empty-state.svg');
$pageTitle = 'Enquiry '.($order['order_number'] ?: '#'.$id);
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <nav class="small mb-3"><a href="<?=e(base_url('my-orders.php'))?>">Enquiries</a> / <?=e($order['order_number'] ?: '#'.$id)?></nav>
    <div class="d-flex flex-wrap gap-2 mb-2">
      <span class="badge text-bg-<?=e(mj_order_status_class((string)$order['status']))?> rounded-pill"><?=e(mj_order_status_label((string)$order['status']))?></span>
      <span class="badge text-bg-secondary rounded-pill">No Customer Payment</span>
      <span class="mj-badge"><?=e(ucwords(str_replace('_',' ',(string)$order['source_type'])))?></span>
    </div>
    <h1 class="fw-bold display-5 mb-1"><?=e($order['order_number'] ?: 'Enquiry #'.$id)?></h1>
    <p class="text-muted mb-0">Review enquiry details, chat and timeline. Customer-to-seller payment is disabled on this website.</p>
  </div>
</section>

<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>
    <div class="alert alert-info rounded-4"><b><i class="bi bi-shield-check me-1"></i>Payment scope locked</b><br><?=e(mj_payment_scope_notice())?></div>
    <div class="row g-4">
      <div class="col-lg-8">
        <div class="mj-card p-4 mb-4">
          <div class="d-flex gap-3 flex-wrap">
            <img src="<?=e($img)?>" class="mj-offer-listing-img" alt="">
            <div class="flex-grow-1">
              <h3 class="fw-bold"><?=e($order['listing_title'] ?: 'Listing / service enquiry')?></h3>
              <p class="text-muted mb-2"><?=e($order['company_name'] ?: 'Marketplace seller')?> • <?=e($isBuyer ? 'Customer enquiry' : 'Seller enquiry')?></p>
              <div class="row g-3">
                <div class="col-md-4"><div class="mj-offer-kpi"><span>Agreed / quoted amount</span><b><?=money($order['total_amount'] ?: $order['amount'], $order['currency_code'] ?: 'SGD')?></b></div></div>
                <div class="col-md-4"><div class="mj-offer-kpi"><span>Customer</span><b><?=e($order['buyer_name'] ?: 'Customer')?></b></div></div>
                <div class="col-md-4"><div class="mj-offer-kpi"><span>Seller</span><b><?=e($order['seller_name'] ?: 'Seller')?></b></div></div>
              </div>
            </div>
          </div>
        </div>
        <div class="mj-card p-4">
          <h4 class="fw-bold mb-3">Timeline</h4>
          <?php if(!$timeline): ?><p class="text-muted mb-0">No timeline yet.</p><?php else: ?>
            <?php foreach($timeline as $t): ?>
              <div class="mj-timeline-item"><b><?=e(ucwords(str_replace('_',' ', $t['action'])))?></b><p class="text-muted mb-1"><?=e($t['note'] ?? '')?></p><small><?=e($t['created_at'])?></small></div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
      <div class="col-lg-4">
        <div class="mj-card p-4 mb-4">
          <h4 class="fw-bold">Actions</h4>
          <div class="d-grid gap-2 mb-3">
            <a class="btn btn-outline-primary" href="<?=e(mj_order_chat_url($order))?>"><i class="bi bi-chat-dots me-1"></i>Open Chat</a>
            <?php if(!empty($order['listing_id'])): ?><a class="btn btn-outline-primary" href="<?=e(base_url('listing.php?id='.(int)$order['listing_id']))?>">View Listing</a><?php endif; ?>
          </div>
          <div class="alert alert-secondary rounded-4"><b>No payment button</b><br>Customers cannot upload proof, pay by wallet, checkout, or pay sellers/users through MJ Marketplace.</div>
          <hr>
          <form method="post" class="d-grid gap-2">
            <?=csrf_input()?>
            <input type="hidden" name="order_id" value="<?=e($id)?>">
            <?php if($isSeller): ?>
              <button class="btn btn-outline-primary" name="action" value="mark_processing">Mark In Discussion</button>
              <button class="btn btn-outline-info" name="action" value="mark_ready">Mark Ready / Arranged</button>
            <?php endif; ?>
            <button class="btn btn-success" name="action" value="mark_completed">Mark Completed</button>
            <?php if(!in_array((string)$order['status'], ['completed','cancelled'], true)): ?>
              <input class="form-control" name="cancel_reason" placeholder="Cancel reason optional">
              <button class="btn btn-outline-danger" name="action" value="cancel">Cancel Enquiry</button>
            <?php endif; ?>
            <input class="form-control" name="dispute_reason" placeholder="Issue reason optional">
            <button class="btn btn-danger" name="action" value="dispute">Report Issue</button>
          </form>
        </div>
        <div class="alert alert-warning rounded-4"><b><i class="bi bi-exclamation-triangle me-1"></i>Safety reminder</b><br>MJ Marketplace does not collect customer-to-seller payments. Confirm details carefully and never share OTP, bank login or passwords.</div>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
