<?php
session_start();
require_once(__DIR__ . '/../config/settings.php');

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

// Seguridad: Solo admin verificado
if (!isset($_SESSION['2fa_verified']) || $_SESSION['2fa_verified'] !== true) {
    echo json_encode(['status' => 'error', 'message' => 'Acceso denegado']);
    exit;
}

try {
    $dsn = "dblib:host={$db_settings['host']};dbname={$db_settings['name']};charset=UTF8";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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

    if ($action == 'save') {
        $title = $_POST['title'];
        $content = $_POST['content'];
        $category = $_POST['category'];
        $path = "";

        if (isset($_FILES['image'])) {
            $dir = "../uploads/guides/";
            if (!is_dir($dir)) mkdir($dir, 0777, true);
            $fileName = time() . "_" . $_FILES['image']['name'];
            move_uploaded_file($_FILES['image']['tmp_name'], $dir . $fileName);
            $path = "uploads/guides/" . $fileName;
        }

        $stmt = $pdo->prepare("INSERT INTO Web_Guides (title, content, category, image_path) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $content, $category, $path]);
        echo json_encode(['status' => 'success', 'message' => 'Guía guardada en los cristales de memoria.']);
    }

    if ($action == 'list') {
        $stmt = $pdo->query("SELECT * FROM Web_Guides ORDER BY id DESC");
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    if ($action == 'delete') {
        $stmt = $pdo->prepare("DELETE FROM Web_Guides WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        echo json_encode(['status' => 'success']);
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}