<?php
require_once 'db.php';
session_start();

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

$db1 = getDB1Connection();
$stmt = $db1->prepare("SELECT role FROM utilisateurs WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

if (!$user || $user['role'] != 1) {
    header('Location: index.php');
    exit;
}

// Récupérer la liste des utilisateurs staff
$staffUsers = $db1->query("SELECT id, username, email FROM utilisateurs WHERE role = 1")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Email Setup - Imators Systems</title>
    <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md">
        <div class="bg-white rounded-lg shadow-lg p-6">
            <div class="flex items-center justify-center mb-8">
                <img src="https://cdn.imators.com/logo.png" alt="Logo" class="h-12 w-auto">
            </div>

            <h2 class="text-2xl font-bold mb-6 text-center">Staff Email Configuration</h2>

            <form id="email-setup-form" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Select Staff Member</label>
                    <select name="staff_id" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">Choose a staff member...</option>
                        <?php foreach($staffUsers as $staffUser): ?>
                            <option value="<?= htmlspecialchars($staffUser['id']) ?>">
                                <?= htmlspecialchars($staffUser['username']) ?> (<?= htmlspecialchars($staffUser['email']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Professional Email</label>
                    <input type="email" name="email" required placeholder="professional@imators.com"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Email Password</label>
                    <input type="password" name="password" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">IMAP Server</label>
                    <input type="text" name="imap_host" required placeholder="imap.imators.com"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">SMTP Server</label>
                    <input type="text" name="smtp_host" required placeholder="smtp.imators.com"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">IMAP Port</label>
                        <input type="number" name="imap_port" value="993" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">SMTP Port</label>
                        <input type="number" name="smtp_port" value="465" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

                <div class="flex justify-between pt-4">
                    <a href="index.php" class="text-gray-600 hover:text-gray-800">Back to Dashboard</a>
                    <button type="submit" 
                            class="bg-black text-white px-4 py-2 rounded-md hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2">
                        Configure Email
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    document.getElementById('email-setup-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const button = form.querySelector('button[type="submit"]');
        const originalText = button.textContent;
        
        try {
            button.disabled = true;
            button.textContent = 'Saving...';
            
            const formData = new FormData(form);
            const response = await fetch('save_staff_email.php', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                alert('Staff email configuration saved successfully!');
                window.location.href = 'index.php';
            } else {
                throw new Error(data.error);
            }
        } catch (error) {
            alert(error.message || 'An error occurred while saving the configuration.');
        } finally {
            button.disabled = false;
            button.textContent = originalText;
        }
    });
    </script>
</body>
</html>