<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

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

try {
    require_once '../db.php';

    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Non autorisé.']);
        exit;
    }

    $userId = $_SESSION['user_id'];
    $method = $_SERVER['REQUEST_METHOD'];

    // GET : Récupérer tous les dossiers/cours de l'utilisateur
    if ($method === 'GET') {
        $stmt = $pdo->prepare("SELECT * FROM courses WHERE user_id = :user_id ORDER BY is_folder DESC, title ASC");
        $stmt->execute(['user_id' => $userId]);
        $courses = $stmt->fetchAll();
        echo json_encode(['success' => true, 'courses' => $courses ? $courses : []]);
        exit;
    }

    // POST : Créer ou modifier un élément (Dossier ou Document)
    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);

        $id = $data['id'] ?? null;
        $title = trim($data['title'] ?? '');
        $subjectName = trim($data['subject_name'] ?? '');
        $color = $data['color'] ?? '#6366f1';
        $content = $data['content'] ?? '';
        $parentId = !empty($data['parent_id']) ? (int)$data['parent_id'] : null;
        $isFolder = isset($data['is_folder']) ? (int)$data['is_folder'] : 0;
        $icon = $data['icon'] ?? ($isFolder ? 'fa-folder' : 'fa-file-lines');

        if (empty($title)) {
            echo json_encode(['success' => false, 'message' => 'Le titre est requis.']);
            exit;
        }

        if ($id) {
            // Mettre à jour
            $stmt = $pdo->prepare("
                UPDATE courses 
                SET title = :title, subject_name = :subject_name, color = :color, content = :content, icon = :icon, updated_at = NOW() 
                WHERE id = :id AND user_id = :user_id
            ");
            $stmt->execute([
                'title'        => $title,
                'subject_name' => $subjectName,
                'color'        => $color,
                'content'      => $content,
                'icon'         => $icon,
                'id'           => $id,
                'user_id'      => $userId
            ]);
            echo json_encode(['success' => true, 'message' => 'Élément mis à jour !']);
        } else {
            // Créer nouvel élément
            $stmt = $pdo->prepare("
                INSERT INTO courses (user_id, parent_id, is_folder, subject_name, title, color, icon, content, created_at) 
                VALUES (:user_id, :parent_id, :is_folder, :subject_name, :title, :color, :icon, :content, NOW())
            ");
            $stmt->execute([
                'user_id'      => $userId,
                'parent_id'    => $parentId,
                'is_folder'    => $isFolder,
                'subject_name' => $subjectName,
                'title'        => $title,
                'color'        => $color,
                'icon'         => $icon,
                'content'      => $content
            ]);
            echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'message' => 'Créé avec succès !']);
        }
        exit;
    }

    // DELETE : Supprimer un dossier ou document
    if ($method === 'DELETE') {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $data['id'] ?? null;

        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM courses WHERE id = :id AND user_id = :user_id");
            $stmt->execute(['id' => $id, 'user_id' => $userId]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'ID manquant.']);
        }
        exit;
    }

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => 'Erreur BDD : ' . $e->getMessage()]);
}
?>