<?php
declare(strict_types=1);

/**
 * modules/quotes/view.php
 *
 * Read-only view of a quote:
 *  - Client / partner / corporate / meta
 *  - Line items table
 *  - Totals (subtotal, discount, grand)
 *  - Actions: Edit, PDF, Email, Convert → Booking, Back
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch quote (with partner/corporate)
 *  3) Column detection (safe, no INFORMATION_SCHEMA needed)
 *  4) Fetch line items (column-safe)
 *  5) Totals & helpers
 *  6) Render
 */

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

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

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

$notice = null;
if (isset($_GET['sent']))      $notice = 'Email sent to client.';
if (isset($_GET['converted'])) $notice = 'Quote converted to a booking.';
if (isset($_GET['pdf']))       $notice = 'PDF generated.';

////////////////////////////////////////////////////////////////
// 2) Fetch quote (with partner/corporate)
////////////////////////////////////////////////////////////////
$q = db()->prepare("
  SELECT q.*,
         p.name AS partner_name,
         c.name AS corporate_name
    FROM quotes q
    LEFT JOIN partners  p ON p.id = q.partner_id
    LEFT JOIN corporates c ON c.id = q.corporate_id
   WHERE q.id = :id AND q.company_id = :cid
   LIMIT 1
");
$q->execute([':id'=>$id, ':cid'=>$cid]);
$quote = $q->fetch();
if (!$quote) redirect('list.php');

////////////////////////////////////////////////////////////////
// 3) Column detection (safe)
////////////////////////////////////////////////////////////////
/**
 * Check if a column exists by attempting a dummy SELECT on it.
 * No INFORMATION_SCHEMA permissions required.
 */
function table_has_column(string $table, string $column): bool {
  try {
    $sql = "SELECT `$column` FROM `$table` WHERE 1=0";
    $stmt = db()->prepare($sql);
    $stmt->execute();
    return true;
  } catch (Throwable $e) {
    return false;
  }
}

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

////////////////////////////////////////////////////////////////
// 4) Fetch line items (column-safe)
////////////////////////////////////////////////////////////////
$sqlLines = "SELECT id, description, quantity, unit_price, line_total"
          . ($hasVehicleTypeCol ? ", vehicle_type" : "")
          . " FROM quote_lines WHERE quote_id = :qid ORDER BY id ASC";
$ls = db()->prepare($sqlLines);
$ls->execute([':qid'=>$id]);
$lines = $ls->fetchAll();

////////////////////////////////////////////////////////////////
// 5) Totals & helpers
////////////////////////////////////////////////////////////////
$discount = (float)($quote['discount'] ?? 0.00);
$subtotal = 0.0;
foreach ($lines as $ln) {
  $qty = (int)($ln['quantity'] ?? 0);
  $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;
}
$grand = max(0.0, $subtotal - $discount);

function quote_status_badge(string $s): string {
  $map = [
    'draft'    => 'secondary',
    'sent'     => 'info',
    'accepted' => 'success',
    'rejected' => 'danger',
  ];
  $cls = $map[$s] ?? 'secondary';
  return '<span class="badge text-bg-'.$cls.'">'.e(ucfirst($s)).'</span>';
}

////////////////////////////////////////////////////////////////
// 6) Render
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">
    Quote #<?= (int)$quote['id'] ?>
    <?php if ($hasQuoteRefCol && !empty($quote['quote_ref'])): ?>
      — <?= e((string)$quote['quote_ref']) ?>
    <?php endif; ?>
  </h1>
  <div class="d-flex gap-2">
    <a class="btn btn-primary" target="_blank" href="<?= e(url_modules('quotes/pdf.php')) ?>?id=<?= (int)$quote['id'] ?>">Generate PDF</a>
    <a class="btn btn-outline-primary" href="<?= e(url_modules('quotes/email_send.php')) ?>?id=<?= (int)$quote['id'] ?>">Send Email</a>
    <a class="btn btn-success" href="<?= e(url_modules('quotes/convert_to_booking.php')) ?>?id=<?= (int)$quote['id'] ?>">Convert → Booking</a>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('quotes/edit.php')) ?>?id=<?= (int)$quote['id'] ?>">Edit</a>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('quotes/list.php')) ?>">Back</a>
  </div>
</div>

<?php if ($notice): ?>
  <div class="alert alert-success"><?= e($notice) ?></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-3">Client & Quote</h2>
        <div class="row g-3">
          <div class="col-md-6">
            <div class="small text-muted">Client Name</div>
            <div class="fw-semibold"><?= e($quote['client_name'] ?? '—') ?></div>
          </div>
          <div class="col-md-6">
            <div class="small text-muted">Client Email</div>
            <div class="fw-semibold"><?= e($quote['client_email'] ?? '—') ?></div>
          </div>
          <div class="col-md-4">
            <div class="small text-muted">Quote Date</div>
            <div class="fw-semibold"><?= e($quote['quote_date'] ?? '—') ?></div>
          </div>
          <div class="col-md-4">
            <div class="small text-muted">Status</div>
            <div class="fw-semibold"><?= quote_status_badge((string)($quote['status'] ?? 'draft')) ?></div>
          </div>
          <?php if ($hasQuoteRefCol): ?>
          <div class="col-md-4">
            <div class="small text-muted">Reference</div>
            <div class="fw-semibold"><?= e($quote['quote_ref'] ?? '—') ?></div>
          </div>
          <?php endif; ?>
          <div class="col-md-6">
            <div class="small text-muted">Partner</div>
            <div class="fw-semibold"><?= e($quote['partner_name'] ?? '—') ?></div>
          </div>
          <div class="col-md-6">
            <div class="small text-muted">Corporate</div>
            <div class="fw-semibold"><?= e($quote['corporate_name'] ?? '—') ?></div>
          </div>
        </div>

        <?php if (!empty($quote['notes'])): ?>
          <hr class="my-3">
          <div class="small text-muted">Notes</div>
          <div class="fw-semibold"><?= nl2br(e((string)$quote['notes'])) ?></div>
        <?php endif; ?>
      </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-3">Totals</h2>
        <div class="row g-3">
          <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>

        <?php if (!empty($quote['pdf_url'])): ?>
          <hr class="my-3">
          <div class="small text-muted">Latest PDF</div>
          <a class="fw-semibold" target="_blank" href="<?= e(url_public((string)$quote['pdf_url'])) ?>">Open PDF</a>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Line Items</h2>
        <div class="table-responsive">
          <table class="table align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:60px;">#</th>
                <th>Description</th>
                <?php if ($hasVehicleTypeCol): ?>
                  <th style="width:220px;">Vehicle Type</th>
                <?php endif; ?>
                <th class="text-end" style="width:120px;">Qty</th>
                <th class="text-end" style="width:160px;">Unit £</th>
                <th class="text-end" style="width:160px;">Line Total</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($lines): ?>
                <?php foreach ($lines as $i => $ln): ?>
                  <?php
                    $qnty = (int)($ln['quantity'] ?? 0);
                    $unit = (float)($ln['unit_price'] ?? 0);
                    $lt   = isset($ln['line_total']) && $ln['line_total'] !== null && $ln['line_total'] !== ''
                            ? (float)$ln['line_total']
                            : ($qnty * $unit);
                  ?>
                  <tr>
                    <td><?= $i+1 ?></td>
                    <td><div style="white-space:pre-wrap;"><?= nl2br(e((string)($ln['description'] ?? ''))) ?></div></td>
                    <?php if ($hasVehicleTypeCol): ?>
                      <td><?= e((string)($ln['vehicle_type'] ?? '')) ?: '—' ?></td>
                    <?php endif; ?>
                    <td class="text-end"><?= number_format($qnty, 0) ?></td>
                    <td class="text-end">£<?= number_format($unit, 2) ?></td>
                    <td class="text-end fw-semibold">£<?= number_format($lt, 2) ?></td>
                  </tr>
                <?php endforeach; ?>
              <?php else: ?>
                <tr><td colspan="<?= $hasVehicleTypeCol ? 6 : 5 ?>" class="text-center text-muted">No line items.</td></tr>
              <?php endif; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="<?= $hasVehicleTypeCol ? 5 : 4 ?>" class="text-end">Subtotal</th>
                <th class="text-end">£<?= number_format($subtotal, 2) ?></th>
              </tr>
              <tr>
                <th colspan="<?= $hasVehicleTypeCol ? 5 : 4 ?>" class="text-end">Discount</th>
                <th class="text-end">£<?= number_format($discount, 2) ?></th>
              </tr>
              <tr>
                <th colspan="<?= $hasVehicleTypeCol ? 5 : 4 ?>" class="text-end">Grand Total</th>
                <th class="text-end">£<?= number_format($grand, 2) ?></th>
              </tr>
            </tfoot>
          </table>
        </div>

        <div class="text-muted small">
          Prices shown exclude VAT unless specified. Terms &amp; Conditions apply (see PDF).
        </div>
      </div>
    </div>
  </div>
</div>

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