<?php
declare(strict_types=1);
/**
 * modules/quotes/email_send.php
 *
 * Send a Quote via email with branded PDF attachment.
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Load company, quote, lines, terms, build totals
 *  3) POST: generate PDF (mPDF) + send with PHPMailer (fallback to mail())
 *  4) Render send form
 */

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

$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;

////////////////////////////////////////////////////////////////
// 2) Load data
////////////////////////////////////////////////////////////////
/* Company (branding) */
$coStmt = db()->prepare("SELECT * FROM companies WHERE id = :id LIMIT 1");
$coStmt->execute([':id' => $cid]);
$co = $coStmt->fetch();

$brandName   = trim((string)($co['name'] ?? '')) ?: 'Brown Hill Chauffeurs';
$brandEmail  = trim((string)($co['email'] ?? ''));
$brandPhone  = trim((string)($co['phone'] ?? ''));
$brandAddr   = trim((string)($co['address'] ?? ''));
$logoUrl     = !empty($co['logo_url']) ? url_public($co['logo_url']) : null;
$contactLine = trim(implode(' • ', array_filter([
  $brandAddr ?: null,
  $brandPhone ? 'Tel: '.$brandPhone : null,
  $brandEmail ? 'Email: '.$brandEmail : null,
])));

/* Quote */
$qStmt = 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
");
$qStmt->execute([':id' => $qid, ':cid' => $cid]);
$quote = $qStmt->fetch();
if (!$quote) redirect(url_modules('quotes/list.php'));

/* Lines */
$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);

/* Terms */
$terms = '';
try {
  $s = db()->prepare("SELECT value FROM settings WHERE company_id=:cid AND `key`='quote_terms' LIMIT 1");
  $s->execute([':cid' => $cid]);
  $row = $s->fetch();
  if ($row && trim((string)$row['value']) !== '') {
    $terms = (string)$row['value'];
  }
} catch (Throwable $e) { /* settings optional */ }
if ($terms === '') {
  $terms = "All bookings are subject to our standard terms & conditions. Prices are in GBP and may exclude parking/waiting unless stated.";
}

/* Helpers */
$quoteRef   = trim((string)($quote['quote_ref'] ?? '')) ?: ('Q-' . (int)$quote['id']);
$quoteDate  = !empty($quote['quote_date']) ? (string)$quote['quote_date'] : date('Y-m-d');
$clientName = trim((string)($quote['client_name'] ?? ''));
$clientEmail= trim((string)($quote['client_email'] ?? ''));

/**
 * Build the HTML used for the PDF body (same visual as pdf.php).
 */
function build_quote_pdf_html(array $co, string $brandName, ?string $logoUrl, string $contactLine, array $q, array $lines, float $subTotal, float $discount, float $grand, string $terms): string {
  $quoteRef  = htmlspecialchars((string)($q['quote_ref'] ?? '' ?: ('Q-' . (int)$q['id'])), ENT_QUOTES, 'UTF-8');
  $quoteDate = htmlspecialchars((string)($q['quote_date'] ?? date('Y-m-d')), ENT_QUOTES, 'UTF-8');
  $status    = htmlspecialchars(ucfirst((string)($q['status'] ?? 'draft')), ENT_QUOTES, 'UTF-8');
  $client    = htmlspecialchars((string)($q['client_name'] ?? ''), ENT_QUOTES, 'UTF-8');
  $cEmail    = htmlspecialchars((string)($q['client_email'] ?? ''), ENT_QUOTES, 'UTF-8');
  $partner   = htmlspecialchars((string)($q['partner_name'] ?? ''), ENT_QUOTES, 'UTF-8');
  $corp      = htmlspecialchars((string)($q['corporate_name'] ?? ''), ENT_QUOTES, 'UTF-8');

  ob_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= $brandName ?> - Quote <?= $quoteRef ?></title>
<style>
  :root{ --border:#e5e7eb; --muted:#6b7280; --text:#111827; --heading:#0f172a; --soft:#f8fafc; }
  *{ box-sizing:border-box; }
  body{ font-family: Arial, Helvetica, sans-serif; font-size:12px; color:var(--text); margin:0; padding:16px; }
  .header{ display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border); padding-bottom:10px; margin-bottom:14px; }
  .brand{ display:flex; align-items:center; gap:10px; }
  .brand .title{ font-size:22px; font-weight:700; color:var(--heading); }
  .muted{ color:var(--muted); }
  .pill{ display:inline-block; font-size:11px; padding:3px 8px; border-radius:999px; background:#eef2ff; color:#3730a3; border:1px solid #e0e7ff; }
  .grid-2{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
  .box{ border:1px solid var(--border); border-radius:10px; padding:10px; background:#fff; }
  .box .h{ font-weight:700; margin-bottom:6px; border-bottom:1px solid var(--border); padding-bottom:4px; color:var(--heading); }
  table.kv{ width:100%; border-collapse:collapse; }
  table.kv td{ padding:5px 6px; vertical-align:top; }
  table.grid{ width:100%; border-collapse:collapse; }
  table.grid th, table.grid td{ border:1px solid var(--border); padding:6px 8px; text-align:left; vertical-align:top; }
  table.grid thead th{ background:var(--soft); font-weight:700; }
  .totals{ width:100%; border-collapse:collapse; margin-top:8px; }
  .totals td{ padding:6px 8px; }
  .footer-note{ margin-top:14px; font-size:11px; color:var(--muted); }
  .terms{ margin-top:12px; font-size:11px; color:#374151; white-space:pre-wrap; }
</style>
</head>
<body>

  <div class="header">
    <div class="brand">
      <?php if ($logoUrl): ?><img src="<?= $logoUrl ?>" alt="Logo" height="44"><?php endif; ?>
      <div>
        <div class="title"><?= $brandName ?> — Quote</div>
        <div class="muted">
          Quote #: <strong><?= $quoteRef ?></strong> •
          Date: <?= $quoteDate ?>
          <?php if ($partner): ?> • Partner: <?= $partner ?><?php endif; ?>
          <?php if ($corp): ?> • Corporate: <?= $corp ?><?php endif; ?>
        </div>
      </div>
    </div>
    <div><?php if (!empty($status)): ?><span class="pill"><?= $status ?></span><?php endif; ?></div>
  </div>

  <div class="grid-2">
    <div class="box">
      <div class="h">Client</div>
      <table class="kv">
        <tr><td class="muted" width="35%">Name</td><td><?= $client ?: '—' ?></td></tr>
        <tr><td class="muted">Email</td><td><?= $cEmail ?: '—' ?></td></tr>
        <tr><td class="muted">Reference</td><td><?= $quoteRef ?></td></tr>
      </table>
    </div>
    <div class="box">
      <div class="h">Company</div>
      <table class="kv">
        <tr><td class="muted" width="35%">Company</td><td><?= $brandName ?></td></tr>
        <?php if (!empty($co['address'])): ?><tr><td class="muted">Address</td><td><?= nl2br(htmlspecialchars((string)$co['address'], ENT_QUOTES, 'UTF-8')) ?></td></tr><?php endif; ?>
        <?php if (!empty($co['phone'])): ?><tr><td class="muted">Phone</td><td><?= htmlspecialchars((string)$co['phone'], ENT_QUOTES, 'UTF-8') ?></td></tr><?php endif; ?>
        <?php if (!empty($co['email'])): ?><tr><td class="muted">Email</td><td><?= htmlspecialchars((string)$co['email'], ENT_QUOTES, 'UTF-8') ?></td></tr><?php endif; ?>
      </table>
    </div>
  </div>

  <div class="box" style="margin-top:12px;">
    <div class="h">Line Items</div>
    <table class="grid">
      <thead>
        <tr>
          <th style="width:48px;">#</th>
          <th>Description</th>
          <th style="width:80px; text-align:right;">Qty</th>
          <th style="width:110px; text-align:right;">Unit £</th>
          <th style="width:120px; text-align:right;">Line Total £</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($lines): ?>
          <?php 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(htmlspecialchars((string)($ln['description'] ?? ''), ENT_QUOTES, 'UTF-8')) ?></td>
            <td style="text-align:right;"><?= number_format($qty, 0) ?></td>
            <td style="text-align:right;"><?= number_format($unit, 2) ?></td>
            <td style="text-align:right;"><?= number_format($lt, 2) ?></td>
          </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td colspan="5" class="muted">No items.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>

    <table class="totals">
      <tr>
        <td style="width:60%;"></td>
        <td class="muted" style="width:20%; text-align:right;">Subtotal</td>
        <td style="width:20%; text-align:right;"><?= number_format($subTotal, 2) ?></td>
      </tr>
      <tr>
        <td></td>
        <td class="muted" style="text-align:right;">Discount</td>
        <td style="text-align:right;"><?= number_format($discount, 2) ?></td>
      </tr>
      <tr>
        <td></td>
        <td class="muted" style="text-align:right;"><strong>Grand Total</strong></td>
        <td style="text-align:right;"><strong><?= number_format($grand, 2) ?></strong></td>
      </tr>
    </table>
  </div>

  <?php if (!empty($q['notes'])): ?>
    <div class="box" style="margin-top:12px;">
      <div class="h">Internal Notes</div>
      <div><?= nl2br(htmlspecialchars((string)$q['notes'], ENT_QUOTES, 'UTF-8')) ?></div>
    </div>
  <?php endif; ?>

  <div class="box" style="margin-top:12px;">
    <div class="h">Terms &amp; Conditions</div>
    <div class="terms"><?= nl2br(htmlspecialchars($terms, ENT_QUOTES, 'UTF-8')) ?></div>
  </div>

  <?php if ($contactLine): ?>
    <div class="footer-note"><?= htmlspecialchars($contactLine, ENT_QUOTES, 'UTF-8') ?></div>
  <?php endif; ?>

</body>
</html>
<?php
  return (string)ob_get_clean();
}

/**
 * Generate PDF bytes from HTML (mPDF). Returns [bytes, filename] or [null, null] if mPDF missing.
 */
function generate_quote_pdf_bytes(array $co, string $brandName, ?string $logoUrl, string $contactLine, array $q, array $lines, float $subTotal, float $discount, float $grand, string $terms): array {
  if (!class_exists('\\Mpdf\\Mpdf')) {
    return [null, null];
  }
  $html = build_quote_pdf_html($co, $brandName, $logoUrl, $contactLine, $q, $lines, $subTotal, $discount, $grand, $terms);
  $mpdf = new \Mpdf\Mpdf([
    'format'        => 'A4',
    'margin_left'   => 12,
    'margin_right'  => 12,
    'margin_top'    => 12,
    'margin_bottom' => 14,
  ]);
  $ref = trim((string)($q['quote_ref'] ?? '')) ?: ('Q-' . (int)$q['id']);
  $mpdf->SetTitle('Quote - ' . $ref);
  $mpdf->SetAuthor($brandName);
  $mpdf->SetWatermarkText($brandName);
  $mpdf->showWatermarkText = true;

  $mpdf->WriteHTML($html);
  $pdf = $mpdf->Output('', 'S'); // return as string
  $filename = 'quote_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', $ref) . '.pdf';
  return [$pdf, $filename];
}

////////////////////////////////////////////////////////////////
// 3) POST: Send email
////////////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $to       = trim((string)($_POST['to'] ?? ''));
    $cc       = trim((string)($_POST['cc'] ?? ''));
    $subject  = trim((string)($_POST['subject'] ?? ''));
    $message  = trim((string)($_POST['message'] ?? ''));
    $attach   = isset($_POST['attach_pdf']);
    $replyTo  = trim((string)($_POST['reply_to'] ?? $brandEmail));

    if ($to === '') {
      throw new RuntimeException('Recipient email is required.');
    }
    if ($subject === '') {
      $subject = "Quote {$quoteRef} from {$brandName}";
    }
    if ($message === '') {
      $message = "Hello {$clientName},\n\nPlease find attached your quote ({$quoteRef}).\n\nRegards,\n{$brandName}";
    }

    // Prepare PDF
    $pdfBytes = null; $pdfFileName = null; $savedPath = null;
    if ($attach) {
      [$pdfBytes, $pdfFileName] = generate_quote_pdf_bytes($co, $brandName, $logoUrl, $contactLine, $quote, $lines, $subTotal, $discount, $grand, $terms);
      if ($pdfBytes !== null) {
        // Save a copy to /public/uploads/quotes
        $dir = project_root() . '/public/uploads/quotes';
        if (!is_dir($dir)) @mkdir($dir, 0775, true);
        $savedPath = $dir . '/' . $pdfFileName;
        @file_put_contents($savedPath, $pdfBytes);
        // Store URL if not set
        $url = 'uploads/quotes/' . $pdfFileName;
        $upd = db()->prepare("UPDATE quotes SET pdf_url = :u WHERE id=:id AND company_id=:cid");
        $upd->execute([':u' => $url, ':id' => $qid, ':cid' => $cid]);
      }
    }

    $sent = false;
    $err  = null;

    // Try PHPMailer first
    if (class_exists('\\PHPMailer\\PHPMailer\\PHPMailer')) {
      $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
      try {
        // Transport: use PHP's mail() by default; configure SMTP in your app bootstrap if needed
        $mail->isMail();

        $mail->setFrom($brandEmail ?: 'no-reply@localhost', $brandName);
        if ($replyTo !== '') $mail->addReplyTo($replyTo, $brandName);

        // To / CC
        foreach (preg_split('/[,;\s]+/', $to) as $addr) {
          $addr = trim($addr);
          if ($addr !== '') $mail->addAddress($addr);
        }
        if ($cc !== '') {
          foreach (preg_split('/[,;\s]+/', $cc) as $addr) {
            $addr = trim($addr);
            if ($addr !== '') $mail->addCC($addr);
          }
        }

        if ($attach && $pdfBytes !== null && $pdfFileName !== null) {
          $mail->addStringAttachment($pdfBytes, $pdfFileName, 'base64', 'application/pdf');
        } elseif ($attach && $savedPath && is_file($savedPath)) {
          $mail->addAttachment($savedPath);
        }

        $mail->isHTML(true);
        $mail->Subject = $subject;

        $bodyHtml = nl2br(e($message)) .
          '<br><br><div style="font-size:12px;color:#6b7280;">' . e($contactLine) . '</div>';
        $mail->Body    = $bodyHtml;
        $mail->AltBody = $message;

        $mail->send();
        $sent = true;
      } catch (\Throwable $e) {
        $err = $e->getMessage();
      }
    }

    // Fallback to mail()
    if (!$sent) {
      $headers = [];
      $from = $brandEmail ?: 'no-reply@localhost';
      $headers[] = 'From: ' . $brandName . ' <' . $from . '>';
      if ($replyTo) $headers[] = 'Reply-To: ' . $replyTo;
      if ($cc)      $headers[] = 'Cc: ' . $cc;
      $headers[] = 'MIME-Version: 1.0';
      $headers[] = 'Content-type: text/html; charset=UTF-8';

      $ok = @mail($to, $subject, nl2br(e($message)), implode("\r\n", $headers));
      if (!$ok) {
        throw new RuntimeException('Unable to send email (no PHPMailer, mail() failed). ' . ($err ? 'Mailer error: '.$err : ''));
      }
      $sent = true;
    }

    // Mark quote as 'sent' if applicable
    if ($sent) {
      if (($quote['status'] ?? 'draft') === 'draft') {
        db()->prepare("UPDATE quotes SET status='sent' WHERE id=:id AND company_id=:cid")
           ->execute([':id'=>$qid, ':cid'=>$cid]);
      }
      audit_log('quote.email_send', 'quote', $qid, [
        'to' => $to, 'cc' => $cc, 'subject' => $subject, 'attached' => (bool)$attach
      ]);
      $notice = 'Email sent successfully.';
    }

  } catch (Throwable $e) {
    $errors[] = (APP_ENV === 'dev') ? $e->getMessage() : 'Failed to send email.';
  }
}

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

$defaultSubject = "Quote {$quoteRef} from {$brandName}";
$defaultMsg = "Hello {$clientName},\n\nPlease find attached your quote ({$quoteRef}) dated {$quoteDate}.\n"
            . "Total: £" . number_format($grand, 2) . "\n\nKind regards,\n{$brandName}";
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Send Quote — <?= e($quoteRef) ?></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>
    <a class="btn btn-outline-primary" target="_blank" href="<?= e(url_modules('quotes/pdf.php?id='.(int)$qid)) ?>">Preview PDF</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="card shadow-sm">
  <div class="card-body">
    <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-3">
        <div class="col-md-6">
          <label class="form-label">To (email) <span class="text-danger">*</span></label>
          <input type="email" class="form-control" name="to" required value="<?= e($_POST['to'] ?? $clientEmail) ?>">
          <div class="form-text">You can enter multiple addresses separated by commas.</div>
        </div>
        <div class="col-md-6">
          <label class="form-label">CC</label>
          <input class="form-control" name="cc" value="<?= e($_POST['cc'] ?? '') ?>">
        </div>

        <div class="col-md-8">
          <label class="form-label">Subject</label>
          <input class="form-control" name="subject" value="<?= e($_POST['subject'] ?? $defaultSubject) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Reply-To</label>
          <input type="email" class="form-control" name="reply_to" value="<?= e($_POST['reply_to'] ?? ($brandEmail ?: '')) ?>">
          <div class="form-text">Where the client will reply.</div>
        </div>

        <div class="col-12">
          <label class="form-label">Message</label>
          <textarea class="form-control" name="message" rows="8"><?= e($_POST['message'] ?? $defaultMsg) ?></textarea>
        </div>

        <div class="col-md-6 form-check mt-2">
          <input class="form-check-input" type="checkbox" id="attach_pdf" name="attach_pdf" <?= (isset($_POST['attach_pdf']) || !isset($_POST['csrf'])) ? 'checked' : '' ?>>
          <label class="form-check-label" for="attach_pdf">Attach Quote PDF</label>
        </div>
      </div>

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

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