<?php
require_once 'db.php';
session_start();
header('Content-Type: application/json');

try {
    if (!isset($_SESSION['user_id'])) {
        throw new Exception('Not authenticated');
    }

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

    if (!$currentUser || $currentUser['role'] != 1) {
        throw new Exception('Unauthorized access');
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    $required = ['staff_id', 'email', 'password', 'imap_host', 'smtp_host', 'imap_port', 'smtp_port'];
    foreach ($required as $field) {
        if (!isset($_POST[$field]) || empty($_POST[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }

    // Conversion explicite en integer
    $staffId = intval($_POST['staff_id']);
    
    // Vérification que l'ID est valide
    if ($staffId <= 0) {
        throw new Exception('Invalid staff ID');
    }

    $stmt = $db1->prepare("SELECT role FROM utilisateurs WHERE id = ?");
    $stmt->execute([$staffId]);
    $staffUser = $stmt->fetch();

    if (!$staffUser || $staffUser['role'] != 1) {
        throw new Exception('Selected user is not a staff member');
    }

    // Test de connexion IMAP
    $mailbox = "{" . $_POST['imap_host'] . ":" . $_POST['imap_port'] . "/imap/ssl}INBOX";
    $test = @imap_open($mailbox, $_POST['email'], $_POST['password']);
    if (!$test) {
        throw new Exception('Failed to connect to mail server: ' . imap_last_error());
    }
    imap_close($test);

    $db2 = getDB2Connection();
    
    $stmt = $db2->prepare("SELECT id FROM mailboxforstaff WHERE user_id = ?");
    $stmt->execute([$staffId]);
    $existing = $stmt->fetch();

    if ($existing) {
        $stmt = $db2->prepare("
            UPDATE mailboxforstaff 
            SET email = ?, 
                password = ?, 
                imap_host = ?, 
                imap_port = ?,
                smtp_host = ?, 
                smtp_port = ?,
                status = 'active',
                updated_at = CURRENT_TIMESTAMP
            WHERE user_id = ?
        ");
        $params = [
            $_POST['email'],
            $_POST['password'],
            $_POST['imap_host'],
            intval($_POST['imap_port']),
            $_POST['smtp_host'],
            intval($_POST['smtp_port']),
            $staffId
        ];
    } else {
        $stmt = $db2->prepare("
            INSERT INTO mailboxforstaff 
            (user_id, email, password, imap_host, imap_port, smtp_host, smtp_port, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, 'active')
        ");
        $params = [
            $staffId,
            $_POST['email'],
            $_POST['password'],
            $_POST['imap_host'],
            intval($_POST['imap_port']),
            $_POST['smtp_host'],
            intval($_POST['smtp_port'])
        ];
    }

    $stmt->execute($params);

    echo json_encode([
        'success' => true,
        'message' => 'Staff email configuration saved successfully'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}