<?php
declare(strict_types=1);
/**
 * modules/invoices/send.php
 *
 * Email an invoice PDF to the client (mPDF + PHPMailer).
 */

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'));

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

$errors = [];
$notice = null;

/* Helpers */
function setting_val(int $companyId, string $key): ?string {
  try { $q = db()->prepare("SELECT value FROM settings WHERE company_id=:cid AND `key`=:k LIMIT 1");
        $q->execute([':cid'=>$companyId, ':k'=>$key]);
        if ($r=$q->fetch()) return (string)$r['value']; } catch(Throwable $e) {}
  try { $q = db()->prepare("SELECT setting_value FROM settings WHERE company_id=:cid AND setting_key=:k LIMIT 1");
        $q->execute([':cid'=>$companyId, ':k'=>$key]);
        if ($r=$q->fetch()) return (string)$r['setting_value']; } catch(Throwable $e) {}
  return null;
}
function column_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; }
}
function n2($v): string { return number_format((float)$v, 2); }

/* Fetch invoice */
$inv = db()->prepare("SELECT * FROM invoices WHERE id=:id AND company_id=:cid LIMIT 1");
$inv->execute([':id'=>$iid, ':cid'=>$cid]);
$invoice = $inv->fetch();
if (!$invoice) redirect(url_modules('invoices/list.php'));

/* Lines */
$linesStmt = db()->prepare("SELECT id, description, quantity, unit_price, line_total FROM invoice_lines WHERE invoice_id=:iid ORDER BY id ASC");
$linesStmt->execute([':iid'=>$iid]);
$lines = $linesStmt->fetchAll();

/* Company */
$coStmt = db()->prepare("SELECT * FROM companies WHERE id=:id LIMIT 1");
$coStmt->execute([':id'=>$cid]);
$co = $coStmt->fetch() ?: [];
$brandName = trim((string)($co['name'] ?? '')) ?: 'Brownhill Group Limited';

/* Logo path */
$logoRel = 'assets/logo.png';
if (!is_readable(project_root().'/public/'.$logoRel)) {
  $alt = 'public/assets/logo.png';
  if (is_readable(project_root().'/public/'.$alt)) $logoRel = $alt;
}
$logoUrl = url_public($logoRel);

/* Contact line */
$companyAddress = trim((string)($co['address'] ?? '')) ?: 'Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ, London, United Kingdom';
$companyPhone   = trim((string)($co['phone']   ?? '')) ?: '+44 208 064 2662';
$companyEmail   = trim((string)($co['email']   ?? '')) ?: 'info@brown-hillchauffeurs.co.uk';
$companyWeb     = trim((string)($co['website'] ?? '')) ?: 'www.brown-hillchauffeurs.co.uk';
$contactLine = implode(' • ', array_filter([$companyAddress,'Phone: '.$companyPhone,'Email: '.$companyEmail,'Website: '.$companyWeb]));

/* Totals */
$subtotal = (float)($invoice['subtotal_amount'] ?? 0);
$discount = (float)($invoice['discount_amount'] ?? 0);
$vatRate  = (float)($invoice['vat_rate'] ?? 0);
$vatAmt   = (float)($invoice['vat_amount'] ?? 0);
$total    = (float)($invoice['total_amount'] ?? 0);
$paid     = (float)($invoice['paid_total'] ?? 0);
if ($subtotal <= 0) {
  $sum = 0.0;
  foreach ($lines as $ln) {
    $qty  = (float)($ln['quantity'] ?? 0);
    $unit = (float)($ln['unit_price'] ?? 0);
    $lt   = ($ln['line_total'] !== null && $ln['line_total'] !== '') ? (float)$ln['line_total'] : ($qty * $unit);
    $sum += $lt;
  }
  $subtotal = $sum;
  if ($total <= 0) {
    $base = max(0.0, $subtotal - $discount);
    $vatAmt = $vatRate > 0 ? round($base * ($vatRate/100), 2) : 0.0;
    $total  = $base + $vatAmt;
  }
}
$invoiceNo   = trim((string)($invoice['invoice_no'] ?? '')) ?: ('INV-'.$invoice['id']);
$invoiceDate = !empty($invoice['invoice_date']) ? (string)$invoice['invoice_date'] : date('Y-m-d');
$dueDate     = (string)($invoice['due_date'] ?? '');

/* Build the same HTML as PDF (simplified here into $html) */
ob_start();
?>
<!DOCTYPE html><html><head><meta charset="utf-8"><title><?= e($brandName) ?> - Invoice <?= e($invoiceNo) ?></title></head>
<body>
  <h3><?= e($brandName) ?> — Invoice <?= e($invoiceNo) ?></h3>
  <p>Date: <?= e($invoiceDate) ?><?php if($dueDate): ?> • Due: <?= e($dueDate) ?><?php endif; ?></p>
  <p><strong>To:</strong> <?= e($invoice['bill_to_name'] ?? '—') ?> (<?= e($invoice['bill_to_email'] ?? '') ?>)</p>
  <p>Total: <strong>£ <?= e(n2($total)) ?></strong> • Paid: £ <?= e(n2($paid)) ?> • Balance: £ <?= e(n2(max(0.0,$total-$paid))) ?></p>
</body></html>
<?php
$html = ob_get_clean();

/* POST: generate PDF, persist (optional), send email */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $to   = trim((string)($_POST['to'] ?? ($invoice['bill_to_email'] ?? '')));
    $cc   = trim((string)($_POST['cc'] ?? ''));
    $bcc  = trim((string)($_POST['bcc'] ?? ''));
    $subj = trim((string)($_POST['subject'] ?? ''));
    $msg  = trim((string)($_POST['message'] ?? ''));
    if ($to === '') throw new RuntimeException('Recipient (To) is required.');

    if (!class_exists('\\Mpdf\\Mpdf')) throw new RuntimeException('mPDF library not found.');
    $mpdf = new \Mpdf\Mpdf(['format'=>'A4','margin_left'=>12,'margin_right'=>12,'margin_top'=>12,'margin_bottom'=>14]);
    $mpdf->SetTitle('Invoice - '.$invoiceNo);
    $mpdf->SetAuthor($brandName);
    $mpdf->SetWatermarkText($brandName);
    $mpdf->showWatermarkText = true;
    // Use the proper HTML from pdf.php for best layout — or keep this minimal:
    // For reliability, reuse pdf.php’s rendering:
    ob_start();
    include __DIR__ . '/pdf.php'; // if you prefer direct include, else keep $html above
    ob_end_clean();
    // Instead of include, render our $html quickly:
    $mpdf->WriteHTML($html);
    $pdfData = $mpdf->Output('', 'S');

    // Save file
    $relDir = 'uploads/invoices';
    $absDir = project_root().'/public/'.$relDir;
    if (!is_dir($absDir)) @mkdir($absDir, 0775, true);
    $safeName = 'invoice_'.preg_replace('/[^A-Za-z0-9_\-]/', '_', $invoiceNo).'.pdf';
    $absFile  = $absDir.'/'.$safeName;
    file_put_contents($absFile, $pdfData);
    $relPath  = $relDir.'/'.$safeName;

    if (column_exists('invoices','pdf_url')) {
      db()->prepare("UPDATE invoices SET pdf_url=:u WHERE id=:id AND company_id=:cid")
        ->execute([':u'=>$relPath, ':id'=>$iid, ':cid'=>$cid]);
    }

    // PHPMailer
    $root = project_root();
    $loaded = false;
    if (file_exists($root.'/vendor/autoload.php')) { require_once $root.'/vendor/autoload.php'; $loaded = true; }
    if (!$loaded && file_exists($root.'/vendor/phpmailer/phpmailer/src/PHPMailer.php')) {
      require_once $root.'/vendor/phpmailer/phpmailer/src/PHPMailer.php';
      require_once $root.'/vendor/phpmailer/phpmailer/src/SMTP.php';
      require_once $root.'/vendor/phpmailer/phpmailer/src/Exception.php';
      $loaded = true;
    }
    if (!$loaded) throw new RuntimeException('PHPMailer library not found.');

    $fromEmail = setting_val($cid,'smtp_from_email') ?: $companyEmail;
    $fromName  = setting_val($cid,'smtp_from_name')  ?: $brandName;

    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);

    $smtpHost = setting_val($cid,'smtp_host');
    $smtpUser = setting_val($cid,'smtp_user');
    $smtpPass = setting_val($cid,'smtp_pass');
    $smtpPort = (int)(setting_val($cid,'smtp_port') ?? 0);
    $smtpSecure = setting_val($cid,'smtp_secure'); // tls/ssl

    if ($smtpHost) {
      $mail->isSMTP();
      $mail->Host = $smtpHost;
      $mail->SMTPAuth = true;
      $mail->Username = $smtpUser ?? '';
      $mail->Password = $smtpPass ?? '';
      if ($smtpSecure) $mail->SMTPSecure = $smtpSecure;
      if ($smtpPort > 0) $mail->Port = $smtpPort;
    } else {
      $mail->isMail();
    }

    $mail->setFrom($fromEmail ?: 'no-reply@localhost', $fromName ?: 'Invoices');
    $mail->addAddress($to);
    if ($cc  !== '') foreach (preg_split('/[;,]+/', $cc)  as $a) { $a=trim($a); if($a) $mail->addCC($a); }
    if ($bcc !== '') foreach (preg_split('/[;,]+/', $bcc) as $a) { $a=trim($a); if($a) $mail->addBCC($a); }

    $subject = $subj !== '' ? $subj : ("Invoice ".$invoiceNo." - ".$brandName);
    $mail->Subject = $subject;

    $body  = '<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#111">';
    $body .= '<p>Dear '.e($invoice['bill_to_name'] ?? 'Client').',</p>';
    $body .= '<p>Please find attached your invoice <strong>'.e($invoiceNo).'</strong>.';
    if ($dueDate) $body .= ' Due date: <strong>'.e($dueDate).'</strong>.';
    $body .= '</p>';
    $body .= '<p>Total Amount: <strong>£ '.n2((float)$total).'</strong></p>';
    $body .= '<p>Kind regards,<br>'.e($brandName).'</p>';
    $body .= '<hr><div style="color:#6b7280;font-size:12px;">'.e($contactLine).'</div>';
    $body .= '</div>';

    $mail->isHTML(true);
    $mail->Body    = $body;
    $mail->AltBody = "Invoice {$invoiceNo}\nTotal: £ ".n2((float)$total)."\n\n{$brandName}\n{$contactLine}";
    $mail->addStringAttachment($pdfData, $safeName, 'base64', 'application/pdf');
    $mail->send();

    db()->prepare("UPDATE invoices SET status='sent' WHERE id=:id AND company_id=:cid")->execute([':id'=>$iid, ':cid'=>$cid]);
    audit_log('invoice.email','invoice',$iid, ['to'=>$to,'subject'=>$subject]);

    redirect(url_modules('invoices/view.php').'?id='.$iid.'&sent=1');
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Failed to send email.';
  }
}

/* Render form */
include dirname(__DIR__, 2) . '/includes/header.php';
$defaultTo   = $invoice['bill_to_email'] ?? '';
$defaultSubj = 'Invoice '.$invoiceNo.' - '.$brandName;
$defaultMsg  = "Dear ".($invoice['bill_to_name'] ?? 'Client').",\n\nPlease find attached your invoice {$invoiceNo}.\n".
               ($dueDate ? "Due date: {$dueDate}\n" : "").
               "Total Amount: £ ".n2((float)$total)."\n\nKind regards,\n{$brandName}";
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Send Invoice Email</h1>
  <div><a class="btn btn-outline-secondary" href="<?= e(url_modules('invoices/view.php').'?id='.$iid) ?>">Back to Invoice</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)$iid ?>">

      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">To <span class="text-danger">*</span></label>
          <input type="email" class="form-control" name="to" required value="<?= e($defaultTo) ?>">
          <div class="form-text">Separate multiple emails with comma or semicolon.</div>
        </div>
        <div class="col-md-3">
          <label class="form-label">CC</label>
          <input type="text" class="form-control" name="cc">
        </div>
        <div class="col-md-3">
          <label class="form-label">BCC</label>
          <input type="text" class="form-control" name="bcc">
        </div>

        <div class="col-12">
          <label class="form-label">Subject</label>
          <input class="form-control" name="subject" value="<?= e($defaultSubj) ?>">
        </div>

        <div class="col-12">
          <label class="form-label">Message</label>
          <textarea class="form-control" name="message" rows="6"><?= e($defaultMsg) ?></textarea>
        </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('invoices/view.php').'?id='.$iid) ?>">Cancel</a>
      </div>
    </form>
  </div>
</div>

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