<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

header("Content-Type: application/json");

$host = "192.168.0.4";
$dbname = "DemandeConge";
$username = "wpuser";
$password = "-2b/)ru5/Bi8P[7_";

$conn = new mysqli($host, $username, $password, $dbname);

if ($conn->connect_error) {
    die(json_encode(["success" => false, "message" => "Erreur de connexion à la base de données : " . $conn->connect_error]));
}

$data = json_decode(file_get_contents('php://input'), true);
$email = $data['email'] ?? '';
$mot_de_passe = $data['mot_de_passe'] ?? '';

$query = "
    SELECT 
        u.ID, 
        u.Prenom, 
        u.Nom, 
        u.Email, 
        u.Role, 
        u.ServiceId,
        s.Nom AS ServiceNom
    FROM Users u
    LEFT JOIN Services s ON u.ServiceId = s.Id
    WHERE u.Email = ? AND u.MDP = ?
";

$stmt = $conn->prepare($query);

if ($stmt === false) {
    die(json_encode(["success" => false, "message" => "Erreur de préparation de la requête : " . $conn->error]));
}

$stmt->bind_param("ss", $email, $mot_de_passe);
$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();
    
    echo json_encode([
        "success" => true,
        "message" => "Connexion réussie.",
        "user" => [ 
            "id" => $user['ID'],      
            "prenom" => $user['Prenom'], 
            "nom" => $user['Nom'],      
            "email" => $user['Email'],
            "role" => $user['Role'],
            "service" => $user['ServiceNom'] ?? 'Non défini'
        ]
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Identifiants incorrects."]);
}

$stmt->close();
$conn->close();
?>
