<?php
session_start();
require_once 'config/database.php';
require_once __DIR__ . '/lib/EmailService.php';
require_once __DIR__ . '/lib/EmailTemplates.php';
use TrustBnk\Admin\Lib\EmailService;
use TrustBnk\Admin\Lib\EmailTemplates;

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save') {
    $email_enabled = isset($_POST['email_enabled']) ? 1 : 0;
    $from_email = trim($_POST['from_email'] ?? '');
    $from_name = trim($_POST['from_name'] ?? '');

    $smtp_enabled = isset($_POST['smtp_enabled']) ? 1 : 0;
    $smtp_host = trim($_POST['smtp_host'] ?? '');
    $smtp_port = (int)($_POST['smtp_port'] ?? 465);
    $smtp_username = trim($_POST['smtp_username'] ?? '');
    $smtp_password = trim($_POST['smtp_password'] ?? '');
    $smtp_encryption = in_array(($_POST['smtp_encryption'] ?? 'ssl'), ['ssl','tls','none']) ? $_POST['smtp_encryption'] : 'ssl';

    try {
        $stmt = $conn->prepare("UPDATE system_settings SET email_enabled = ?, from_email = ?, from_name = ?, smtp_enabled = ?, smtp_host = ?, smtp_port = ?, smtp_username = ?, smtp_password = ?, smtp_encryption = ?, updated_at = NOW() WHERE id = 1");
        $stmt->execute([$email_enabled, $from_email, $from_name, $smtp_enabled, $smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_encryption]);
        $success_message = 'Email settings updated successfully';
    } catch (PDOException $e) {
        $error_message = 'Failed to update settings: ' . $e->getMessage();
    }
}

$sys = $conn->query("SELECT * FROM system_settings WHERE id = 1")->fetch();
$gen = $conn->query("SELECT * FROM general_settings WHERE id = 1")->fetch();

// Test email
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'test') {
    $test_to = trim($_POST['test_email'] ?? '');
    if (!filter_var($test_to, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'Enter a valid test email address';
    } else {
        $emailService = new EmailService($conn);
        $fakeUser = [
            'firstname' => 'Test',
            'lastname' => 'User',
            'account_number' => '0000000000',
            'account_type' => 'Savings',
            'balance' => 0,
            'created_at' => date('Y-m-d H:i:s')
        ];
        [$subject, $html] = EmailTemplates::welcome($gen ?: [], $fakeUser);
        $ok = $emailService->sendEmail($test_to, 'Test User', '[Test] ' . $subject, $html, 'System Notification', null, (int)($_SESSION['admin_id'] ?? 0));
        $success_message = $ok ? 'Test email sent. Check inbox/spam.' : 'Failed to send test email. Check settings and email_logs table.';
    }
}
$database->closeConnection();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Settings</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .toggle { position: relative; display: inline-block; width: 54px; height: 28px; }
        .toggle input { display:none; }
        .slider { position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0; background:#d1d5db; transition:.2s; border-radius:9999px; }
        .slider:before { position:absolute; content:""; height:22px; width:22px; left:3px; bottom:3px; background:white; transition:.2s; border-radius:9999px; box-shadow:0 2px 5px rgba(0,0,0,.2); }
        input:checked + .slider { background:#10b981; }
        input:checked + .slider:before { transform: translateX(26px); }
        .settings-grid { display:grid; grid-template-columns: 1fr 1fr; gap:24px; }
        .settings-card { background:#fff; border-radius:12px; padding:20px; box-shadow:0 6px 20px rgba(0,0,0,.06); }
        .settings-card h3 { margin:0 0 10px; }
        .form-row { display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
        .form-group { margin-bottom:12px; }
        .form-group label { display:block; margin-bottom:6px; color:#374151; }
        .form-group input, .form-group select { width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; }
    </style>
    </head>
<body>
    <div class="admin-container">
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo"><?php echo htmlspecialchars($gen['site_name'] ?? 'TrustBeam Credit'); ?></h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li>
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="active">
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </aside>

        <main class="admin-main">
            <div class="page-header">
                <h2>Email Settings</h2>
                <nav class="breadcrumb">
                    <a href="index.php">Dashboard</a> / Email Settings
                </nav>
            </div>

            <?php if ($success_message): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($success_message); ?>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
            <?php endif; ?>

            <form method="POST">
                <input type="hidden" name="action" value="save" />
                <div class="settings-grid">
                    <div class="settings-card">
                        <h3>General Email</h3>
                        <div class="form-group">
                            <label>Enable All Emails</label>
                            <label class="toggle">
                                <input type="checkbox" name="email_enabled" <?php echo !empty($sys['email_enabled']) ? 'checked' : ''; ?> />
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="from_email">From Email</label>
                                <input id="from_email" name="from_email" type="email" value="<?php echo htmlspecialchars($sys['from_email'] ?? ''); ?>" placeholder="no-reply@yourdomain.com" />
                            </div>
                            <div class="form-group">
                                <label for="from_name">From Name</label>
                                <input id="from_name" name="from_name" type="text" value="<?php echo htmlspecialchars($sys['from_name'] ?? ($gen['site_name'] ?? 'Notifications')); ?>" />
                            </div>
                        </div>
                    </div>

                    <div class="settings-card">
                        <h3>SMTP</h3>
                        <div class="form-group">
                            <label>Enable SMTP</label>
                            <label class="toggle">
                                <input type="checkbox" name="smtp_enabled" <?php echo !empty($sys['smtp_enabled']) ? 'checked' : ''; ?> />
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="smtp_host">SMTP Host</label>
                                <input id="smtp_host" name="smtp_host" type="text" value="<?php echo htmlspecialchars($sys['smtp_host'] ?? ''); ?>" placeholder="smtp.gmail.com" />
                            </div>
                            <div class="form-group">
                                <label for="smtp_port">SMTP Port</label>
                                <input id="smtp_port" name="smtp_port" type="number" value="<?php echo htmlspecialchars($sys['smtp_port'] ?? 465); ?>" />
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="smtp_username">SMTP Username</label>
                                <input id="smtp_username" name="smtp_username" type="text" value="<?php echo htmlspecialchars($sys['smtp_username'] ?? ''); ?>" />
                            </div>
                            <div class="form-group">
                                <label for="smtp_password">SMTP Password / App Password</label>
                                <input id="smtp_password" name="smtp_password" type="password" value="<?php echo htmlspecialchars($sys['smtp_password'] ?? ''); ?>" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="smtp_encryption">Encryption</label>
                            <select id="smtp_encryption" name="smtp_encryption">
                                <option value="ssl" <?php echo (($sys['smtp_encryption'] ?? '') === 'ssl') ? 'selected' : ''; ?>>SSL</option>
                                <option value="tls" <?php echo (($sys['smtp_encryption'] ?? '') === 'tls') ? 'selected' : ''; ?>>TLS</option>
                                <option value="none" <?php echo (($sys['smtp_encryption'] ?? '') === 'none') ? 'selected' : ''; ?>>None</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-actions" style="margin-top:20px;">
                    <button type="submit" class="btn-primary">
                        <i class="fas fa-save"></i>
                        Save Settings
                    </button>
                </div>
            </form>

            <div class="settings-card" style="margin-top:20px;">
                <h3>Send Test Email</h3>
                <form method="POST" style="margin-top:10px;">
                    <input type="hidden" name="action" value="test" />
                    <div class="form-row">
                        <div class="form-group">
                            <label for="test_email">Recipient Email</label>
                            <input id="test_email" name="test_email" type="email" placeholder="you@example.com" value="<?php echo htmlspecialchars($_SESSION['admin_email'] ?? ''); ?>" />
                        </div>
                    </div>
                    <button type="submit" class="btn-secondary">
                        <i class="fas fa-paper-plane"></i>
                        Send Test Email
                    </button>
                </form>
            </div>
        </main>
    </div>

    <script src="assets/js/admin.js"></script>
</body>
</html>


