<?php
// Activer le buffer de sortie pour capturer toutes les erreurs
ob_start();

// Fonction pour toujours renvoyer du JSON
function sendJsonResponse($data) {
    ob_clean();
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode($data);
    exit;
}

// Gestionnaire d'erreurs fatales
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        sendJsonResponse([
            "success" => false,
            "message" => "Erreur serveur: " . $error['message']
        ]);
    }
});

// CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

// Connexion DB
try {
    require_once __DIR__ . '/../config/database.php';
} catch (Exception $e) {
    sendJsonResponse([
        "success" => false,
        "message" => "Erreur de connexion DB: " . $e->getMessage()
    ]);
}

class AuthController {
    private $db;

    public function __construct() {
        try {
            $this->db = (new Database())->getConnection();
        } catch (Exception $e) {
            sendJsonResponse([
                "success" => false,
                "message" => "Erreur DB: " . $e->getMessage()
            ]);
        }
    }

    // Connexion par PIN
    public function loginWithPin() {
        $raw = file_get_contents("php://input");
        $data = json_decode($raw, true);

        if ($data === null) {
            sendJsonResponse(["success" => false, "message" => "JSON invalide ou vide"]);
        }

        if (!isset($data["code_pin"]) || strlen($data["code_pin"]) != 4) {
            sendJsonResponse(["success" => false, "message" => "Code PIN invalide"]);
        }

        try {
            $stmt = $this->db->prepare("SELECT * FROM membres WHERE code_pin = ? LIMIT 1");
            $stmt->execute([$data["code_pin"]]);
            $membre = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$membre) {
                sendJsonResponse(["success" => false, "message" => "Code PIN incorrect"]);
            }

            unset($membre["code_pin"]);
            sendJsonResponse(["success" => true, "membre" => $membre]);
        } catch (Exception $e) {
            sendJsonResponse(["success" => false, "message" => $e->getMessage()]);
        }
    }

    // Inscription
    public function register() {
        $raw = file_get_contents("php://input");
        $data = json_decode($raw, true);

        if ($data === null) {
            sendJsonResponse(["success" => false, "message" => "JSON invalide ou vide"]);
        }

        if (!isset($data["nom"]) || !isset($data["prenom"]) || !isset($data["username"])) {
            sendJsonResponse(["success" => false, "message" => "Paramètres manquants"]);
        }

        try {
            // ⚠️ Vérification du username supprimée pour éviter blocage
            $pin = sprintf('%04d', rand(1000, 9999));
            $nom_complet = $data["prenom"] . " " . $data["nom"];

            $stmt = $this->db->prepare("
                INSERT INTO membres (username, nom, prenom, nom_complet, telephone, code_pin, role, statut, date_adhesion)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            $ok = $stmt->execute([
                $data["username"],
                $data["nom"],
                $data["prenom"],
                $nom_complet,
                $data["telephone"] ?? null,
                $pin,
                "membre",
                "actif"
            ]);

            if ($ok) {
                sendJsonResponse([
                    "success" => true,
                    "message" => "Compte créé avec succès.",
                    "pin" => $pin
                ]);
            } else {
                sendJsonResponse(["success" => false, "message" => "Erreur lors de la création"]);
            }
        } catch (Exception $e) {
            sendJsonResponse(["success" => false, "message" => $e->getMessage()]);
        }
    }

    // Liste tous les membres
    public function all() {
        try {
            $stmt = $this->db->query("SELECT id, username, nom, prenom, telephone, role, statut, date_adhesion FROM membres");
            $membres = $stmt->fetchAll(PDO::FETCH_ASSOC);
            sendJsonResponse(["success" => true, "membres" => $membres]);
        } catch (Exception $e) {
            sendJsonResponse(["success" => false, "message" => $e->getMessage()]);
        }
    }
}

// Router
$controller = new AuthController();
$action = $_GET["action"] ?? null;

if (!$action) {
    sendJsonResponse(["success" => false, "message" => "Action manquante"]);
}

switch ($action) {
    case 'login_pin':
        if ($_SERVER["REQUEST_METHOD"] === 'POST') {
            $controller->loginWithPin();
        } else {
            sendJsonResponse(["success" => false, "message" => "POST requis"]);
        }
        break;

    case 'register':
        if ($_SERVER["REQUEST_METHOD"] === 'POST') {
            $controller->register();
        } else {
            sendJsonResponse(["success" => false, "message" => "POST requis"]);
        }
        break;

    case 'all':
        if ($_SERVER["REQUEST_METHOD"] === 'GET') {
            $controller->all();
        } else {
            sendJsonResponse(["success" => false, "message" => "GET requis"]);
        }
        break;

    default:
        sendJsonResponse(["success" => false, "message" => "Action inconnue"]);
        break;
}

// Sécurité : réponse par défaut
sendJsonResponse(["success" => false, "message" => "Aucune action exécutée"]);
