<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    $db = Database::getInstance();
} catch (Exception $e) {
    die(json_encode(['success' => false, 'message' => 'DB Connection failed: ' . $e->getMessage()]));
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'auth':
        $username = $_GET['username'] ?? '';
        $password = $_GET['password'] ?? '';
        $user = $db->selectOne("SELECT * FROM Utilisateurs WHERE code_utilisateur = ? AND statut = 'ACTIF'", [$username]);
        if ($user && ($user['mot_de_passe'] === $password || password_verify($password, $user['mot_de_passe']))) {
            echo json_encode(['success' => true, 'data' => $user]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Identifiants incorrects']);
        }
        break;
        
    case 'list':
        try {
            $result = $db->select("SELECT * FROM Utilisateurs WHERE statut = 'ACTIF' ORDER BY code_utilisateur DESC");
            echo json_encode(['success' => true, 'data' => $result]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'create':
        $data = json_decode(file_get_contents('php://input'), true);
        try {
            $sql = "INSERT INTO Utilisateurs (code_utilisateur, Nom, NomAR, Prenom, PrenomAR, NomPrenom, NomPrenomAR, mot_de_passe, statut, role, SiteID, last_ticket_number, is_session_open, CreerPar, Date_Modif, email, last_password_change_date) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $pdo->prepare($sql)->execute([
                $data['code_utilisateur'],
                $data['Nom'],
                $data['NomAR'] ?? '',
                $data['Prenom'],
                $data['PrenomAR'] ?? '',
                $data['NomPrenom'],
                $data['NomPrenomAR'] ?? '',
                $data['mot_de_passe'],
                $data['statut'],
                $data['role'],
                $data['SiteID'],
                $data['last_ticket_number'] ?? null,
                $data['is_session_open'] ?? 'N',
                $data['CreerPar'],
                date('Y-m-d H:i:s'),
                $data['email'] ?? '',
                date('Y-m-d H:i:s')
            ]);
            echo json_encode(['success' => true, 'message' => 'Utilisateur créé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'update':
        $code = $_GET['code'] ?? '';
        $data = json_decode(file_get_contents('php://input'), true);
        try {
            $sql = "UPDATE Utilisateurs SET Nom = ?, NomAR = ?, Prenom = ?, PrenomAR = ?, 
                    NomPrenom = ?, NomPrenomAR = ?, email = ?, mot_de_passe = ?, 
                    statut = ?, role = ?, SiteID = ?, CreerPar = ?, Date_Modif = ? 
                    WHERE code_utilisateur = ?";
            $pdo->prepare($sql)->execute([
                $data['Nom'],
                $data['NomAR'] ?? '',
                $data['Prenom'],
                $data['PrenomAR'] ?? '',
                $data['NomPrenom'],
                $data['NomPrenomAR'] ?? '',
                $data['email'] ?? '',
                $data['mot_de_passe'],
                $data['statut'],
                $data['role'],
                $data['SiteID'],
                $data['CreerPar'],
                date('Y-m-d H:i:s'),
                $code
            ]);
            echo json_encode(['success' => true, 'message' => 'Utilisateur modifié']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'delete':
        $code = $_GET['code'] ?? '';
        try {
            $pdo->prepare("DELETE FROM Utilisateurs WHERE code_utilisateur = ?")->execute([$code]);
            echo json_encode(['success' => true, 'message' => 'Utilisateur supprimé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'lastcode':
        $siteId = $_GET['siteId'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT code_utilisateur FROM Utilisateurs WHERE SiteID = ? ORDER BY code_utilisateur DESC LIMIT 1");
            $stmt->execute([$siteId]);
            $result = $stmt->fetch();
            if ($result) {
                echo json_encode(['success' => true, 'data' => $result['code_utilisateur']]);
            } else {
                echo json_encode(['success' => true, 'data' => null]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}
