<?php
declare(strict_types=1);
/**
 * modules/quotes/convert_to_booking.php
 *
 * Convert a Quote → Booking.
 *
 * Flow:
 *  1) Load quote + lines + company + (optional) partner commission rule
 *  2) Show a light “conversion” form (lets you pick pickup date/time + tweak notes)
 *  3) On POST:
 *      - Create a new booking (mirrors modules/bookings/add.php insert logic)
 *      - Insert one booking_vehicles row per quote line (client_price = line_total)
 *      - Compute partner commission (fixed/percent) if a partner is attached
 *      - Mark quote as 'accepted'
 *      - Redirect to bookings/edit.php for any further changes
 *
 * This file is self-contained and does NOT modify add.php.
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops','sales']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$qid = (int)($_GET['id'] ?? $_GET['quote_id'] ?? $_POST['id'] ?? 0);
if ($qid <= 0) redirect(url_modules('quotes/list.php'));

$errors = [];
$notice = null;

/* ------------------------------------------------------------
 * 1) Load quote + lines + partner (for commission rule)
 * ------------------------------------------------------------ */
$qStmt = db()->prepare("
  SELECT q.*,
         p.name AS partner_name, p.commission_type, p.commission_value
    FROM quotes q
    LEFT JOIN partners p ON p.id = q.partner_id
   WHERE q.id = :id AND q.company_id = :cid
   LIMIT 1
");
$qStmt->execute([':id' => $qid, ':cid' => $cid]);
$quote = $qStmt->fetch();
if (!$quote) redirect(url_modules('quotes/list.php'));

$lStmt = db()->prepare("
  SELECT id, description, quantity, unit_price, line_total
    FROM quote_lines
   WHERE quote_id = :qid
   ORDER BY id ASC
");
$lStmt->execute([':qid' => $qid]);
$lines = $lStmt->fetchAll();

/* Totals */
$subTotal = 0.0;
foreach ($lines as $ln) {
  $qty  = (int)($ln['quantity'] ?? 1);
  $unit = (float)($ln['unit_price'] ?? 0);
  $lt   = isset($ln['line_total']) && $ln['line_total'] !== null && $ln['line_total'] !== ''
            ? (float)$ln['line_total'] : ($qty * $unit);
  $subTotal += $lt;
}
$discount = (float)($quote['discount'] ?? 0.0);
$grand    = max(0.0, $subTotal - $discount);

$quoteRef    = (string)($quote['quote_ref'] ?? ('Q-' . (int)$quote['id']));
$clientName  = (string)($quote['client_name'] ?? '');
$clientEmail = (string)($quote['client_email'] ?? '');
$partnerId   = !empty($quote['partner_id']) ? (int)$quote['partner_id'] : null;
$partnerRule = [
  'type'  => $quote['commission_type'] ?? null,
  'value' => $quote['commission_value'] ?? null,
];

/* Default commission suggestion (only for partner-attached quotes) */
$commissionSuggested = 0.00;
if ($partnerId && ($partnerRule['type'] === 'fixed' || $partnerRule['type'] === 'percent')) {
  if ($partnerRule['type'] === 'fixed') {
    $commissionSuggested = (float)$partnerRule['value'];
  } else {
    $pct = max(0.0, min(100.0, (float)$partnerRule['value']));
    $commissionSuggested = round(($pct / 100.0) * $grand, 2);
  }
}

/* Build a default notes text with the quote lines */
$notesDefault = "Converted from Quote {$quoteRef}.\n";
foreach ($lines as $i => $ln) {
  $qty  = (int)($ln['quantity'] ?? 1);
  $unit = (float)($ln['unit_price'] ?? 0);
  $lt   = isset($ln['line_total']) && $ln['line_total'] !== null && $ln['line_total'] !== ''
            ? (float)$ln['line_total'] : ($qty * $unit);
  $desc = trim((string)($ln['description'] ?? ''));
  $notesDefault .= sprintf(
    "- Line %d: %s | Qty %d | Unit £%.2f | Total £%.2f\n",
    $i+1, $desc !== '' ? $desc : 'Item', $qty, $unit, $lt
  );
}

/* ------------------------------------------------------------
 * 2) Handle POST: Create booking & rows, accept quote, redirect
 * ------------------------------------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $pickup_date  = trim((string)($_POST['pickup_date'] ?? ''));
    $pickup_time  = trim((string)($_POST['pickup_time'] ?? ''));
    $booking_type = in_array(($_POST['booking_type'] ?? ''), ['Transfer','As Directed'], true) ? $_POST['booking_type'] : 'Transfer';
    $hours        = ($_POST['hours'] ?? '') !== '' ? (float)$_POST['hours'] : null;
    $commission   = ($_POST['partner_commission_amount'] ?? '') !== '' ? (float)$_POST['partner_commission_amount'] : $commissionSuggested;
    $notes        = trim((string)($_POST['notes'] ?? $notesDefault));

    // We keep pickup date/time optional; can be edited later
    $pickup_date = $pickup_date !== '' ? $pickup_date : null;
    $pickup_time = $pickup_time !== '' ? $pickup_time : null;

    // Generate a booking reference using your project helper (already updated in your system)
    $ref = generate_booking_ref($cid);

    db()->beginTransaction();

    /* Insert booking (mirrors add.php structure, minimal fields) */
    $ins = db()->prepare("
      INSERT INTO bookings (
        company_id, booking_ref, partner_id, booking_type, hours,
        client_name, client_email,
        pickup_date, pickup_time,
        pax_count, luggage_count,
        pickup_address, via, dropoff_address, flight_number,
        notes, status,
        total_client_price, total_driver_price,
        client_parking_fee, client_waiting_fee, driver_parking_fee, driver_waiting_fee,
        partner_commission_amount,
        created_by, created_at
      )
      VALUES (
        :cid, :ref, :pid, :bt, :hrs,
        :cn, :ce,
        :pd, :pt,
        0, 0,
        NULL, NULL, NULL, NULL,
        :notes, 'New',
        :tc, 0,
        0, 0, 0, 0,
        :pc,
        :uid, NOW()
      )
    ");
    $ins->execute([
      ':cid'  => $cid,
      ':ref'  => $ref,
      ':pid'  => $partnerId,
      ':bt'   => $booking_type,
      ':hrs'  => $hours,
      ':cn'   => $clientName !== '' ? $clientName : null,
      ':ce'   => $clientEmail !== '' ? $clientEmail : null,
      ':pd'   => $pickup_date,
      ':pt'   => $pickup_time,
      ':notes'=> $notes !== '' ? $notes : null,
      ':tc'   => $grand,
      ':pc'   => $commission,
      ':uid'  => $user['id'] ?? null,
    ]);
    $bid = (int)db()->lastInsertId();

    /* Insert booking_vehicles rows — one per quote line, client_price only */
    $insBV = db()->prepare("
      INSERT INTO booking_vehicles
        (booking_id, vehicle_id, vehicle_type, vehicle_reg_no, driver_id, driver_price, client_price, sequence_order)
      VALUES
        (:bid, :vid, :vt, :vr, :did, :dp, :cp, :seq)
    ");
    $seq = 1;
    foreach ($lines as $ln) {
      $qty  = (int)($ln['quantity'] ?? 1);
      $unit = (float)($ln['unit_price'] ?? 0);
      $lt   = isset($ln['line_total']) && $ln['line_total'] !== null && $ln['line_total'] !== ''
                ? (float)$ln['line_total'] : ($qty * $unit);

      // Create one row per line; if you prefer, multiply rows by qty or keep as a single total
      $insBV->execute([
        ':bid' => $bid,
        ':vid' => null,
        ':vt'  => null,
        ':vr'  => null,
        ':did' => null,
        ':dp'  => 0.00,
        ':cp'  => $lt,
        ':seq' => $seq++
      ]);
    }

    /* Mark quote as accepted */
    db()->prepare("UPDATE quotes SET status='accepted', updated_at=NOW() WHERE id=:id AND company_id=:cid")
       ->execute([':id'=>$qid, ':cid'=>$cid]);

    db()->commit();

    audit_log('quote.convert_to_booking', 'quote', $qid, [
      'booking_id' => $bid,
      'booking_ref'=> $ref,
      'client_total' => $grand,
      'commission' => $commission
    ]);

    // Go to the new booking for any fine-tuning (assign driver/vehicle, addresses, etc.)
    redirect(url_modules('bookings/edit.php') . '?id=' . $bid);

  } catch (Throwable $e) {
    if (db()->inTransaction()) db()->rollBack();
    $errors[] = (APP_ENV === 'dev') ? $e->getMessage() : 'Unable to convert quote to booking.';
  }
}

/* ------------------------------------------------------------
 * 3) Render: Conversion form
 * ------------------------------------------------------------ */
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Convert Quote → Booking</h1>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('quotes/view.php?id='.(int)$qid)) ?>">Back to Quote</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="alert alert-danger"><ul class="mb-0"><?php foreach($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div><?php endif; ?>

<div class="row g-3">
  <div class="col-12 col-lg-7">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Quote Summary</h2>
        <div class="row g-2">
          <div class="col-md-6">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Quote Ref</div>
              <div class="fw-bold"><?= e($quoteRef) ?></div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Client</div>
              <div class="fw-bold"><?= e($clientName ?: '—') ?></div>
              <div class="small text-muted"><?= e($clientEmail ?: '') ?></div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Subtotal</div>
              <div class="fw-bold">£<?= number_format($subTotal, 2) ?></div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Discount</div>
              <div class="fw-bold">£<?= number_format($discount, 2) ?></div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Grand Total</div>
              <div class="fw-bold">£<?= number_format($grand, 2) ?></div>
            </div>
          </div>
        </div>

        <hr class="my-3">
        <h2 class="h6 text-uppercase text-muted mb-2">Line Items</h2>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:56px;">#</th>
                <th>Description</th>
                <th class="text-end" style="width:80px;">Qty</th>
                <th class="text-end" style="width:110px;">Unit £</th>
                <th class="text-end" style="width:120px;">Total £</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($lines): foreach ($lines as $i=>$ln):
                $qty  = (int)($ln['quantity'] ?? 1);
                $unit = (float)($ln['unit_price'] ?? 0);
                $lt   = isset($ln['line_total']) && $ln['line_total'] !== null && $ln['line_total'] !== ''
                          ? (float)$ln['line_total'] : ($qty * $unit);
              ?>
              <tr>
                <td><?= (int)($i+1) ?></td>
                <td><?= nl2br(e((string)$ln['description'])) ?></td>
                <td class="text-end"><?= number_format($qty, 0) ?></td>
                <td class="text-end"><?= number_format($unit, 2) ?></td>
                <td class="text-end"><?= number_format($lt, 2) ?></td>
              </tr>
              <?php endforeach; else: ?>
              <tr><td colspan="5" class="text-muted">No items.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>

      </div>
    </div>
  </div>

  <div class="col-12 col-lg-5">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Booking Details</h2>
        <form method="post" autocomplete="off">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="id" value="<?= (int)$qid ?>">

          <div class="row g-2">
            <div class="col-md-6">
              <label class="form-label">Pickup Date</label>
              <input type="date" class="form-control" name="pickup_date" value="<?= e($_POST['pickup_date'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">Pickup Time</label>
              <input type="time" class="form-control" name="pickup_time" value="<?= e($_POST['pickup_time'] ?? '') ?>">
            </div>

            <div class="col-md-6">
              <label class="form-label">Type</label>
              <select class="form-select" name="booking_type">
                <?php $bt = $_POST['booking_type'] ?? 'Transfer'; ?>
                <option value="Transfer"   <?= $bt==='Transfer'?'selected':''; ?>>Transfer</option>
                <option value="As Directed"<?= $bt==='As Directed'?'selected':''; ?>>As Directed</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Hours (if As Directed)</label>
              <input type="number" step="0.5" class="form-control" name="hours" value="<?= e($_POST['hours'] ?? '') ?>">
            </div>

            <div class="col-md-6">
              <label class="form-label">Partner Commission (£)</label>
              <input type="number" step="0.01" class="form-control" name="partner_commission_amount"
                     value="<?= e($_POST['partner_commission_amount'] ?? number_format($commissionSuggested, 2, '.', '')) ?>">
              <div class="form-text">
                <?php if ($partnerId && $partnerRule['type']): ?>
                  Suggested from <?= e($quote['partner_name']) ?>:
                  <?= e($partnerRule['type']==='percent' ? $partnerRule['value'].'%' : '£'.$partnerRule['value']) ?>
                <?php else: ?>
                  No partner commission on this quote.
                <?php endif; ?>
              </div>
            </div>

            <div class="col-12">
              <label class="form-label">Notes</label>
              <textarea class="form-control" name="notes" rows="6"><?= e($_POST['notes'] ?? $notesDefault) ?></textarea>
            </div>

            <div class="col-12 mt-2 d-flex gap-2">
              <button class="btn btn-dark">Create Booking</button>
              <a class="btn btn-outline-secondary" href="<?= e(url_modules('quotes/view.php?id='.(int)$qid)) ?>">Cancel</a>
            </div>
          </div>
        </form>

        <hr class="my-3">
        <div class="small text-muted">
          After creation, you'll be redirected to the booking editor where you can assign vehicles/drivers and add addresses.
        </div>
      </div>
    </div>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
