<?php
/**
 * Mailer Helper
 * --------------------------------------------------------------
 * Wraps PHPMailer to send automated emails for:
 *   - Quotations (sent to sale_vendors.email)
 *   - Delivery Notes
 *   - Tax Invoices
 *
 * SMTP CREDENTIALS: edit config/email.php directly (not the
 * Settings page in the app - that no longer controls email).
 *
 * REQUIREMENT: PHPMailer must be installed via composer:
 *      composer require phpmailer/phpmailer
 * This creates /vendor/autoload.php which is required below.
 * --------------------------------------------------------------
 */

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/PdfHelper.php';

// Load bundled PHPMailer (no Composer required - source files are
// directly included in vendor/phpmailer/src/, loaded via vendor/autoload.php)
$autoload = __DIR__ . '/../vendor/autoload.php';
$autoloadFound = file_exists($autoload);
if ($autoloadFound) {
    require_once $autoload;
}

// Load SMTP credentials directly from config/email.php (hardcoded file, not database)
$emailConfig = require __DIR__ . '/../config/email.php';

class Mailer {

    /**
     * Send an email using SMTP settings from config/email.php.
     *
     * @param string $toEmail
     * @param string $toName
     * @param string $subject
     * @param string $htmlBody
     * @param array  $attachments  array of ['path' => '/full/path.pdf', 'name' => 'invoice.pdf']
     *                             OR      ['string' => '<pdf bytes>', 'name' => 'invoice.pdf']
     * @return array ['success' => bool, 'error' => string|null]
     */
    public static function send($toEmail, $toName, $subject, $htmlBody, $attachments = []) {
        global $autoload, $autoloadFound, $emailConfig;

        if (empty($toEmail) || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
            return ['success' => false, 'error' => "Invalid or missing email address ($toEmail). Please update the customer's email in Sale Customers."];
        }

        if (class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
            return self::sendViaPHPMailer($toEmail, $toName, $subject, $htmlBody, $attachments, $emailConfig);
        }

        // PHPMailer class not found - figure out WHY so the error is actually useful
        if (!$autoloadFound) {
            return [
                'success' => false,
                'error' => "PHPMailer files are missing. Expected vendor/autoload.php at: $autoload — "
                    . "this file (and the vendor/phpmailer/src/ folder next to it) should already be bundled with the app. "
                    . "If they're missing, re-download/re-upload the full application package so the 'vendor' folder is restored inside 'stockapp'."
            ];
        }

        return [
            'success' => false,
            'error' => "vendor/autoload.php was found and loaded, but the PHPMailer class still doesn't exist. "
                . "Check that vendor/phpmailer/src/PHPMailer.php, SMTP.php and Exception.php actually exist and aren't empty/corrupted files."
        ];
    }

    private static function sendViaPHPMailer($toEmail, $toName, $subject, $htmlBody, $attachments, $cfg) {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $debugLog = [];

        try {
            $smtpHost = $cfg['smtp_host'] ?? '';
            $smtpUser = $cfg['smtp_username'] ?? '';
            $smtpPass = $cfg['smtp_password'] ?? '';

            if (empty($smtpHost) || empty($smtpUser) || empty($smtpPass)
                || $smtpHost === 'smtp.example.com' || $smtpUser === 'your-email@gmail.com' || $smtpUser === 'your-email@example.com') {
                return [
                    'success' => false,
                    'error' => 'SMTP not configured yet. Open config/email.php and edit smtp_host, smtp_username, smtp_password with your real values.'
                ];
            }

            $mail->isSMTP();
            $mail->Host       = $smtpHost;
            $mail->SMTPAuth   = true;
            $mail->Username   = $smtpUser;
            // Strip accidental spaces - Gmail app passwords are often copy-pasted
            // with spaces (e.g. "abcd efgh ijkl mnop") which breaks auth silently.
            $mail->Password   = str_replace(' ', '', $smtpPass);
            $encryption       = $cfg['smtp_encryption'] ?? 'tls';
            $mail->SMTPSecure = ($encryption === 'ssl')
                ? PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS
                : PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = (int) ($cfg['smtp_port'] ?? 587);
            $mail->Timeout    = 20;
            $mail->SMTPKeepAlive = false;

            // Capture verbose SMTP debug output instead of printing it,
            // so we can show the REAL connection/auth error to the user
            // rather than a generic failure message.
            $mail->SMTPDebug = 2;
            $mail->Debugoutput = function($str, $level) use (&$debugLog) {
                $debugLog[] = trim($str);
            };

            $fromEmail = $cfg['from_email'] ?? $smtpUser;
            $fromName  = $cfg['from_name'] ?? getSetting('company_name', 'Seder Core');
            $mail->setFrom($fromEmail, $fromName);
            $mail->addAddress($toEmail, $toName);
            $mail->addReplyTo($fromEmail, $fromName);

            // Support both file-path attachments and in-memory string attachments
            foreach ($attachments as $att) {
                if (!empty($att['string'])) {
                    // Attach from memory (generated PDF bytes)
                    $mail->addStringAttachment($att['string'], $att['name'] ?? 'document.pdf', 'base64', 'application/pdf');
                } elseif (!empty($att['path']) && file_exists($att['path'])) {
                    $mail->addAttachment($att['path'], $att['name'] ?? basename($att['path']));
                }
            }

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $htmlBody;
            $mail->AltBody = strip_tags($htmlBody);

            $mail->send();
            return ['success' => true, 'error' => null];

        } catch (Exception $e) {
            $detail = $mail->ErrorInfo ?: $e->getMessage();
            // Append the last few SMTP debug lines so the real cause
            // (auth failed, connection refused, port blocked, etc.) is visible.
            $relevantDebug = array_slice($debugLog, -6);
            if ($relevantDebug) {
                $detail .= ' | SMTP debug: ' . implode(' >> ', $relevantDebug);
            }
            return ['success' => false, 'error' => $detail];
        }
    }

    /**
     * Log an email send attempt to the email_logs table
     */
    public static function logEmail($type, $referenceId, $toEmail, $subject, $status, $error = null) {
        global $pdo;
        $pdo->prepare("INSERT INTO email_logs (email_type, reference_id, to_email, subject, status, error_message)
                        VALUES (?,?,?,?,?,?)")
            ->execute([$type, $referenceId, $toEmail, $subject, $status, $error]);
    }

    // -------------------------------------------------------
    // Private: build HTML for each document type
    // (mirrors the logic in quotation_pdf.php / delivery_pdf.php / invoice_pdf.php
    //  but runs server-side so we can generate PDF bytes for attachment)
    // -------------------------------------------------------

    private static function buildQuotationHtml($q, $lineItems) {
        $rupee = '&#8377;';
        $companyName    = getSetting('company_name', 'Your Company');
        $companyAddress = getSetting('company_address', '');
        $companyGst     = getSetting('company_gst', '');
        $companyPhone   = getSetting('company_phone', '');
        $companyEmail   = getSetting('company_email', '');

        $qSubtotalFinal = 0; $qCgstFinal = 0; $qSgstFinal = 0;
        foreach ($lineItems as $li) {
            $originalTotal = $li['line_total_before_discount'] ?: 0;
            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
            $qSubtotalFinal += round($li['line_subtotal'] * $ratio, 2);
            $qCgstFinal     += round($li['line_cgst'] * $ratio, 2);
            $qSgstFinal     += round($li['line_sgst'] * $ratio, 2);
        }

        $html = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: "DejaVu Sans", Arial, sans-serif; font-size: 11px; color: #222; padding: 24px; }
.header { display: table; width: 100%; margin-bottom: 16px; }
.header-left { display: table-cell; vertical-align: top; width: 60%; }
.header-right { display: table-cell; vertical-align: top; text-align: right; width: 40%; }
.company-name { font-size: 20px; font-weight: bold; color: #1D4E4A; margin-bottom: 4px; }
.company-info { font-size: 10px; color: #555; line-height: 1.6; }
.doc-title { font-size: 22px; font-weight: bold; color: #1D4E4A; letter-spacing: 2px; }
.doc-no { font-size: 13px; font-weight: bold; color: #333; margin-top: 4px; }
.doc-meta { font-size: 10px; color: #555; margin-top: 3px; line-height: 1.6; }
hr.divider { border: none; border-top: 1.5px solid #1D4E4A; margin: 12px 0; }
.to-section { margin-bottom: 14px; }
.to-label { font-size: 9px; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; color: #888; margin-bottom: 4px; }
.to-name { font-size: 13px; font-weight: bold; color: #1D4E4A; }
.to-info { font-size: 10px; color: #444; line-height: 1.6; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 16px; }
thead tr { background-color: #1D4E4A; color: #fff; }
th { padding: 7px 6px; text-align: left; font-size: 10px; font-weight: bold; white-space: nowrap; }
th.num { text-align: right; }
td { padding: 6px 6px; font-size: 10px; border-bottom: 1px solid #E8E4DC; vertical-align: top; }
td.num { text-align: right; white-space: nowrap; }
tr:nth-child(even) td { background: #F9F7F2; }
.totals-table { width: 260px; margin-left: auto; border-collapse: collapse; }
.totals-table td { padding: 4px 6px; font-size: 11px; border: none; }
.totals-table .lbl { color: #666; }
.totals-table .val { text-align: right; font-weight: bold; }
.grand-row td { font-size: 14px; font-weight: bold; color: #1D4E4A; border-top: 2px solid #1D4E4A; padding-top: 7px; }
.notes { font-size: 10px; color: #555; margin-top: 12px; line-height: 1.5; }
.footer-note { font-size: 9px; color: #999; margin-top: 14px; border-top: 1px solid #eee; padding-top: 8px; text-align: center; }
</style></head><body>
<div class="header">
  <div class="header-left">
    <div class="company-name">' . htmlspecialchars($companyName) . '</div>
    <div class="company-info">' . nl2br(htmlspecialchars($companyAddress)) . '<br>'
        . ($companyGst   ? 'GSTIN: ' . htmlspecialchars($companyGst) . '<br>' : '')
        . ($companyPhone ? 'Phone: ' . htmlspecialchars($companyPhone) : '')
        . ($companyEmail ? ' | Email: ' . htmlspecialchars($companyEmail) : '') . '
    </div>
  </div>
  <div class="header-right">
    <div class="doc-title">QUOTATION</div>
    <div class="doc-no">' . htmlspecialchars($q['quotation_no']) . '</div>
    <div class="doc-meta">Date: ' . date('d-M-Y', strtotime($q['quotation_date'])) . '<br>
      Valid Until: ' . ($q['valid_until'] ? date('d-M-Y', strtotime($q['valid_until'])) : 'N/A') . '<br>
      Status: ' . strtoupper($q['status']) . '
    </div>
  </div>
</div>
<hr class="divider">
<div class="to-section">
  <div class="to-label">Bill To</div>
  <div class="to-name">' . htmlspecialchars($q['customer_name']) . '</div>
  <div class="to-info">' . nl2br(htmlspecialchars($q['shipping_address'] ?: $q['billing_address'])) . '<br>'
        . htmlspecialchars($q['city']) . ($q['city'] && $q['state'] ? ', ' : '') . htmlspecialchars($q['state']) . ' ' . htmlspecialchars($q['pincode']) . '<br>'
        . ($q['customer_gst'] ? 'GSTIN: ' . htmlspecialchars($q['customer_gst']) . '<br>' : '')
        . 'Phone: ' . htmlspecialchars($q['phone']) . '
  </div>
</div>
<hr class="divider">
<table>
  <thead>
    <tr>
      <th style="width:28px">#</th><th>Item Description</th><th>HSN</th>
      <th class="num">Qty</th><th class="num">Unit</th><th class="num">Rate (excl. GST)</th>
      <th class="num">CGST</th><th class="num">SGST</th><th class="num">Amount</th>
    </tr>
  </thead>
  <tbody>';

        $sno = 1;
        foreach ($lineItems as $li) {
            $originalTotal = $li['line_total_before_discount'] ?: 0;
            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
            $finalBase = round($li['line_subtotal'] * $ratio, 2);
            $finalCgst = round($li['line_cgst'] * $ratio, 2);
            $finalSgst = round($li['line_sgst'] * $ratio, 2);
            $effectiveRate = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;

            $html .= '<tr>
      <td>' . $sno++ . '</td>
      <td>' . htmlspecialchars($li['item_name']) . '</td>
      <td>' . htmlspecialchars($li['hsn_code'] ?: '-') . '</td>
      <td class="num">' . $li['qty'] . '</td>
      <td class="num">' . htmlspecialchars($li['unit']) . '</td>
      <td class="num">' . $rupee . number_format($effectiveRate, 2) . '</td>
      <td class="num">' . $rupee . number_format($finalCgst, 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['cgst_percent'], 1) . '%)</span></td>
      <td class="num">' . $rupee . number_format($finalSgst, 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['sgst_percent'], 1) . '%)</span></td>
      <td class="num"><strong>' . $rupee . number_format($li['line_final_amount'], 2) . '</strong></td>
    </tr>';
        }

        $html .= '</tbody></table>
<table class="totals-table">
  <tr><td class="lbl">Subtotal</td><td class="val">' . $rupee . number_format($qSubtotalFinal, 2) . '</td></tr>
  <tr><td class="lbl">CGST</td><td class="val">' . $rupee . number_format($qCgstFinal, 2) . '</td></tr>
  <tr><td class="lbl">SGST</td><td class="val">' . $rupee . number_format($qSgstFinal, 2) . '</td></tr>
  <tr class="grand-row"><td class="lbl">Grand Total</td><td class="val">' . $rupee . number_format($q['grand_total'], 2) . '</td></tr>
</table>';

        if (!empty($q['notes'])) {
            $html .= '<div class="notes"><strong>Notes:</strong> ' . nl2br(htmlspecialchars($q['notes'])) . '</div>';
        }

        $html .= '<div class="footer-note">This is a system-generated quotation. Prices are inclusive of applicable taxes.</div>
</body></html>';

        return $html;
    }

    private static function buildDeliveryHtml($d, $lineItems) {
        $rupee = '&#8377;';
        $companyName    = getSetting('company_name', 'Your Company');
        $companyAddress = getSetting('company_address', '');
        $companyGst     = getSetting('company_gst', '');
        $companyPhone   = getSetting('company_phone', '');
        $companyEmail   = getSetting('company_email', '');

        // Calculate totals (same logic as delivery_pdf.php)
        $dnSubtotal = 0; $dnCgst = 0; $dnSgst = 0; $dnTotal = 0;
        foreach ($lineItems as $li) {
            $originalTotal = $li['line_total_before_discount'] ?: 0;
            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
            $finalBase = round(($li['line_subtotal'] ?? 0) * $ratio, 2);
            $finalCgst = round(($li['line_cgst'] ?? 0) * $ratio, 2);
            $finalSgst = round(($li['line_sgst'] ?? 0) * $ratio, 2);
            $dnSubtotal += $finalBase;
            $dnCgst     += $finalCgst;
            $dnSgst     += $finalSgst;
            $dnTotal    += $finalBase + $finalCgst + $finalSgst;
        }

        $deliveredInfo = '';
        if (($d['status'] ?? '') === 'delivered' && !empty($d['delivered_datetime'])) {
            $deliveredInfo = 'Delivered: ' . date('d-M-Y h:i A', strtotime($d['delivered_datetime']));
        }

        $html = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: "DejaVu Sans", Arial, sans-serif; font-size: 11px; color: #222; padding: 24px; }
.header { display: table; width: 100%; margin-bottom: 16px; }
.header-left { display: table-cell; vertical-align: top; width: 60%; }
.header-right { display: table-cell; vertical-align: top; text-align: right; width: 40%; }
.company-name { font-size: 20px; font-weight: bold; color: #1D4E4A; margin-bottom: 4px; }
.company-info { font-size: 10px; color: #555; line-height: 1.6; }
.doc-title { font-size: 22px; font-weight: bold; color: #1D4E4A; letter-spacing: 2px; }
.doc-no { font-size: 13px; font-weight: bold; color: #333; margin-top: 4px; }
.doc-meta { font-size: 10px; color: #555; margin-top: 3px; line-height: 1.6; }
hr { border: none; border-top: 1.5px solid #1D4E4A; margin: 12px 0; }
.to-label { font-size: 9px; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; color: #888; margin-bottom: 4px; }
.to-name { font-size: 13px; font-weight: bold; color: #1D4E4A; }
.to-info { font-size: 10px; color: #444; line-height: 1.6; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; margin: 14px 0; }
thead tr { background-color: #1D4E4A; color: #fff; }
th { padding: 7px 6px; text-align: left; font-size: 10px; font-weight: bold; white-space: nowrap; }
th.num { text-align: right; }
td { padding: 6px 6px; font-size: 10px; border-bottom: 1px solid #E8E4DC; vertical-align: top; }
td.num { text-align: right; white-space: nowrap; }
tr:nth-child(even) td { background: #F9F7F2; }
.totals-table { width: 260px; margin-left: auto; border-collapse: collapse; }
.totals-table td { padding: 4px 6px; font-size: 11px; border: none; }
.totals-table .lbl { color: #666; }
.totals-table .val { text-align: right; font-weight: bold; }
.grand-row td { font-size: 14px; font-weight: bold; color: #1D4E4A; border-top: 2px solid #1D4E4A; padding-top: 7px; }
.footer-note { font-size: 9px; color: #999; margin-top: 14px; border-top: 1px solid #eee; padding-top: 8px; text-align: center; }
</style></head><body>
<div class="header">
  <div class="header-left">
    <div class="company-name">' . htmlspecialchars($companyName) . '</div>
    <div class="company-info">' . nl2br(htmlspecialchars($companyAddress)) . '<br>'
        . ($companyGst   ? 'GSTIN: ' . htmlspecialchars($companyGst) . '<br>' : '')
        . ($companyPhone ? 'Phone: ' . htmlspecialchars($companyPhone) : '')
        . ($companyEmail ? ' | Email: ' . htmlspecialchars($companyEmail) : '') . '
    </div>
  </div>
  <div class="header-right">
    <div class="doc-title">DELIVERY NOTE</div>
    <div class="doc-no">' . htmlspecialchars($d['delivery_no']) . '</div>
    <div class="doc-meta">Date: ' . date('d-M-Y', strtotime($d['delivery_date']))
        . ($deliveredInfo ? '<br>' . $deliveredInfo : '') . '</div>
  </div>
</div>
<hr>
<div style="margin-bottom:14px;">
  <div class="to-label">Deliver To</div>
  <div class="to-name">' . htmlspecialchars($d['customer_name']) . '</div>
  <div class="to-info">'
        . nl2br(htmlspecialchars($d['shipping_address'] ?: $d['billing_address'])) . '<br>'
        . htmlspecialchars($d['city']) . ($d['city'] && $d['state'] ? ', ' : '') . htmlspecialchars($d['state']) . ' ' . htmlspecialchars($d['pincode']) . '<br>'
        . 'Phone: ' . htmlspecialchars($d['phone']) . '
  </div>
</div>
<hr>
<table>
  <thead>
    <tr>
      <th style="width:28px">#</th><th>Item</th>
      <th class="num">Qty</th><th class="num">Unit</th>
      <th class="num">Rate</th><th class="num">CGST</th><th class="num">SGST</th><th class="num">Amount</th>
    </tr>
  </thead>
  <tbody>';

        $sno = 1;
        foreach ($lineItems as $li) {
            $originalTotal = $li['line_total_before_discount'] ?: 0;
            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
            $finalBase = round(($li['line_subtotal'] ?? 0) * $ratio, 2);
            $finalCgst = round(($li['line_cgst'] ?? 0) * $ratio, 2);
            $finalSgst = round(($li['line_sgst'] ?? 0) * $ratio, 2);
            $finalAmt  = $finalBase + $finalCgst + $finalSgst;
            $effectiveRate = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;

            $html .= '<tr>
      <td>' . $sno++ . '</td>
      <td>' . htmlspecialchars($li['item_name']) . '</td>
      <td class="num">' . $li['qty'] . '</td>
      <td class="num">' . htmlspecialchars($li['unit']) . '</td>
      <td class="num">' . $rupee . number_format($effectiveRate, 2) . '</td>
      <td class="num">' . $rupee . number_format($finalCgst, 2)
          . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['cgst_percent'] ?? 0, 1) . '%)</span></td>
      <td class="num">' . $rupee . number_format($finalSgst, 2)
          . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['sgst_percent'] ?? 0, 1) . '%)</span></td>
      <td class="num"><strong>' . $rupee . number_format($finalAmt, 2) . '</strong></td>
    </tr>';
        }

        $html .= '</tbody></table>
<table class="totals-table">
  <tr><td class="lbl">Subtotal</td><td class="val">' . $rupee . number_format($dnSubtotal, 2) . '</td></tr>
  <tr><td class="lbl">CGST</td><td class="val">' . $rupee . number_format($dnCgst, 2) . '</td></tr>
  <tr><td class="lbl">SGST</td><td class="val">' . $rupee . number_format($dnSgst, 2) . '</td></tr>
  <tr class="grand-row"><td class="lbl">Total Amount</td><td class="val">' . $rupee . number_format($dnTotal, 2) . '</td></tr>
</table>';

        if (!empty($d['notes'])) {
            $html .= '<p style="font-size:10px;color:#555;margin-top:12px;"><strong>Notes:</strong> ' . nl2br(htmlspecialchars($d['notes'])) . '</p>';
        }

        $html .= '<div class="footer-note">This is a system-generated delivery note.</div>
</body></html>';
        return $html;
    }

    private static function buildInvoiceHtml($inv, $lineItems) {
        $rupee = '&#8377;';
        $companyName    = getSetting('company_name', 'Your Company');
        $companyAddress = getSetting('company_address', '');
        $companyGst     = getSetting('company_gst', '');
        $companyPhone   = getSetting('company_phone', '');
        $companyEmail   = getSetting('company_email', '');

        $subtotal = 0; $cgstTotal = 0; $sgstTotal = 0;
        foreach ($lineItems as $li) {
            $subtotal   += $li['line_subtotal'] ?? 0;
            $cgstTotal  += $li['line_cgst'] ?? 0;
            $sgstTotal  += $li['line_sgst'] ?? 0;
        }

        $html = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: "DejaVu Sans", Arial, sans-serif; font-size: 11px; color: #222; padding: 24px; }
.header { display: table; width: 100%; margin-bottom: 16px; }
.header-left { display: table-cell; vertical-align: top; width: 60%; }
.header-right { display: table-cell; vertical-align: top; text-align: right; width: 40%; }
.company-name { font-size: 20px; font-weight: bold; color: #1D4E4A; margin-bottom: 4px; }
.company-info { font-size: 10px; color: #555; line-height: 1.6; }
.doc-title { font-size: 22px; font-weight: bold; color: #1D4E4A; letter-spacing: 2px; }
.doc-no { font-size: 13px; font-weight: bold; color: #333; margin-top: 4px; }
.doc-meta { font-size: 10px; color: #555; margin-top: 3px; line-height: 1.6; }
hr.divider { border: none; border-top: 1.5px solid #1D4E4A; margin: 12px 0; }
.to-section { margin-bottom: 14px; }
.to-label { font-size: 9px; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; color: #888; margin-bottom: 4px; }
.to-name { font-size: 13px; font-weight: bold; color: #1D4E4A; }
.to-info { font-size: 10px; color: #444; line-height: 1.6; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 16px; }
thead tr { background-color: #1D4E4A; color: #fff; }
th { padding: 7px 6px; text-align: left; font-size: 10px; font-weight: bold; white-space: nowrap; }
th.num { text-align: right; }
td { padding: 6px 6px; font-size: 10px; border-bottom: 1px solid #E8E4DC; vertical-align: top; }
td.num { text-align: right; white-space: nowrap; }
tr:nth-child(even) td { background: #F9F7F2; }
.totals-table { width: 260px; margin-left: auto; border-collapse: collapse; }
.totals-table td { padding: 4px 6px; font-size: 11px; border: none; }
.totals-table .lbl { color: #666; }
.totals-table .val { text-align: right; font-weight: bold; }
.grand-row td { font-size: 14px; font-weight: bold; color: #1D4E4A; border-top: 2px solid #1D4E4A; padding-top: 7px; }
.footer-note { font-size: 9px; color: #999; margin-top: 14px; border-top: 1px solid #eee; padding-top: 8px; text-align: center; }
</style></head><body>
<div class="header">
  <div class="header-left">
    <div class="company-name">' . htmlspecialchars($companyName) . '</div>
    <div class="company-info">' . nl2br(htmlspecialchars($companyAddress)) . '<br>'
        . ($companyGst   ? 'GSTIN: ' . htmlspecialchars($companyGst) . '<br>' : '')
        . ($companyPhone ? 'Phone: ' . htmlspecialchars($companyPhone) : '')
        . ($companyEmail ? ' | Email: ' . htmlspecialchars($companyEmail) : '') . '
    </div>
  </div>
  <div class="header-right">
    <div class="doc-title">TAX INVOICE</div>
    <div class="doc-no">' . htmlspecialchars($inv['invoice_no']) . '</div>
    <div class="doc-meta">Date: ' . date('d-M-Y', strtotime($inv['invoice_date'])) . '</div>
  </div>
</div>
<hr class="divider">
<div class="to-section">
  <div class="to-label">Bill To</div>
  <div class="to-name">' . htmlspecialchars($inv['customer_name']) . '</div>
  <div class="to-info">' . nl2br(htmlspecialchars($inv['billing_address'] ?? '')) . '<br>'
        . ($inv['customer_gst'] ?? '' ? 'GSTIN: ' . htmlspecialchars($inv['customer_gst']) . '<br>' : '')
        . 'Phone: ' . htmlspecialchars($inv['phone'] ?? '') . '
  </div>
</div>
<hr class="divider">
<table>
  <thead>
    <tr>
      <th style="width:28px">#</th><th>Item Description</th><th>HSN</th>
      <th class="num">Qty</th><th class="num">Unit</th><th class="num">Rate (excl. GST)</th>
      <th class="num">CGST</th><th class="num">SGST</th><th class="num">Amount</th>
    </tr>
  </thead>
  <tbody>';

        $sno = 1;
        foreach ($lineItems as $li) {
            $html .= '<tr>
      <td>' . $sno++ . '</td>
      <td>' . htmlspecialchars($li['item_name']) . '</td>
      <td>' . htmlspecialchars($li['hsn_code'] ?: '-') . '</td>
      <td class="num">' . $li['qty'] . '</td>
      <td class="num">' . htmlspecialchars($li['unit']) . '</td>
      <td class="num">' . $rupee . number_format($li['unit_price'] ?? 0, 2) . '</td>
      <td class="num">' . $rupee . number_format($li['line_cgst'] ?? 0, 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['cgst_percent'] ?? 0, 1) . '%)</span></td>
      <td class="num">' . $rupee . number_format($li['line_sgst'] ?? 0, 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['sgst_percent'] ?? 0, 1) . '%)</span></td>
      <td class="num"><strong>' . $rupee . number_format($li['line_total'] ?? 0, 2) . '</strong></td>
    </tr>';
        }

        $html .= '</tbody></table>
<table class="totals-table">
  <tr><td class="lbl">Subtotal</td><td class="val">' . $rupee . number_format($subtotal, 2) . '</td></tr>
  <tr><td class="lbl">CGST</td><td class="val">' . $rupee . number_format($cgstTotal, 2) . '</td></tr>
  <tr><td class="lbl">SGST</td><td class="val">' . $rupee . number_format($sgstTotal, 2) . '</td></tr>';

        if (!empty($inv['tds_amount']) && $inv['tds_amount'] > 0) {
            $html .= '<tr><td class="lbl">TDS Deducted</td><td class="val">- ' . $rupee . number_format($inv['tds_amount'], 2) . '</td></tr>';
        }

        $html .= '<tr class="grand-row"><td class="lbl">Grand Total</td><td class="val">' . $rupee . number_format($inv['grand_total'], 2) . '</td></tr>
</table>
<div class="footer-note">This is a system-generated tax invoice.</div>
</body></html>';
        return $html;
    }

    // -------------------------------------------------------
    // Public high-level send methods
    // -------------------------------------------------------

    /**
     * High level: send quotation email with PDF attachment
     */
    public static function sendQuotation($quotationId) {
        global $pdo;

        $stmt = $pdo->prepare("SELECT q.*, c.customer_name, c.email, c.phone, c.billing_address, c.shipping_address,
                                       c.gst_number as customer_gst, c.city, c.state, c.pincode
                                FROM quotations q
                                JOIN sale_vendors c ON c.id = q.customer_id
                                WHERE q.id = ?");
        $stmt->execute([$quotationId]);
        $q = $stmt->fetch();
        if (!$q) return ['success' => false, 'error' => 'Quotation not found'];
        if (empty($q['email'])) return ['success' => false, 'error' => 'Customer email not set'];

        // Fetch line items
        $stmt2 = $pdo->prepare("SELECT qi.*, i.item_name, i.item_code, i.hsn_code, i.unit
                                 FROM quotation_items qi JOIN items i ON i.id=qi.item_id
                                 WHERE qi.quotation_id=?");
        $stmt2->execute([$quotationId]);
        $lineItems = $stmt2->fetchAll();

        $companyName = getSetting('company_name', 'Our Company');
        $subject = "Quotation {$q['quotation_no']} from {$companyName}";

        $body = "
            <p>Dear {$q['customer_name']},</p>
            <p>Please find attached the quotation <strong>{$q['quotation_no']}</strong> dated " . formatDate($q['quotation_date']) . ".</p>
            <p><strong>Total Amount: " . formatMoney($q['grand_total']) . "</strong> (inclusive of GST)</p>
            <p>This quotation is valid until " . formatDate($q['valid_until']) . ".</p>
            <p>Kindly review and confirm to proceed.</p>
            <br><p>Thank you,<br>{$companyName}</p>
        ";

        // Generate PDF in memory and attach
        $attachments = [];
        $pdfHtml = self::buildQuotationHtml($q, $lineItems);
        $pdfBytes = PdfHelper::generateString($pdfHtml);
        if ($pdfBytes) {
            $attachments[] = ['string' => $pdfBytes, 'name' => "Quotation_{$q['quotation_no']}.pdf"];
        }

        $result = self::send($q['email'], $q['customer_name'], $subject, $body, $attachments);
        self::logEmail('quotation', $quotationId, $q['email'], $subject, $result['success'] ? 'sent' : 'failed', $result['error']);

        if ($result['success']) {
            $pdo->prepare("UPDATE quotations SET email_sent = 1, email_sent_at = NOW(), status = IF(status='draft','sent',status) WHERE id = ?")
                ->execute([$quotationId]);
        }
        return $result;
    }

    /**
     * High level: send delivery note email with PDF attachment
     */
    public static function sendDeliveryNote($deliveryNoteId) {
        global $pdo;

        $stmt = $pdo->prepare("SELECT d.*, c.customer_name, c.email, c.phone,
                                       c.shipping_address, c.billing_address, c.city, c.state, c.pincode,
                                       q.quotation_no, q.grand_total, q.id as q_id
                                FROM delivery_notes d
                                JOIN sale_vendors c ON c.id = d.customer_id
                                JOIN quotations q ON q.id = d.quotation_id
                                WHERE d.id = ?");
        $stmt->execute([$deliveryNoteId]);
        $d = $stmt->fetch();
        if (!$d) return ['success' => false, 'error' => 'Delivery note not found'];
        if (empty($d['email'])) return ['success' => false, 'error' => 'Customer email not set'];

        // Fetch line items — same query as delivery_pdf.php
        $stmt2 = $pdo->prepare("SELECT dni.*, i.item_name, i.item_code, i.unit,
                                        qi.unit_price, qi.cgst_percent, qi.sgst_percent,
                                        qi.line_subtotal, qi.line_cgst, qi.line_sgst,
                                        qi.line_total_before_discount, qi.line_discount_amount, qi.line_final_amount
                                 FROM delivery_note_items dni
                                 JOIN items i ON i.id = dni.item_id
                                 LEFT JOIN quotation_items qi ON qi.quotation_id = :qid AND qi.item_id = dni.item_id
                                 WHERE dni.delivery_note_id = :did");
        $stmt2->execute(['qid' => $d['q_id'], 'did' => $deliveryNoteId]);
        $lineItems = $stmt2->fetchAll();

        $companyName = getSetting('company_name', 'Our Company');
        $subject = "Delivery Note {$d['delivery_no']} from {$companyName}";

        $body = "
            <p>Dear {$d['customer_name']},</p>
            <p>Your order is on the way. Please find attached the Delivery Note <strong>{$d['delivery_no']}</strong> dated " . formatDate($d['delivery_date']) . ".</p>
            <p>We will notify you once your tax invoice is generated.</p>
            <br><p>Thank you,<br>{$companyName}</p>
        ";

        // Generate PDF in memory and attach
        $attachments = [];
        $pdfHtml = self::buildDeliveryHtml($d, $lineItems);
        $pdfBytes = PdfHelper::generateString($pdfHtml);
        if ($pdfBytes) {
            $attachments[] = ['string' => $pdfBytes, 'name' => "DeliveryNote_{$d['delivery_no']}.pdf"];
        }

        $result = self::send($d['email'], $d['customer_name'], $subject, $body, $attachments);
        self::logEmail('delivery_note', $deliveryNoteId, $d['email'], $subject, $result['success'] ? 'sent' : 'failed', $result['error']);

        if ($result['success']) {
            $pdo->prepare("UPDATE delivery_notes SET email_sent = 1, email_sent_at = NOW() WHERE id = ?")
                ->execute([$deliveryNoteId]);
        }
        return $result;
    }

    /**
     * High level: send tax invoice email with PDF attachment
     */
    public static function sendInvoice($invoiceId) {
        global $pdo;

        $stmt = $pdo->prepare("SELECT i.*, c.customer_name, c.email, c.phone, c.billing_address,
                                       c.gst_number as customer_gst
                                FROM invoices i
                                JOIN sale_vendors c ON c.id = i.customer_id
                                WHERE i.id = ?");
        $stmt->execute([$invoiceId]);
        $inv = $stmt->fetch();
        if (!$inv) return ['success' => false, 'error' => 'Invoice not found'];
        if (empty($inv['email'])) return ['success' => false, 'error' => 'Customer email not set'];

        // Fetch line items
        $stmt2 = $pdo->prepare("SELECT ii.*, it.item_name, it.hsn_code, it.unit
                                 FROM invoice_items ii JOIN items it ON it.id=ii.item_id
                                 WHERE ii.invoice_id=?");
        $stmt2->execute([$invoiceId]);
        $lineItems = $stmt2->fetchAll();

        $companyName = getSetting('company_name', 'Our Company');
        $subject = "Tax Invoice {$inv['invoice_no']} from {$companyName}";

        $tdsLine = ($inv['tds_amount'] ?? 0) > 0
            ? "<p>TDS Deducted: <strong>" . formatMoney($inv['tds_amount']) . "</strong></p>"
            : "";

        $body = "
            <p>Dear {$inv['customer_name']},</p>
            <p>Please find attached the Tax Invoice <strong>{$inv['invoice_no']}</strong> dated " . formatDate($inv['invoice_date']) . ".</p>
            <p><strong>Total Payable: " . formatMoney($inv['grand_total']) . "</strong></p>
            $tdsLine
            <p>Kindly process the payment at your earliest convenience.</p>
            <br><p>Thank you,<br>{$companyName}</p>
        ";

        // Generate PDF in memory and attach
        $attachments = [];
        $pdfHtml = self::buildInvoiceHtml($inv, $lineItems);
        $pdfBytes = PdfHelper::generateString($pdfHtml);
        if ($pdfBytes) {
            $attachments[] = ['string' => $pdfBytes, 'name' => "Invoice_{$inv['invoice_no']}.pdf"];
        }

        $result = self::send($inv['email'], $inv['customer_name'], $subject, $body, $attachments);
        self::logEmail('tax_invoice', $invoiceId, $inv['email'], $subject, $result['success'] ? 'sent' : 'failed', $result['error']);

        if ($result['success']) {
            $pdo->prepare("UPDATE invoices SET email_sent = 1, email_sent_at = NOW() WHERE id = ?")
                ->execute([$invoiceId]);
        }
        return $result;
    }
}