<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';

// Enforce Admin Authorization
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

$success_msg = '';
$error_msg = '';

$config_dir = __DIR__ . '/../config';
if (!is_dir($config_dir)) {
    @mkdir($config_dir, 0755, true);
}

// ---------------------------------------------------------
// 1. SMTP SETTINGS ENGINE
// ---------------------------------------------------------
$settings_file = $config_dir . '/email-settings.json';
$email_settings = [
    'smtp_host'      => 'mail.tipspac.com',
    'smtp_port'      => '465',
    'smtp_user'      => 'no-reply@tipspac.com',
    'smtp_pass'      => '',
    'sender_name'    => 'tipspac Pro AI',
    'email_enabled'  => '0'
];

if (file_exists($settings_file)) {
    $loaded = json_decode(file_get_contents($settings_file), true);
    if (is_array($loaded)) {
        $email_settings = array_merge($email_settings, $loaded);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_email_settings'])) {
    $email_settings['smtp_host']     = trim($_POST['smtp_host'] ?? '');
    $email_settings['smtp_port']     = trim($_POST['smtp_port'] ?? '');
    $email_settings['smtp_user']     = trim($_POST['smtp_user'] ?? '');
    $email_settings['sender_name']   = trim($_POST['sender_name'] ?? '');
    $email_settings['email_enabled'] = isset($_POST['email_enabled']) ? '1' : '0';

    $new_pass = trim($_POST['smtp_pass'] ?? '');
    if ($new_pass !== '') {
        $email_settings['smtp_pass'] = $new_pass;
    }

    if (file_put_contents($settings_file, json_encode($email_settings, JSON_PRETTY_PRINT)) !== false) {
        $success_msg = "SMTP configurations updated successfully.";
    } else {
        $error_msg = "Failed to save SMTP configurations. Check file permissions.";
    }
}

// ---------------------------------------------------------
// 2. MESSAGE TEMPLATE EDITOR ENGINE (EXPANDED)
// ---------------------------------------------------------
$templates_file = $config_dir . '/email-templates.json';

// Comprehensive template definitions with placeholders and descriptions
$default_templates = [
    'welcome' => [
        'subject' => 'Welcome to tipspac Pro AI! ⚽',
        'body' => "Hello {user_name},\n\nWelcome to tipspac – the ultimate AI‑driven football prediction engine. You now have access to free daily tips and can upgrade to VIP for premium insights.\n\nStart exploring: {site_url}\n\nBest,\nThe tipspac Team",
        'description' => 'Sent to new users upon registration.'
    ],
    'account_verification' => [
        'subject' => 'Verify Your Email Address 📧',
        'body' => "Hello {user_name},\n\nPlease verify your email address by clicking the link below:\n\n{verification_link}\n\nIf you did not create an account, please ignore this email.\n\nBest,\nThe tipspac Team",
        'description' => 'Sent to new users requiring email verification.'
    ],
    'reset' => [
        'subject' => 'Password Reset Request 🔐',
        'body' => "Hello {user_name},\n\nWe received a request to reset your password. Use the code below:\n\n{reset_code}\n\nIf you did not request this, please ignore this email.\n\nThe tipspac Team",
        'description' => 'Sent when a user requests a password reset.'
    ],
    'vip_upgrade' => [
        'subject' => 'VIP Upgrade Successful! 👑',
        'body' => "Hello {user_name},\n\nThank you for upgrading to VIP! Your account now has full access to:\n- Exclusive VIP tips\n- AI Bet Builder\n- Advanced analytics\n- Priority support\n\nYour VIP status is active until {expiry_date}.\n\nEnjoy the premium advantage!\nThe tipspac Team",
        'description' => 'Sent after successful VIP payment and activation.'
    ],
    'payment_confirmation' => [
        'subject' => 'Payment Confirmation – tipspac Pro 💳',
        'body' => "Hello {user_name},\n\nWe have received your payment of {amount} {currency} for the {plan_name} plan. Your account has been updated accordingly.\n\nTransaction ID: {transaction_id}\n\nThank you for your trust!\nThe tipspac Team",
        'description' => 'Sent after any successful payment (including manual approvals).'
    ],
    'referral_reward' => [
        'subject' => '🎁 You Earned VIP Days!',
        'body' => "Hello {user_name},\n\nCongratulations! You have referred {referral_count} friends and earned {vip_days} extra VIP days.\n\nYour VIP status is now extended until {expiry_date}.\n\nKeep sharing your referral code: {referral_code}\n\nBest,\nThe tipspac Team",
        'description' => 'Sent when a user earns VIP days through referrals.'
    ],
    'bet_of_the_day_alert' => [
        'subject' => 'Bet of the Day is Live! 🔥',
        'body' => "Hello {user_name},\n\nOur AI has just released today's Bet of the Day. Check it out now:\n\n{bet_of_the_day_link}\n\nDon't miss out on this high‑confidence pick!\n\nThe tipspac Team",
        'description' => 'Sent daily (or when a new Bet of the Day is published).'
    ],
    'new_prediction_alert' => [
        'subject' => 'New AI Predictions Available 📊',
        'body' => "Hello {user_name},\n\nOur neural network has processed the latest matches. New predictions are now available for:\n\n{league_list}\n\nVisit your dashboard to view them.\n\nThe tipspac Team",
        'description' => 'Sent when new predictions are generated for user’s favourite leagues.'
    ],
    'subscription_expiry' => [
        'subject' => 'Your VIP Subscription is Expiring Soon ⏳',
        'body' => "Hello {user_name},\n\nYour VIP access will expire on {expiry_date}. To avoid interruption, renew now:\n\n{renewal_link}\n\nKeep enjoying premium predictions!\nThe tipspac Team",
        'description' => 'Sent 7 days before VIP subscription expiry.'
    ],
    'system_notification' => [
        'subject' => 'System Update – tipspac Pro 🛠️',
        'body' => "Hello {user_name},\n\nWe have performed a system update to improve our prediction accuracy and user experience.\n\nIf you notice any issues, please contact support.\n\nThank you for being part of tipspac!\nThe tipspac Team",
        'description' => 'Sent for general system announcements or maintenance.'
    ]
];

// Load existing templates or create default if missing
if (file_exists($templates_file)) {
    $loaded_templates = json_decode(file_get_contents($templates_file), true);
    if (is_array($loaded_templates)) {
        // Merge with defaults to ensure all keys exist
        $email_templates = array_merge($default_templates, $loaded_templates);
    } else {
        $email_templates = $default_templates;
    }
} else {
    $email_templates = $default_templates;
    file_put_contents($templates_file, json_encode($email_templates, JSON_PRETTY_PRINT));
}

// Process Template Updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    $type = $_POST['template_type'] ?? '';
    
    if (isset($email_templates[$type])) {
        $email_templates[$type]['subject'] = trim($_POST['template_subject'] ?? '');
        $email_templates[$type]['body']    = trim($_POST['template_body'] ?? '');
        // Keep description if not changed
        if (!empty($_POST['template_description'])) {
            $email_templates[$type]['description'] = trim($_POST['template_description']);
        }
        
        if (file_put_contents($templates_file, json_encode($email_templates, JSON_PRETTY_PRINT)) !== false) {
            $success_msg = "Email template successfully updated.";
        } else {
            $error_msg = "Failed to save email template. Check file permissions.";
        }
    } else {
        $error_msg = "Invalid template type selected.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Email Management</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .template-card {
            transition: all 0.2s ease;
        }
        .template-card:hover {
            transform: translateY(-2px);
        }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') document.documentElement.classList.add('dark');
        else document.documentElement.classList.remove('dark');
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Email Management</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Configure SMTP relays and edit automated message templates.</p>
            </div>
            <div class="bg-white dark:bg-slate-900 px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-800 flex items-center gap-3 shadow-sm">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-wider font-bold">Engine:</span>
                <?php if($email_settings['email_enabled'] === '1'): ?>
                    <span class="bg-emerald-50 text-emerald-600 border border-emerald-200 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-500 font-extrabold text-[10px] px-3 py-1 rounded-full uppercase tracking-wider">LIVE</span>
                <?php else: ?>
                    <span class="bg-amber-50 text-amber-600 border border-amber-200 dark:bg-amber-500/10 dark:border-amber-500/30 dark:text-amber-500 font-extrabold text-[10px] px-3 py-1 rounded-full uppercase tracking-wider">DISABLED</span>
                <?php endif; ?>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo htmlspecialchars($success_msg); ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo htmlspecialchars($error_msg); ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Templates Available</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo count($email_templates); ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">SMTP Host</span>
                <span class="text-base font-bold text-cyan-600 dark:text-cyan-400 mt-1 block truncate"><?php echo htmlspecialchars($email_settings['smtp_host']); ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Sender Name</span>
                <span class="text-base font-bold text-emerald-600 dark:text-emerald-400 mt-1 block truncate"><?php echo htmlspecialchars($email_settings['sender_name']); ?></span>
            </div>
        </div>

        <!-- ========== MAIN CONTENT ========== -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            
            <!-- LEFT: SMTP Settings -->
            <div class="space-y-6">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-lg mb-5 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">📨 SMTP Relay Settings</h3>
                    
                    <form action="email-management.php" method="POST" class="space-y-4">
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">SMTP Host</label>
                                <input type="text" name="smtp_host" value="<?php echo htmlspecialchars($email_settings['smtp_host']); ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                            </div>
                            <div>
                                <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Port</label>
                                <input type="text" name="smtp_port" value="<?php echo htmlspecialchars($email_settings['smtp_port']); ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Username</label>
                            <input type="text" name="smtp_user" value="<?php echo htmlspecialchars($email_settings['smtp_user']); ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>
                        
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Password</label>
                            <input type="password" name="smtp_pass" placeholder="Leave blank to keep current" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-rose-500/50 focus:border-rose-500 text-sm transition-all">
                        </div>
                        
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Sender Name</label>
                            <input type="text" name="sender_name" value="<?php echo htmlspecialchars($email_settings['sender_name']); ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>
                        
                        <div class="pt-2 border-t border-slate-200 dark:border-slate-800 mt-4">
                            <label class="flex items-center justify-between bg-slate-50 dark:bg-slate-950 p-4 rounded-xl border border-slate-200 dark:border-slate-800 cursor-pointer transition-colors">
                                <div>
                                    <span class="text-sm font-bold text-slate-900 dark:text-white block">Global Email Dispatching</span>
                                    <span class="text-[9px] text-slate-500 dark:text-gray-400">Master switch for all outgoing emails</span>
                                </div>
                                <input type="checkbox" name="email_enabled" value="1" <?php if($email_settings['email_enabled']=='1') echo 'checked'; ?> class="w-5 h-5 accent-emerald-500 rounded border-slate-300 dark:bg-slate-800 dark:border-slate-700">
                            </label>
                        </div>
                        
                        <button type="submit" name="save_email_settings" class="w-full bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-black font-bold py-3.5 rounded-xl transition shadow-lg shadow-emerald-500/20 text-xs tracking-wider uppercase">💾 Save SMTP Config</button>
                    </form>
                </div>

                <!-- SMTP Test -->
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-lg mb-3 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">🔌 SMTP Connectivity Test</h3>
                    <p class="text-[10px] text-slate-500 dark:text-gray-400 mb-4">Send a test email to verify your SMTP configuration.</p>
                    <form action="test-smtp.php" method="POST" target="_blank" class="flex gap-2">
                        <input type="email" name="test_email" placeholder="admin@example.com" class="flex-1 bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 text-xs rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 transition-all">
                        <button type="submit" class="bg-slate-800 hover:bg-slate-700 dark:bg-slate-700 dark:hover:bg-slate-600 text-white text-xs px-5 py-3 rounded-xl font-bold tracking-widest uppercase transition shadow-md shadow-slate-800/20">Test</button>
                    </form>
                </div>
            </div>

            <!-- RIGHT: Template Editor -->
            <div class="space-y-6">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-lg mb-2 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">📝 Email Templates</h3>
                    <p class="text-[10px] text-slate-500 dark:text-gray-400 mb-4 leading-relaxed">
                        Edit templates for each system trigger. Use placeholders: 
                        <span class="font-mono text-emerald-500 bg-emerald-50 dark:bg-emerald-500/10 px-1 rounded">{user_name}</span>, 
                        <span class="font-mono text-emerald-500 bg-emerald-50 dark:bg-emerald-500/10 px-1 rounded">{site_url}</span>, 
                        <span class="font-mono text-emerald-500 bg-emerald-50 dark:bg-emerald-500/10 px-1 rounded">{reset_code}</span>, 
                        <span class="font-mono text-emerald-500 bg-emerald-50 dark:bg-emerald-500/10 px-1 rounded">{expiry_date}</span>, etc.
                    </p>
                    
                    <form action="email-management.php" method="POST" class="space-y-4">
                        
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Select Trigger</label>
                            <select name="template_type" id="templateSelector" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-sm transition-all font-medium cursor-pointer">
                                <?php foreach ($email_templates as $key => $template): ?>
                                    <option value="<?php echo $key; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $key)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Subject</label>
                            <input type="text" name="template_subject" id="templateSubject" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-sm transition-all">
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Body</label>
                            <textarea name="template_body" id="templateBody" rows="8" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-sm transition-all leading-relaxed resize-y"></textarea>
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Description</label>
                            <input type="text" name="template_description" id="templateDescription" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-500 dark:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-sm transition-all cursor-default" readonly>
                        </div>

                        <button type="submit" name="save_template" class="w-full bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-black font-bold py-3.5 rounded-xl transition shadow-lg shadow-blue-500/20 text-xs tracking-wider uppercase">💾 Update Template</button>
                    </form>
                </div>
            </div>

        </div>
    </main>

    <script>
        // Load template data from PHP into JavaScript
        const emailData = <?php echo json_encode($email_templates); ?>;
        
        document.addEventListener('DOMContentLoaded', function() {
            const selector = document.getElementById('templateSelector');
            const subjInput = document.getElementById('templateSubject');
            const bodyInput = document.getElementById('templateBody');
            const descInput = document.getElementById('templateDescription');

            function loadTemplate(type) {
                if (emailData[type]) {
                    subjInput.value = emailData[type].subject || '';
                    bodyInput.value = emailData[type].body || '';
                    descInput.value = emailData[type].description || '';
                }
            }

            // Load initial
            loadTemplate(selector.value);

            // Listen for changes
            selector.addEventListener('change', function(e) {
                loadTemplate(e.target.value);
            });
        });
    </script>
</body>
</html>