<?php
/**
 * iTools NexusAI · Admin API Controller (style_admin/api.php)
 * Handles Styles, Prompts, Visual Builder Presets, Keycode Management, & Analytics.
 * Supports MySQL DB with automatic JSON file fallback.
 */

error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 0);

if (!headers_sent()) {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    header('Content-Type: application/json; charset=UTF-8');
}

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

$baseDir = dirname(__DIR__);
$stylesJsonFile  = $baseDir . '/imagegen_styles.json';
$statsJsonFile   = $baseDir . '/imagegen_style_stats.json';
$promptsJsonFile = $baseDir . '/prompt_library.json';
$presetsJsonFile = $baseDir . '/prompt_builder_presets.json';
$uploadsDir      = $baseDir . '/uploads/styles';

if (!is_dir($uploadsDir)) {
    @mkdir($uploadsDir, 0777, true);
}

function getDb(): ?PDO {
    static $pdo = null;
    static $attempted = false;
    if ($attempted) return $pdo;
    $attempted = true;
    try {
        $dsn = "mysql:host=localhost;dbname=nexusai_studio;charset=utf8mb4";
        $pdo = new PDO($dsn, "root", "", [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT => 2
        ]);
        return $pdo;
    } catch (Exception $e) {
        $pdo = null;
        return null;
    }
}

function jsonResponse(mixed $data, int $code = 200): never {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}

function readJsonFile(string $file): array {
    if (file_exists($file)) {
        $content = @file_get_contents($file);
        $data = json_decode($content, true);
        if (is_array($data)) return $data;
    }
    return [];
}

function writeJsonFile(string $file, array $data): bool {
    return @file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) !== false;
}

$rawInput = file_get_contents('php://input');
$inputData = json_decode($rawInput, true);
if (!is_array($inputData)) $inputData = [];
$action = $_GET['action'] ?? $_POST['action'] ?? $inputData['action'] ?? '';

$db = getDb();

// ── 1. ART STYLES CRUD ───────────────────────────────────────────────────────
if ($action === 'get_styles' || $action === 'styles') {
    if ($db) {
        try {
            $stmt = $db->query("SELECT * FROM `styles` ORDER BY `is_featured` DESC, `created_at` DESC");
            $rows = $stmt->fetchAll();
            foreach ($rows as &$r) {
                $r['is_featured'] = (bool)$r['is_featured'];
            }
            jsonResponse($rows);
        } catch (Exception $e) {}
    }
    jsonResponse(readJsonFile($stylesJsonFile));
}

if ($action === 'save_style') {
    $id = trim($inputData['id'] ?? $_POST['id'] ?? '');
    $name = trim($inputData['name'] ?? $_POST['name'] ?? '');
    $prompt = trim($inputData['prompt'] ?? $_POST['prompt'] ?? '');
    $category = trim($inputData['category'] ?? $_POST['category'] ?? 'General');
    $image = trim($inputData['image'] ?? $_POST['image'] ?? '');
    $displayMode = trim($inputData['display_mode'] ?? $_POST['display_mode'] ?? 'thumbnail');
    $isFeatured = !empty($inputData['is_featured']) || !empty($_POST['is_featured']) ? 1 : 0;
    
    if (!$name || !$prompt) jsonResponse(['error' => 'Style name and prompt are required'], 400);

    if (!$id) {
        $id = 'style_' . time() . '_' . substr(md5(uniqid()), 0, 4);
    }
    $createdAt = time();

    if ($db) {
        try {
            $stmt = $db->prepare("INSERT INTO `styles` (`id`, `name`, `prompt`, `category`, `image`, `display_mode`, `is_featured`, `created_at`) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?) 
                ON DUPLICATE KEY UPDATE `name` = VALUES(`name`), `prompt` = VALUES(`prompt`), `category` = VALUES(`category`), `image` = VALUES(`image`), `display_mode` = VALUES(`display_mode`), `is_featured` = VALUES(`is_featured`)");
            $stmt->execute([$id, $name, $prompt, $category, $image, $displayMode, $isFeatured, $createdAt]);
        } catch (Exception $e) {}
    }

    // Sync to JSON file
    $styles = readJsonFile($stylesJsonFile);
    $found = false;
    foreach ($styles as &$s) {
        if ($s['id'] === $id) {
            $s['name'] = $name;
            $s['prompt'] = $prompt;
            $s['category'] = $category;
            $s['image'] = $image;
            $s['display_mode'] = $displayMode;
            $s['is_featured'] = (bool)$isFeatured;
            $found = true;
            break;
        }
    }
    if (!$found) {
        array_unshift($styles, [
            'id' => $id,
            'name' => $name,
            'prompt' => $prompt,
            'category' => $category,
            'image' => $image,
            'display_mode' => $displayMode,
            'is_featured' => (bool)$isFeatured,
            'created_at' => $createdAt
        ]);
    }
    writeJsonFile($stylesJsonFile, $styles);
    jsonResponse(['status' => 'success', 'id' => $id]);
}

if ($action === 'delete_style') {
    $id = trim($inputData['id'] ?? $_POST['id'] ?? $_GET['id'] ?? '');
    if (!$id) jsonResponse(['error' => 'ID is required'], 400);

    if ($db) {
        try {
            $stmt = $db->prepare("DELETE FROM `styles` WHERE `id` = ?");
            $stmt->execute([$id]);
        } catch (Exception $e) {}
    }

    $styles = readJsonFile($stylesJsonFile);
    $styles = array_values(array_filter($styles, fn($s) => $s['id'] !== $id));
    writeJsonFile($stylesJsonFile, $styles);
    jsonResponse(['status' => 'success']);
}

// ── 2. PROMPT LIBRARY CRUD ───────────────────────────────────────────────────
if ($action === 'get_prompts') {
    if ($db) {
        try {
            $stmt = $db->query("SELECT * FROM `prompt_library` ORDER BY `created_at` DESC");
            jsonResponse($stmt->fetchAll());
        } catch (Exception $e) {}
    }
    jsonResponse(readJsonFile($promptsJsonFile));
}

if ($action === 'save_prompt') {
    $id = trim($inputData['id'] ?? $_POST['id'] ?? '');
    $title = trim($inputData['title'] ?? $_POST['title'] ?? '');
    $prompt = trim($inputData['prompt'] ?? $_POST['prompt'] ?? '');
    $category = trim($inputData['category'] ?? $_POST['category'] ?? 'General');
    $tags = trim($inputData['tags'] ?? $_POST['tags'] ?? '');
    $isPreset = !empty($inputData['is_preset']) ? 1 : 0;

    if (!$title || !$prompt) jsonResponse(['error' => 'Title and prompt are required'], 400);

    if (!$id) $id = 'prompt_' . time() . '_' . substr(md5(uniqid()), 0, 4);
    $createdAt = time();

    if ($db) {
        try {
            $stmt = $db->prepare("INSERT INTO `prompt_library` (`id`, `title`, `prompt`, `category`, `tags`, `is_preset`, `created_at`)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE `title` = VALUES(`title`), `prompt` = VALUES(`prompt`), `category` = VALUES(`category`), `tags` = VALUES(`tags`), `is_preset` = VALUES(`is_preset`)");
            $stmt->execute([$id, $title, $prompt, $category, $tags, $isPreset, $createdAt]);
        } catch (Exception $e) {}
    }

    $prompts = readJsonFile($promptsJsonFile);
    $found = false;
    foreach ($prompts as &$p) {
        if ($p['id'] === $id) {
            $p['title'] = $title;
            $p['prompt'] = $prompt;
            $p['category'] = $category;
            $p['tags'] = $tags;
            $p['is_preset'] = $isPreset;
            $found = true;
            break;
        }
    }
    if (!$found) {
        array_unshift($prompts, [
            'id' => $id,
            'title' => $title,
            'prompt' => $prompt,
            'category' => $category,
            'tags' => $tags,
            'is_preset' => $isPreset,
            'created_at' => $createdAt
        ]);
    }
    writeJsonFile($promptsJsonFile, $prompts);
    jsonResponse(['status' => 'success', 'id' => $id]);
}

if ($action === 'delete_prompt') {
    $id = trim($inputData['id'] ?? $_POST['id'] ?? $_GET['id'] ?? '');
    if ($db) {
        try {
            $stmt = $db->prepare("DELETE FROM `prompt_library` WHERE `id` = ?");
            $stmt->execute([$id]);
        } catch (Exception $e) {}
    }
    $prompts = readJsonFile($promptsJsonFile);
    $prompts = array_values(array_filter($prompts, fn($p) => $p['id'] !== $id));
    writeJsonFile($promptsJsonFile, $prompts);
    jsonResponse(['status' => 'success']);
}

// ── 3. VISUAL PROMPT BUILDER PRESETS ─────────────────────────────────────────
if ($action === 'get_builder_presets') {
    if ($db) {
        try {
            $stmt = $db->query("SELECT * FROM `prompt_builder_presets` ORDER BY `category` ASC, `sort_order` ASC");
            $rows = $stmt->fetchAll();
            if (!empty($rows)) jsonResponse($rows);
        } catch (Exception $e) {}
    }
    
    // Default fallback presets if file or DB empty
    $presets = readJsonFile($presetsJsonFile);
    if (empty($presets)) {
        $presets = [
            ['id' => 'b1', 'category' => 'Medium', 'name' => 'Photorealistic', 'value' => 'hyperrealistic 8k photograph, professional studio portrait', 'icon' => 'fa-camera'],
            ['id' => 'b2', 'category' => 'Medium', 'name' => 'Anime / Manga', 'value' => 'anime digital artwork, Makoto Shinkai style, vibrant shading', 'icon' => 'fa-paintbrush'],
            ['id' => 'b3', 'category' => 'Medium', 'name' => 'Cinematic 3D', 'value' => '3D render, Pixar Octane Render style, soft volumetric lighting', 'icon' => 'fa-cube'],
            ['id' => 'b4', 'category' => 'Medium', 'name' => 'Oil Painting', 'value' => 'oil on canvas, visible brushstrokes, textured masterpiece', 'icon' => 'fa-palette'],
            ['id' => 'b5', 'category' => 'Lighting', 'name' => 'Cinematic Glow', 'value' => 'cinematic lighting, rim light, deep shadows, moody contrast', 'icon' => 'fa-sun'],
            ['id' => 'b6', 'category' => 'Lighting', 'name' => 'Golden Hour', 'value' => 'golden hour sunlight, warm ambient glow, soft lens flare', 'icon' => 'fa-sun-plant-wilt'],
            ['id' => 'b7', 'category' => 'Lighting', 'name' => 'Neon Cyberpunk', 'value' => 'vivid neon lighting, cyan and magenta glow, dark moody reflections', 'icon' => 'fa-bolt'],
            ['id' => 'b8', 'category' => 'Camera', 'name' => 'Macro Shot', 'value' => 'close-up macro photography, shallow depth of field, sharp focus', 'icon' => 'fa-magnifying-glass'],
            ['id' => 'b9', 'category' => 'Camera', 'name' => 'Wide Angle', 'value' => 'wide angle perspective shot, epic landscape view, grand composition', 'icon' => 'fa-expand'],
            ['id' => 'b10', 'category' => 'Camera', 'name' => '85mm Portrait', 'value' => '85mm lens portrait, creamy bokeh background, razor sharp detail', 'icon' => 'fa-user'],
            ['id' => 'b11', 'category' => 'Quality', 'name' => 'Masterpiece 8K', 'value' => 'masterpiece, best quality, highly detailed, 8k resolution, photorealistic', 'icon' => 'fa-award'],
            ['id' => 'b12', 'category' => 'Quality', 'name' => 'Unreal Engine 5', 'value' => 'rendered in Unreal Engine 5, ray tracing, ultra detailed texture', 'icon' => 'fa-gamepad']
        ];
        writeJsonFile($presetsJsonFile, $presets);
    }
    jsonResponse($presets);
}

if ($action === 'save_builder_preset') {
    $id = trim($inputData['id'] ?? $_POST['id'] ?? '');
    $category = trim($inputData['category'] ?? $_POST['category'] ?? 'Medium');
    $name = trim($inputData['name'] ?? $_POST['name'] ?? '');
    $value = trim($inputData['value'] ?? $_POST['value'] ?? '');
    $icon = trim($inputData['icon'] ?? $_POST['icon'] ?? 'fa-wand-magic-sparkles');
    $sortOrder = intval($inputData['sort_order'] ?? $_POST['sort_order'] ?? 0);

    if (!$name || !$value) jsonResponse(['error' => 'Name and value required'], 400);

    if (!$id) $id = 'preset_' . time() . '_' . rand(100,999);

    if ($db) {
        try {
            $stmt = $db->prepare("INSERT INTO `prompt_builder_presets` (`id`, `category`, `name`, `value`, `icon`, `sort_order`)
                VALUES (?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE `category` = VALUES(`category`), `name` = VALUES(`name`), `value` = VALUES(`value`), `icon` = VALUES(`icon`), `sort_order` = VALUES(`sort_order`)");
            $stmt->execute([$id, $category, $name, $value, $icon, $sortOrder]);
        } catch (Exception $e) {}
    }

    $presets = readJsonFile($presetsJsonFile);
    $found = false;
    foreach ($presets as &$p) {
        if ($p['id'] === $id) {
            $p['category'] = $category;
            $p['name'] = $name;
            $p['value'] = $value;
            $p['icon'] = $icon;
            $p['sort_order'] = $sortOrder;
            $found = true;
            break;
        }
    }
    if (!$found) {
        $presets[] = ['id' => $id, 'category' => $category, 'name' => $name, 'value' => $value, 'icon' => $icon, 'sort_order' => $sortOrder];
    }
    writeJsonFile($presetsJsonFile, $presets);
    jsonResponse(['status' => 'success', 'id' => $id]);
}

if ($action === 'delete_builder_preset') {
    $id = trim($inputData['id'] ?? $_POST['id'] ?? $_GET['id'] ?? '');
    if ($db) {
        try {
            $stmt = $db->prepare("DELETE FROM `prompt_builder_presets` WHERE `id` = ?");
            $stmt->execute([$id]);
        } catch (Exception $e) {}
    }
    $presets = readJsonFile($presetsJsonFile);
    $presets = array_values(array_filter($presets, fn($p) => $p['id'] !== $id));
    writeJsonFile($presetsJsonFile, $presets);
    jsonResponse(['status' => 'success']);
}

// ── 4. ANALYTICS & LOGS ──────────────────────────────────────────────────────
if ($action === 'get_analytics' || $action === 'get_logs') {
    $stats = readJsonFile($statsJsonFile);
    $styles = readJsonFile($stylesJsonFile);
    $styleMap = [];
    foreach ($styles as $s) {
        $styleMap[$s['id']] = $s['name'];
    }

    $topStyles = [];
    foreach ($stats as $id => $count) {
        $topStyles[] = [
            'id' => $id,
            'name' => $styleMap[$id] ?? $id,
            'count' => $count
        ];
    }
    usort($topStyles, fn($a, $b) => $b['count'] <=> $a['count']);

    $logs = [];
    $keycodes = [];
    if ($db) {
        try {
            $stmtLogs = $db->query("SELECT * FROM `api_logs` ORDER BY `id` DESC LIMIT 100");
            $logs = $stmtLogs->fetchAll();

            $stmtKeys = $db->query("SELECT * FROM `keycodes` ORDER BY `last_active` DESC");
            $keycodes = $stmtKeys->fetchAll();
        } catch (Exception $e) {}
    }

    jsonResponse([
        'top_styles' => $topStyles,
        'logs'       => $logs,
        'keycodes'   => $keycodes
    ]);
}

// ── 5. THUMBNAIL IMAGE UPLOADER ──────────────────────────────────────────────
if ($action === 'upload_image' || !empty($_FILES['image'])) {
    if (empty($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        jsonResponse(['error' => 'Failed to upload image'], 400);
    }
    $tmp = $_FILES['image']['tmp_name'];
    $name = basename($_FILES['image']['name']);
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    if (!in_array($ext, $allowed)) jsonResponse(['error' => 'Invalid image format'], 400);

    $newName = 'style_' . time() . '_' . substr(md5(uniqid()), 0, 6) . '.' . $ext;
    $targetPath = $uploadsDir . '/' . $newName;

    if (move_uploaded_file($tmp, $targetPath)) {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $subDir = trim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/\\');
        $urlPath = $subDir ? '/' . $subDir . '/uploads/styles/' . $newName : '/uploads/styles/' . $newName;
        $fullUrl = $scheme . '://' . $host . $urlPath;
        jsonResponse(['status' => 'success', 'url' => $fullUrl]);
    } else {
        jsonResponse(['error' => 'Could not move uploaded file'], 500);
    }
}

jsonResponse(['error' => 'Invalid action'], 400);
