<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

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

class CategoryController {

    private $db;

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

    // GET /api/categories?action=all
    public function all() {
        $sql = $this->db->prepare("SELECT * FROM categories ORDER BY type, nom");
        $sql->execute();
        echo json_encode(["success" => true, "data" => $sql->fetchAll(PDO::FETCH_ASSOC)]);
    }

    // POST /api/categories?action=add
    public function add() {
        $payload = json_decode(file_get_contents("php://input"), true);

        if (!isset($payload["nom"]) || !isset($payload["type"])) {
            echo json_encode(["success" => false, "message" => "Champs manquants"]);
            return;
        }

        $sql = $this->db->prepare("INSERT INTO categories (nom, type) VALUES (?, ?)");
        $sql->execute([$payload["nom"], $payload["type"]]);

        echo json_encode(["success" => true, "message" => "Catégorie ajoutée"]);
    }

    // POST /api/categories?action=update&id=X
    public function update() {
        if (!isset($_GET["id"])) {
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        $payload = json_decode(file_get_contents("php://input"), true);

        $sql = $this->db->prepare("
            UPDATE categories SET nom = ?, type = ?
            WHERE id = ?
        ");
        $sql->execute([$payload["nom"], $payload["type"], $_GET["id"]]);

        echo json_encode(["success" => true, "message" => "Catégorie modifiée"]);
    }

    // GET /api/categories?action=delete&id=X
    public function delete() {
        if (!isset($_GET["id"])) {
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        $sql = $this->db->prepare("DELETE FROM categories WHERE id = ?");
        $sql->execute([$_GET["id"]]);

        echo json_encode(["success" => true, "message" => "Catégorie supprimée"]);
    }
}

$controller = new CategoryController();

if (isset($_GET["action"])) {
    switch ($_GET["action"]) {
        case "all": $controller->all(); break;
        case "add": $controller->add(); break;
        case "update": $controller->update(); break;
        case "delete": $controller->delete(); break;
        default:
            echo json_encode(["success" => false, "message" => "Action inconnue"]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Aucune action fournie"]);
}
