<?php
declare(strict_types=1);
/**
 * modules/quotes/edit.php
 *
 * Edit an existing Quote (header + dynamic line items).
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch quote + lines + reference data
 *  3) Helpers (column checks, ref generator)
 *  4) Handle POST (validate, UPDATE, reinsert lines)
 *  5) Render form (dynamic rows + live totals)
 */

////////////////////////////////////////////////////////////////
// 1) Bootstrap & guards
////////////////////////////////////////////////////////////////
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'));

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

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch quote + lines + reference data
////////////////////////////////////////////////////////////////
$quoteStmt = db()->prepare("
  SELECT *
    FROM quotes
   WHERE id=:id AND company_id=:cid
   LIMIT 1
");
$quoteStmt->execute([':id'=>$id, ':cid'=>$cid]);
$quote = $quoteStmt->fetch();
if (!$quote) redirect('list.php');

$linesStmt = db()->prepare("
  SELECT *
    FROM quote_lines
   WHERE quote_id=:qid
   ORDER BY id ASC
");
$linesStmt->execute([':qid'=>$id]);
$lines = $linesStmt->fetchAll();

$partners = [];
try {
  $ps = db()->prepare("SELECT id, name FROM partners WHERE company_id=:cid ORDER BY name");
  $ps->execute([':cid'=>$cid]);
  $partners = $ps->fetchAll();
} catch (Throwable $e) { /* ignore */ }

$corporates = [];
try {
  $cs = db()->prepare("SELECT id, name FROM corporates WHERE company_id=:cid ORDER BY name");
  $cs->execute([':cid'=>$cid]);
  $corporates = $cs->fetchAll();
} catch (Throwable $e) { /* ignore */ }

////////////////////////////////////////////////////////////////
// 3) Helpers (column checks, ref)
////////////////////////////////////////////////////////////////
function q_col_exists(string $table, string $column): bool {
  try {
    $q = db()->prepare("
      SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
       WHERE TABLE_SCHEMA = DATABASE()
         AND TABLE_NAME   = :t
         AND COLUMN_NAME  = :c
       LIMIT 1
    ");
    $q->execute([':t'=>$table, ':c'=>$column]);
    return (bool)$q->fetchColumn();
  } catch (Throwable $e) {
    return false;
  }
}

/** Generate a unique-ish quote_ref like "BHC-<ddmmyyyy>-<6 digits>" if column exists. */
function gen_quote_ref_if_supported(int $companyId): ?string {
  if (!q_col_exists('quotes','quote_ref')) return null;
  $date = date('dmY');
  for ($i=0; $i<5; $i++) {
    $suffix = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    $ref = "BHC-{$date}-{$suffix}";
    $dup = db()->prepare("SELECT id FROM quotes WHERE company_id=:cid AND quote_ref=:r LIMIT 1");
    $dup->execute([':cid'=>$companyId, ':r'=>$ref]);
    if (!$dup->fetch()) return $ref;
  }
  return "BHC-{$date}-".substr((string)time(), -6);
}

$hasQuoteRefCol    = q_col_exists('quotes','quote_ref');
$hasVehicleTypeCol = q_col_exists('quote_lines','vehicle_type');

////////////////////////////////////////////////////////////////
// 4) Handle POST (validate, UPDATE, reinsert lines)
////////////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $quote_ref   = trim((string)($_POST['quote_ref'] ?? ''));
    $client_name = trim((string)($_POST['client_name'] ?? ''));
    $client_email= trim((string)($_POST['client_email'] ?? ''));
    $partner_id  = (int)($_POST['partner_id'] ?? 0) ?: null;
    $corporate_id= (int)($_POST['corporate_id'] ?? 0) ?: null;
    $quote_date  = (string)($_POST['quote_date'] ?? ($quote['quote_date'] ?? date('Y-m-d')));
    $discount    = (float)($_POST['discount'] ?? 0);
    $notes       = trim((string)($_POST['notes'] ?? ''));
    $status      = (string)($_POST['status'] ?? ($quote['status'] ?? 'draft'));
    if (!in_array($status, ['draft','sent','accepted','rejected'], true)) $status = 'draft';

    if ($client_name === '') $errors[] = 'Client name is required.';
    if ($quote_date === '')  $quote_date = date('Y-m-d');

    // Lines
    $desc = $_POST['line_desc']       ?? [];
    $veh  = $_POST['line_vehicle']    ?? [];
    $qty  = $_POST['line_qty']        ?? [];
    $unit = $_POST['line_unit_price'] ?? [];

    // Validate at least one meaningful line
    $hasAnyLine = false;
    $subtotal   = 0.0;
    $lineCount  = max(count($desc), count($qty), count($unit), count($veh));
    for ($i=0; $i<$lineCount; $i++) {
      $d = isset($desc[$i]) ? trim((string)$desc[$i]) : '';
      $q = isset($qty[$i])  ? (int)$qty[$i] : 0;
      $u = isset($unit[$i]) ? (float)$unit[$i] : 0.0;
      if ($d !== '' || ($q>0 && $u>0)) {
        $hasAnyLine = true;
        $subtotal  += max(1, $q) * max(0, $u);
      }
    }
    if (!$hasAnyLine) $errors[] = 'Please add at least one line item.';

    // quote_ref uniqueness (if column exists)
    if ($hasQuoteRefCol) {
      if ($quote_ref === '') $quote_ref = gen_quote_ref_if_supported($cid) ?? '';
      if ($quote_ref !== '') {
        $dup = db()->prepare("SELECT id FROM quotes WHERE company_id=:cid AND quote_ref=:r AND id<>:id LIMIT 1");
        $dup->execute([':cid'=>$cid, ':r'=>$quote_ref, ':id'=>$id]);
        if ($dup->fetch()) $errors[] = 'Quote reference already exists. Please change it.';
      }
    } else {
      $quote_ref = '';
    }

    if (!$errors) {
      db()->beginTransaction();

      // Build UPDATE dynamically to avoid schema mismatch trouble
      $set  = [
        "partner_id = :pid",
        "corporate_id = :coid",
        "client_name = :cn",
        "client_email = :ce",
        "quote_date = :qd",
        "discount = :disc",
        "status = :st",
        "notes = :notes",
        "updated_at = NOW()",
      ];
      $args = [
        ':pid'  => $partner_id,
        ':coid' => $corporate_id,
        ':cn'   => $client_name,
        ':ce'   => ($client_email !== '' ? $client_email : null),
        ':qd'   => $quote_date,
        ':disc' => $discount,
        ':st'   => $status,
        ':notes'=> ($notes !== '' ? $notes : null),
        ':id'   => $id,
        ':cid'  => $cid,
      ];
      if ($hasQuoteRefCol) {
        $set[]        = "quote_ref = :qref";
        $args[':qref']= ($quote_ref !== '' ? $quote_ref : null);
      }

      $upd = db()->prepare("UPDATE quotes SET ".implode(', ', $set)." WHERE id=:id AND company_id=:cid LIMIT 1");
      $upd->execute($args);

      // Reinsert lines
      $del = db()->prepare("DELETE FROM quote_lines WHERE quote_id=:qid");
      $del->execute([':qid'=>$id]);

      $insSql = "
        INSERT INTO quote_lines (quote_id, description, quantity, unit_price, line_total".
        ($hasVehicleTypeCol ? ", vehicle_type" : "").
        ") VALUES (:qid, :d, :q, :u, :t".
        ($hasVehicleTypeCol ? ", :vt" : "").
        ")
      ";
      $ins = db()->prepare($insSql);

      for ($i=0; $i<$lineCount; $i++) {
        $d = isset($desc[$i]) ? trim((string)$desc[$i]) : '';
        $q = isset($qty[$i])  ? (int)$qty[$i] : 0;
        $u = isset($unit[$i]) ? (float)$unit[$i] : 0.0;
        $v = isset($veh[$i])  ? trim((string)$veh[$i])  : '';

        if ($d === '' && $q <= 0 && $u <= 0) continue;

        $q = max(1, $q);
        $u = max(0.0, $u);
        $t = $q * $u;

        $params = [
          ':qid' => $id,
          ':d'   => $d !== '' ? $d : null,
          ':q'   => $q,
          ':u'   => $u,
          ':t'   => $t,
        ];
        if ($hasVehicleTypeCol) $params[':vt'] = ($v !== '' ? $v : null);
        $ins->execute($params);
      }

      db()->commit();
      audit_log('quote.update','quote',$id,['fields'=>'all']);
      $notice = 'Quote saved successfully.';

      // Refresh in-memory model
      $quoteStmt->execute([':id'=>$id, ':cid'=>$cid]);
      $quote = $quoteStmt->fetch();
      $linesStmt->execute([':qid'=>$id]);
      $lines = $linesStmt->fetchAll();
    }
  } catch (Throwable $e) {
    if (db()->inTransaction()) db()->rollBack();
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to save changes.';
  }
}

////////////////////////////////////////////////////////////////
// 5) Render form
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';

$vehTypes = defined('VEHICLE_TYPES') ? VEHICLE_TYPES : [
  'Economy Saloon','Business Sedan','First Class Sedan','Business Van',
  'Economy MPV5','Economy MPV8','Mini Bus','Coach'
];

// Helper for selected attr
$optSel = fn($a, $b) => ((string)$a === (string)$b && $a !== '') ? 'selected' : '';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Edit Quote</h1>
  <div class="d-flex gap-2">
    <a href="view.php?id=<?= (int)$id ?>" class="btn btn-outline-secondary">View</a>
    <a href="pdf.php?id=<?= (int)$id ?>" class="btn btn-outline-secondary" target="_blank">PDF</a>
    <a href="list.php" class="btn btn-outline-secondary">Back</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 $e) echo '<li>'.e($e).'</li>'; ?></ul></div>
<?php endif; ?>

<form method="post" id="quoteForm" autocomplete="off">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <input type="hidden" name="id" value="<?= (int)$id ?>">

  <!-- Sticky bar -->
  <div class="position-sticky top-0 z-3 pb-2" style="background:#f8fafc;">
    <div class="d-flex justify-content-between align-items-center mb-2 pt-2">
      <div class="small text-muted">Update client details and line items. Totals update automatically.</div>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark">Save Changes</button>
        <a class="btn btn-outline-secondary" href="list.php">Cancel</a>
      </div>
    </div>
  </div>

  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-3">
        <?php if ($hasQuoteRefCol): ?>
        <div class="col-md-4">
          <label class="form-label">Quotation Reference</label>
          <input class="form-control" name="quote_ref"
                 value="<?= e($_POST['quote_ref'] ?? ($quote['quote_ref'] ?? '')) ?>">
          <div class="form-text">Format like <strong>BHC-<?= e(date('dmY')) ?>-XXXXXX</strong>. Leave or edit as needed.</div>
        </div>
        <?php endif; ?>

        <div class="col-md-4">
          <label class="form-label">Client Name <span class="text-danger">*</span></label>
          <input class="form-control" name="client_name" required
                 value="<?= e($_POST['client_name'] ?? ($quote['client_name'] ?? '')) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Client Email</label>
          <input type="email" class="form-control" name="client_email"
                 value="<?= e($_POST['client_email'] ?? ($quote['client_email'] ?? '')) ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Partner (optional)</label>
          <?php $curPartner = $_POST['partner_id'] ?? $quote['partner_id']; ?>
          <select class="form-select" name="partner_id">
            <option value="">—</option>
            <?php foreach ($partners as $p): ?>
              <option value="<?= (int)$p['id'] ?>" <?= $optSel($curPartner, $p['id']) ?>><?= e($p['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Corporate (optional)</label>
          <?php $curCorp = $_POST['corporate_id'] ?? $quote['corporate_id']; ?>
          <select class="form-select" name="corporate_id">
            <option value="">—</option>
            <?php foreach ($corporates as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= $optSel($curCorp, $c['id']) ?>><?= e($c['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label">Quote Date</label>
          <input type="date" class="form-control" name="quote_date"
                 value="<?= e($_POST['quote_date'] ?? ($quote['quote_date'] ?? date('Y-m-d'))) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">Status</label>
          <?php $curStatus = $_POST['status'] ?? $quote['status'] ?? 'draft'; ?>
          <select class="form-select" name="status">
            <?php foreach (['draft','sent','accepted','rejected'] as $st): ?>
              <option value="<?= e($st) ?>" <?= $curStatus===$st?'selected':'' ?>><?= e(ucfirst($st)) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-3">
          <label class="form-label">Discount (£)</label>
          <input type="number" step="0.01" class="form-control js-calc" name="discount"
                 value="<?= e($_POST['discount'] ?? (string)($quote['discount'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-9">
          <label class="form-label">Notes (internal)</label>
          <input class="form-control" name="notes" value="<?= e($_POST['notes'] ?? ($quote['notes'] ?? '')) ?>">
        </div>
      </div>
    </div>
  </div>

  <!-- Line Items -->
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h2 class="h6 mb-0">Line Items</h2>
        <button type="button" class="btn btn-sm btn-outline-primary" id="btnAddRow">Add Line</button>
      </div>

      <div class="table-responsive">
        <table class="table align-middle" id="linesTable">
          <thead class="table-light">
            <tr>
              <th style="width:60px;">#</th>
              <th>Description</th>
              <th style="width:220px;">Vehicle Type (optional)</th>
              <th style="width:120px;" class="text-end">Qty</th>
              <th style="width:160px;" class="text-end">Unit £</th>
              <th style="width:160px;" class="text-end">Line Total</th>
              <th style="width:80px;"></th>
            </tr>
          </thead>
          <tbody>
            <?php
            // If POST (validation error), prefer POST contents
            $postRows = [];
            if ($_SERVER['REQUEST_METHOD']==='POST') {
              $postRows = array_map(null,
                (array)($_POST['line_desc'] ?? []),
                (array)($_POST['line_vehicle'] ?? []),
                (array)($_POST['line_qty'] ?? []),
                (array)($_POST['line_unit_price'] ?? [])
              );
            }
            if ($postRows) {
              foreach ($postRows as $i => $r) {
                $d = (string)($r[0] ?? '');
                $v = (string)($r[1] ?? '');
                $q = (int)($r[2] ?? 1);
                $u = (string)($r[3] ?? '0.00');
                ?>
                <tr>
                  <td class="seq"><?= $i+1 ?></td>
                  <td><textarea class="form-control" name="line_desc[]" rows="2"><?= e($d) ?></textarea></td>
                  <td>
                    <select class="form-select" name="line_vehicle[]">
                      <option value="">—</option>
                      <?php foreach ($vehTypes as $t): ?>
                        <option value="<?= e($t) ?>" <?= ($v===$t?'selected':'') ?>><?= e($t) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </td>
                  <td><input type="number" min="1" step="1" class="form-control text-end js-qty" name="line_qty[]" value="<?= e($q) ?>"></td>
                  <td><input type="number" step="0.01" class="form-control text-end js-unit" name="line_unit_price[]" value="<?= e($u) ?>"></td>
                  <td class="text-end fw-semibold line-total">0.00</td>
                  <td><button type="button" class="btn btn-sm btn-outline-danger js-del">Delete</button></td>
                </tr>
                <?php
              }
            } else {
              // Use DB lines
              if (!$lines) $lines = [['description'=>'','vehicle_type'=>null,'quantity'=>1,'unit_price'=>'0.00']];
              foreach ($lines as $i => $ln) {
                $d = (string)($ln['description'] ?? '');
                $v = (string)($ln['vehicle_type'] ?? '');
                $q = (int)($ln['quantity'] ?? 1);
                $u = (string)($ln['unit_price'] ?? '0.00');
                ?>
                <tr>
                  <td class="seq"><?= $i+1 ?></td>
                  <td><textarea class="form-control" name="line_desc[]" rows="2"><?= e($d) ?></textarea></td>
                  <td>
                    <select class="form-select" name="line_vehicle[]">
                      <option value="">—</option>
                      <?php foreach ($vehTypes as $t): ?>
                        <option value="<?= e($t) ?>" <?= ($v===$t?'selected':'') ?>><?= e($t) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </td>
                  <td><input type="number" min="1" step="1" class="form-control text-end js-qty" name="line_qty[]" value="<?= e($q) ?>"></td>
                  <td><input type="number" step="0.01" class="form-control text-end js-unit" name="line_unit_price[]" value="<?= e($u) ?>"></td>
                  <td class="text-end fw-semibold line-total">0.00</td>
                  <td><button type="button" class="btn btn-sm btn-outline-danger js-del">Delete</button></td>
                </tr>
                <?php
              }
            }
            ?>
          </tbody>
          <tfoot>
            <tr>
              <th colspan="5" class="text-end">Subtotal</th>
              <th class="text-end" id="subtotalCell">0.00</th>
              <th></th>
            </tr>
            <tr>
              <th colspan="5" class="text-end">Discount</th>
              <th class="text-end" id="discountCell">0.00</th>
              <th></th>
            </tr>
            <tr>
              <th colspan="5" class="text-end">Grand Total</th>
              <th class="text-end" id="grandCell">0.00</th>
              <th></th>
            </tr>
          </tfoot>
        </table>
      </div>

      <div class="text-muted small">
        Tip: Leave Vehicle Type empty if not relevant. Use the Description for full journey details.
      </div>
    </div>
  </div>

  <div class="d-flex gap-2">
    <button type="submit" class="btn btn-dark">Save Changes</button>
    <a class="btn btn-outline-secondary" href="list.php">Cancel</a>
  </div>
</form>

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

<script>
(function(){
  const tbody = document.querySelector('#linesTable tbody');
  const btnAdd = document.getElementById('btnAddRow');
  const discountInput = document.querySelector('input[name="discount"]');

  function renumber(){
    [...tbody.rows].forEach((tr, idx) => {
      const seq = tr.querySelector('.seq');
      if (seq) seq.textContent = String(idx+1);
    });
    recalc();
  }

  function recalc(){
    let subtotal = 0;
    [...tbody.rows].forEach(tr => {
      const qty  = parseFloat(tr.querySelector('.js-qty')?.value || '0');
      const unit = parseFloat(tr.querySelector('.js-unit')?.value || '0');
      const total = (isNaN(qty)?0:qty) * (isNaN(unit)?0:unit);
      subtotal += total;
      const td = tr.querySelector('.line-total');
      if (td) td.textContent = total.toFixed(2);
    });
    const disc = parseFloat(discountInput?.value || '0');
    const grand = subtotal - (isNaN(disc)?0:disc);
    document.getElementById('subtotalCell').textContent = subtotal.toFixed(2);
    document.getElementById('discountCell').textContent = (isNaN(disc)?0:disc).toFixed(2);
    document.getElementById('grandCell').textContent = grand.toFixed(2);
  }

  btnAdd.addEventListener('click', () => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td class="seq"></td>
      <td><textarea class="form-control" name="line_desc[]" rows="2"></textarea></td>
      <td>
        <select class="form-select" name="line_vehicle[]">
          <option value="">—</option>
          <?php foreach ($vehTypes as $t): ?>
            <option value="<?= e($t) ?>"><?= e($t) ?></option>
          <?php endforeach; ?>
        </select>
      </td>
      <td><input type="number" min="1" step="1" class="form-control text-end js-qty" name="line_qty[]" value="1"></td>
      <td><input type="number" step="0.01" class="form-control text-end js-unit" name="line_unit_price[]" value="0.00"></td>
      <td class="text-end fw-semibold line-total">0.00</td>
      <td><button type="button" class="btn btn-sm btn-outline-danger js-del">Delete</button></td>
    `;
    tbody.appendChild(tr);
    renumber();
  });

  tbody.addEventListener('click', (e) => {
    const btn = e.target.closest('.js-del');
    if (!btn) return;
    const tr = btn.closest('tr');
    if (tr) tr.remove();
    renumber();
  });

  tbody.addEventListener('input', (e) => {
    if (e.target.classList.contains('js-qty') || e.target.classList.contains('js-unit')) {
      recalc();
    }
  });
  discountInput.addEventListener('input', recalc);

  renumber();
})();
</script>
