<?php
if (!defined('INSTALLED')) require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();

$demoVars = [
    'customer_name'  => 'Ahmed Khan',
    'company_name'   => setting('company_name','Rig N Dig'),
    'quote_number'   => 'RFQ-00042',
    'estimate_number'=> 'EST-00018',
    'invoice_number' => 'INV-00033',
    'request_number' => 'WS-00007',
    'total'          => 'PKR 125,000.00',
    'subtotal'       => 'PKR 106,838.00',
    'due_date'       => date('d M Y', strtotime('+30 days')),
    'valid_until'    => date('d M Y', strtotime('+15 days')),
    'paid_date'      => date('d M Y'),
    'amount_paid'    => 'PKR 125,000.00',
    'balance_due'    => 'PKR 0.00',
    'equipment'      => 'API 6A Gate Valve 3" 5000PSI',
    'status'         => 'In Progress — Parts Ordered',
    'message'        => 'Your equipment has been inspected. Parts have been ordered and repair is underway. Estimated completion: 3 working days.',
    'email'          => 'ahmed.khan@example.com',
    'temp_password'  => 'Temp@1234',
    'portal_url'     => (defined('SITE_URL') ? rtrim(SITE_URL,'/') : '#') . '/portal/login.php',
    'reset_link'     => (defined('SITE_URL') ? rtrim(SITE_URL,'/') : '#') . '/portal/reset-password.php?token=SAMPLETOKEN123',
    'subject'        => 'New Arrivals — API Flanges & Valves Now In Stock',
    'content'        => '<p>We are pleased to introduce our latest stock of <strong>API 6A Flanges</strong> and <strong>Cameron Gate Valves</strong>, now available for immediate delivery from our Islamabad warehouse.</p><p>As one of our valued customers, you get <strong>priority access</strong> and special bulk pricing.</p>',
    'site_url'       => defined('SITE_URL') ? SITE_URL : '#',
    'year'           => date('Y'),
];

// POST from live preview (body typed in editor)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body = $_POST['body'] ?? '';
    foreach ($demoVars as $k => $v) {
        $body = str_replace('{{' . $k . '}}', $v, $body);
    }
    echo emailHtmlWrapper($body);
    exit;
}

// GET: load from DB
$id  = (int)($_GET['id'] ?? 0);
$tpl = $id ? Database::fetchOne("SELECT * FROM email_templates WHERE id=?", [$id]) : null;
if (!$tpl) {
    echo '<p style="font-family:sans-serif;padding:20px;color:#666;">Select a template to preview.</p>';
    exit;
}
$body = $tpl['body'];
foreach ($demoVars as $k => $v) {
    $body = str_replace('{{' . $k . '}}', $v, $body);
}
echo emailHtmlWrapper($body);
