<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';

require_admin();

$pageTitle = 'Email Templates';
$success = '';
$error = '';

if (isset($_GET['updated'])) {
    $success = 'Email template updated successfully.';
}

if (isset($_GET['created'])) {
    $success = 'Default email templates created successfully.';
}

if (isset($_GET['create_defaults'])) {
    $defaultTemplates = [
        [
            'template_key' => 'order_confirmation',
            'subject' => 'Your {{site_name}} order {{order_number}} has been received',
            'body' => "Hi {{customer_name}},\n\nThank you for your order {{order_number}}.\n\nOrder Total: {{order_total}}\n\nWe will update you once your order progresses.\n\nThank you,\n{{site_name}}"
        ],
        [
            'template_key' => 'payment_status_update',
            'subject' => 'Payment update for order {{order_number}}',
            'body' => "Hi {{customer_name}},\n\nYour payment status for order {{order_number}} is now: {{payment_status}}.\n\nThank you,\n{{site_name}}"
        ],
        [
            'template_key' => 'referral_reward_issued',
            'subject' => 'You earned {{points}} referral points',
            'body' => "Hi {{customer_name}},\n\nYour referral reward has been issued.\n\nPoints earned: {{points}}\n\nThank you for sharing {{site_name}}."
        ],
    ];

    foreach ($defaultTemplates as $template) {
        $stmt = $pdo->prepare("
            INSERT INTO email_templates (
                template_key,
                subject,
                body,
                status
            ) VALUES (?, ?, ?, 'active')
            ON DUPLICATE KEY UPDATE
                subject = VALUES(subject),
                body = VALUES(body),
                status = 'active',
                updated_at = CURRENT_TIMESTAMP
        ");

        $stmt->execute([
            $template['template_key'],
            $template['subject'],
            $template['body']
        ]);
    }

    redirect(ADMIN_URL . '/email-templates.php?created=1');
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $templateId = (int) ($_POST['template_id'] ?? 0);
        $subject = trim($_POST['subject'] ?? '');
        $body = trim($_POST['body'] ?? '');
        $status = $_POST['status'] ?? 'active';

        if ($templateId <= 0) {
            $error = 'Invalid template.';
        } elseif ($subject === '') {
            $error = 'Subject is required.';
        } elseif ($body === '') {
            $error = 'Body is required.';
        } elseif (!in_array($status, ['active', 'inactive'], true)) {
            $error = 'Invalid status.';
        } else {
            $stmt = $pdo->prepare("
                UPDATE email_templates
                SET subject = ?,
                    body = ?,
                    status = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $subject,
                $body,
                $status,
                $templateId
            ]);

            redirect(ADMIN_URL . '/email-templates.php?updated=1');
        }
    }
}

$templates = $pdo->query("
    SELECT *
    FROM email_templates
    ORDER BY template_key ASC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Email Templates</h1>
            <div class="admin-user">Manage email templates before SMTP integration.</div>
        </div>

        <a class="admin-btn" href="<?= e(ADMIN_URL); ?>/email-templates.php?create_defaults=1">
            Create Default Templates
        </a>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel">
        <h2>Available Variables</h2>
        <p style="color:#666; line-height:1.7;">
            You can use:
            <strong>{{site_name}}</strong>,
            <strong>{{customer_name}}</strong>,
            <strong>{{order_number}}</strong>,
            <strong>{{order_total}}</strong>,
            <strong>{{payment_status}}</strong>,
            <strong>{{points}}</strong>
        </p>
    </section>

    <?php if (!$templates): ?>
        <section class="admin-panel" style="margin-top:24px;">
            <p>No email templates yet. Click <strong>Create Default Templates</strong>.</p>
        </section>
    <?php endif; ?>

    <?php foreach ($templates as $template): ?>
        <section class="admin-panel" style="margin-top:24px;">
            <h2><?= e($template['template_key']); ?></h2>

            <form method="POST">
                <?= csrf_field(); ?>
                <input type="hidden" name="template_id" value="<?= e($template['id']); ?>">

                <div class="admin-field">
                    <label>Subject</label>
                    <input type="text" name="subject" value="<?= e($template['subject']); ?>" required>
                </div>

                <div class="admin-field">
                    <label>Body</label>
                    <textarea name="body" rows="8" required><?= e($template['body']); ?></textarea>
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= $template['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?= $template['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <button type="submit" class="admin-btn">Save Template</button>
            </form>
        </section>
    <?php endforeach; ?>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>