<?php
declare(strict_types=1);
/**
 * modules/quotes/add.php
 *
 * Create a new Quote (header + dynamic line items).
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Reference data (partners, corporates)
 *  3) Helpers (optional quote_ref generator + column checks)
 *  4) Handle POST (validate, insert, 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'));

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Reference data (partners, corporates)
////////////////////////////////////////////////////////////////
$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 (quote_ref & schema checks)
////////////////////////////////////////////////////////////////
/** Check if a column exists (defensive for mixed schemas). */
function 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 generate_quote_ref_if_supported(int $companyId): ?string {
  if (!col_exists('quotes','quote_ref')) return null;
  $date = date('dmY');
  // Try a few randoms to avoid collision
  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;
  }
  // Fallback with time-based suffix
  return "BHC-{$date}-".substr((string)time(), -6);
}

// Pre-suggest a reference if supported
$quoteRefSuggested = generate_quote_ref_if_supported($cid);

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

    // Header fields
    $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'] ?? date('Y-m-d'));
    $discount    = (float)($_POST['discount'] ?? 0);
    $notes       = trim((string)($_POST['notes'] ?? ''));

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

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

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

    // Basic 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.';

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

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

      // Insert quote header
      $fields = [
        'company_id'   => ':cid',
        'partner_id'   => ':pid',
        'corporate_id' => ':coid',
        'client_name'  => ':cn',
        'client_email' => ':ce',
        'quote_date'   => ':qd',
        'discount'     => ':disc',
        'status'       => "'draft'",
        'notes'        => ':notes',
        'created_at'   => 'NOW()',
        'updated_at'   => 'NOW()',
      ];
      $args = [
        ':cid'  => $cid,
        ':pid'  => $partner_id,
        ':coid' => $corporate_id,
        ':cn'   => $client_name,
        ':ce'   => ($client_email !== '' ? $client_email : null),
        ':qd'   => $quote_date,
        ':disc' => $discount,
        ':notes'=> ($notes !== '' ? $notes : null),
      ];
      if ($hasQuoteRefCol) {
        $fields['quote_ref'] = ':qref';
        $args[':qref'] = ($quote_ref !== '' ? $quote_ref : null);
      }

      $sql = "INSERT INTO quotes (".implode(',', array_keys($fields)).")
              VALUES (".implode(',', array_values($fields)).")";
      $ins = db()->prepare($sql);
      $ins->execute($args);
      $qid = (int)db()->lastInsertId();

      // Insert line items
      $insLBase = "
        INSERT INTO quote_lines (quote_id, description, quantity, unit_price, line_total".
        ($hasVehicleTypeCol ? ", vehicle_type" : "").
        ") VALUES (:qid, :d, :q, :u, :t".
        ($hasVehicleTypeCol ? ", :vt" : "").
        ")
      ";
      $insL = db()->prepare($insLBase);

      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' => $qid,
          ':d'   => $d !== '' ? $d : null,
          ':q'   => $q,
          ':u'   => $u,
          ':t'   => $t,
        ];
        if ($hasVehicleTypeCol) {
          $params[':vt'] = ($v !== '' ? $v : null);
        }
        $insL->execute($params);
      }

      db()->commit();
      audit_log('quote.create','quote',$qid,['client'=>$client_name,'subtotal'=>$subtotal,'discount'=>$discount]);

      redirect('list.php?saved=1');
    }
  } catch (Throwable $e) {
    if (db()->inTransaction()) db()->rollBack();
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to save quote.';
  }
}

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

// Vehicle types (optional UX)
$vehTypes = defined('VEHICLE_TYPES') ? VEHICLE_TYPES : [
  'Economy Saloon','Business Sedan','First Class Sedan','Business Van',
  'Economy MPV5','Economy MPV8','Mini Bus','Coach'
];
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">New Quote</h1>
  <a href="list.php" class="btn btn-outline-secondary">Back</a>
</div>

<?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()) ?>">

  <!-- 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">Fill client details and add line items. Totals update automatically.</div>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark">Save Quote</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 (col_exists('quotes','quote_ref')): ?>
        <div class="col-md-4">
          <label class="form-label">Quotation Reference</label>
          <input class="form-control" name="quote_ref"
                 value="<?= e($_POST['quote_ref'] ?? ($quoteRefSuggested ?? '')) ?>">
          <div class="form-text">Auto-suggested like <strong>BHC-<?= e(date('dmY')) ?>-XXXXXX</strong>. You can change it.</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'] ?? '') ?>">
        </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'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Partner (optional)</label>
          <select class="form-select" name="partner_id">
            <option value="">—</option>
            <?php foreach ($partners as $p): ?>
              <option value="<?= (int)$p['id'] ?>" <?= ((int)($_POST['partner_id'] ?? 0)===(int)$p['id'])?'selected':'' ?>>
                <?= e($p['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Corporate (optional)</label>
          <select class="form-select" name="corporate_id">
            <option value="">—</option>
            <?php foreach ($corporates as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= ((int)($_POST['corporate_id'] ?? 0)===(int)$c['id'])?'selected':'' ?>>
                <?= e($c['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Quote Date</label>
          <input type="date" class="form-control" name="quote_date"
                 value="<?= e($_POST['quote_date'] ?? date('Y-m-d')) ?>">
        </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'] ?? '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'] ?? '') ?>">
        </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
            $rows = [];
            if ($_SERVER['REQUEST_METHOD']==='POST') {
              $rows = array_map(null,
                (array)($_POST['line_desc'] ?? []),
                (array)($_POST['line_vehicle'] ?? []),
                (array)($_POST['line_qty'] ?? []),
                (array)($_POST['line_unit_price'] ?? [])
              );
            }
            if (!$rows) $rows = [[ '', '', 1, '0.00' ]];

            foreach ($rows 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" placeholder="e.g., Airport Transfer Heathrow → City"><?= 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 endforeach; ?>
          </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: You can 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 Quote</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" placeholder="e.g., Airport Transfer Heathrow → City"></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>
