<?php
require_once __DIR__ . '/../models/Agent.php';

class AuthController {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function login() {
        // Try to get data from JSON body first
        $data = json_decode(file_get_contents("php://input"));
        
        // Fallback to $_POST if JSON is empty
        $username = $data->username ?? $_POST['username'] ?? null;
        $password = $data->password ?? $_POST['password'] ?? null;

        if (!empty($username) && !empty($password)) {
            $agent = new Agent($this->db);
            $user = $agent->login($username, $password);

            if ($user) {
                // Pour simplifier, on génère un token fictif ou on utilise l'ID
                $token = base64_encode($user['username'] . ":" . time());
                
                echo json_encode([
                    "success" => true,
                    "message" => "Connexion réussie",
                    "data" => [
                        "token" => $token,
                        "user" => [
                            "id" => $user['id'],
                            "username" => $user['username'],
                            "full_name" => $user['full_name'] ?? $user['username'],
                            "role" => $user['role'] ?? 'agent'
                        ]
                    ]
                ]);
            } else {
                http_response_code(401);
                echo json_encode([
                    "success" => false,
                    "message" => "Identifiants invalides ou compte inactif"
                ]);
            }
        } else {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "message" => "Données incomplètes. Username et Password requis."
            ]);
        }
    }
}
?>
