<?php
/**
 * CMS API Handler
 */
session_start();
header('Content-Type: application/json');

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$db = new App_DB(DBU::$dba_user);
$action = $_GET['action'] ?? '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? $action;

    if ($action === 'save_page') {
        $id = $input['id'] ?? null;

        // Slug validation: lowercase, no spaces
        $slug = strtolower(preg_replace('/[^a-zA-Z0-9\-]/', '', str_replace(' ', '-', $input['slug'])));

        $data = [
            'title' => $input['title'],
            'slug' => $slug,
            'content' => $input['content'],
            'meta_title' => $input['meta_title'] ?: $input['title'],
            'meta_description' => $input['meta_description'],
            'status' => $input['status']
        ];

        if ($id) {
            $sql = "UPDATE cms_pages SET title = :title, slug = :slug, content = :content, 
                    meta_title = :meta_title, meta_description = :meta_description, status = :status 
                    WHERE id = :id";
            $data['id'] = $id;
        }
        else {
            $sql = "INSERT INTO cms_pages (title, slug, content, meta_title, meta_description, status) 
                    VALUES (:title, :slug, :content, :meta_title, :meta_description, :status)";
        }

        if ($db->dbQuery($sql, $data)) {
            echo json_encode(['success' => true, 'message' => 'Page saved successfully']);
        }
        else {
            echo json_encode(['success' => false, 'message' => 'Database error']);
        }
        exit;
    }

    if ($action === 'save_menu') {
        $id = $input['id'] ?? null;
        $name = $input['name'];
        if ($id) {
            $sql = "UPDATE cms_menus SET menu_name = :name WHERE id = :id";
            $res = $db->dbQuery($sql, ['name' => $name, 'id' => $id]);
        }
        else {
            $sql = "INSERT INTO cms_menus (menu_name) VALUES (:name)";
            $res = $db->dbQuery($sql, ['name' => $name]);
        }
        echo json_encode(['success' => $res]);
        exit;
    }

    if ($action === 'save_menu_item') {
        $id = $input['id'] ?? null;
        $data = [
            'menu_id' => $input['menu_id'],
            'label' => $input['label'],
            'link_type' => $input['link_type'],
            'page_id' => $input['page_id'] ?: null,
            'custom_url' => $input['custom_url'],
            'parent_id' => $input['parent_id'],
            'order_index' => 0
        ];
        if ($id) {
            $sql = "UPDATE cms_menu_items SET label = :label, link_type = :link_type, 
                    page_id = :page_id, custom_url = :custom_url, parent_id = :parent_id 
                    WHERE id = :id";
            $data['id'] = $id;
            unset($data['menu_id']);
            unset($data['order_index']);
        }
        else {
            $sql = "INSERT INTO cms_menu_items (menu_id, label, link_type, page_id, custom_url, parent_id, order_index) 
                    VALUES (:menu_id, :label, :link_type, :page_id, :custom_url, :parent_id, :order_index)";
        }
        echo json_encode(['success' => $db->dbQuery($sql, $data)]);
        exit;
    }

    if ($action === 'delete_menu_item') {
        echo json_encode(['success' => $db->dbQuery("DELETE FROM cms_menu_items WHERE id = :id", ['id' => $input['id']])]);
        exit;
    }

    if ($action === 'activate_theme') {
        $id = $input['id'];
        $theme = $db->getRecordFilled("SELECT directory_name FROM cms_themes WHERE id = :id", ['id' => $id]);
        if ($theme) {
            $db->dbQuery("UPDATE cms_themes SET is_active = 0");
            $db->dbQuery("UPDATE cms_themes SET is_active = 1 WHERE id = :id", ['id' => $id]);
            $db->dbQuery("INSERT INTO cms_settings (setting_key, setting_value) VALUES ('active_theme', :val) 
                          ON DUPLICATE KEY UPDATE setting_value = :val", ['val' => $theme['directory_name']]);
            echo json_encode(['success' => true]);
        }
        else {
            echo json_encode(['success' => false]);
        }
        exit;
    }

    if ($action === 'ai_create_theme') {
        $name = $input['name'];
        $color = $input['color'];
        $layout = $input['layout'];
        $dir_name = strtolower(str_replace(' ', '_', $name)) . '_' . time();
        $target_dir = "../../web/themes/" . $dir_name . "/";

        mkdir($target_dir . "layout", 0755, true);
        mkdir($target_dir . "assets/css", 0755, true);

        // Map colors
        $colors = ['blue' => '#0d6efd', 'green' => '#198754', 'dark' => '#212529'];
        $primary = $colors[$color] ?? '#0d6efd';

        // Create style.css
        $css = "body { direction: rtl; } .navbar { background: {$primary} !important; }";
        if ($layout === 'boxed') {
            $css .= " @media (min-width: 1200px) { body { background: #f0f2f5; } .container { background: white; box-shadow: 0 0 20px rgba(0,0,0,0.05); } }";
        }
        file_put_contents($target_dir . "assets/css/style.css", $css);

        // Copy layout files from default (simple generation)
        $default_path = "../../web/themes/default/layout/";
        if (file_exists($default_path . "main.php")) {
            $main_content = file_get_contents($default_path . "main.php");
            // Inject new CSS
            $main_content = str_replace('<!-- Custom CSS -->', "<link rel='stylesheet' href='themes/{$dir_name}/assets/css/style.css'>", $main_content);
            file_put_contents($target_dir . "layout/main.php", $main_content);

            copy($default_path . "header.php", $target_dir . "layout/header.php");
            copy($default_path . "footer.php", $target_dir . "layout/footer.php");
        }

        $res = $db->dbQuery(
            "INSERT INTO cms_themes (theme_name, directory_name, is_active) VALUES (:name, :dir, 0)",
        ['name' => $name, 'dir' => $dir_name]
        );

        echo json_encode(['success' => $res]);
        exit;
    }

    if ($action === 'delete_theme') {
        $id = $input['id'];
        $theme = $db->getRecordFilled("SELECT directory_name, is_active FROM cms_themes WHERE id = :id", ['id' => $id]);
        if ($theme && $theme['is_active'] == 0) {
            $dir = "../../web/themes/" . $theme['directory_name'];
            // Simple recursive delete
            if (is_dir($dir)) {
                exec("rm -rf " . escapeshellarg($dir));
            }
            echo json_encode(['success' => $db->dbQuery("DELETE FROM cms_themes WHERE id = :id", ['id' => $id])]);
        }
        else {
            echo json_encode(['success' => false, 'message' => 'Cannot delete active theme']);
        }
        exit;
    }

    if ($action === 'delete_page') {
        $id = $input['id'];
        if ($db->dbQuery("DELETE FROM cms_pages WHERE id = :id", ['id' => $id])) {
            echo json_encode(['success' => true]);
        }
        else {
            echo json_encode(['success' => false]);
        }
        exit;
    }

    if ($action === 'generate_ai_content' || $action === 'generate_ai_meta_title' || $action === 'generate_ai_meta_description') {
        $title = $input['title'] ?? 'General Page';
        $slug = $input['slug'] ?? '';
        $existingContent = $input['content'] ?? '';

        require_once('../libs/classes/App_DB.php');
        $db_cms = new App_DB(DBU::$dba_user);
        $db_key = $db_cms->getRecordFilled("SELECT setting_value FROM cms_settings WHERE setting_key = 'gemini_api_key'");

        if ($db_key && !empty($db_key['setting_value'])) {
            $apiKey = $db_key['setting_value'];
        }
        else {
            require_once('../libs/classes/EnvLoader.php');
            $apiKey = EnvLoader::get('GEMINI_API_KEY');
        }

        if (!$apiKey) {
            echo json_encode(['success' => false, 'message' => 'Gemini API Key not found in .env']);
            exit;
        }

        $prompt = "";
        if ($action === 'generate_ai_content') {
            $prompt = "Generate professional, well-formatted HTML content for a Madrasa website page. 
                       Topic: {$title} 
                       Context: This is a content page for an Islamic Educational Institution (Madrasa).
                       Language: Primarily Urdu with English terms where appropriate.
                       Requirements:
                       - Use <h2> for main section headings.
                       - Use <p> for detailed descriptions.
                       - Use <ul> and <li> for features or lists.
                       - Use Bootstrap 5.3 classes if helpful (e.g., text-primary, bg-light, p-3).
                       - Output ONLY the clean HTML body content. No <html>, <head>, or <body>.
                       - Style: Professional, informative, and welcoming.";
        }
        elseif ($action === 'generate_ai_meta_title') {
            $prompt = "Generate a catchy, SEO-friendly Meta Title (max 65 chars) for a Madrasa website page titled '{$title}'. Output ONLY the title text. Use Urdu if appropriate, otherwise English.";
        }
        elseif ($action === 'generate_ai_meta_description') {
            $prompt = "Generate a concise, SEO-friendly Meta Description (max 160 chars) for a Madrasa website page titled '{$title}'. 
                       Brief context: " . substr($existingContent, 0, 200) . "
                       Output ONLY the description text. Use Urdu.";
        }

        $url = "https://generativelanguage.googleapis.com/v1/models/gemini-2.5-flash-lite:generateContent?key=" . trim($apiKey);
        $data = ['contents' => [['parts' => [['text' => $prompt]]]]];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($httpCode === 200) {
            $resData = json_decode($response, true);
            $content = $resData['candidates'][0]['content']['parts'][0]['text'] ?? '';
            // Strip markdown formatting if AI returns it
            $content = preg_replace('/^```(html|text)?\s*|```$/m', '', $content);
            echo json_encode(['success' => true, 'content' => trim($content)]);
        }
        else {
            echo json_encode([
                'success' => false,
                'message' => 'AI Generation failed (code ' . $httpCode . ')'
            ]);
        }
        exit;
    }
}

// Handle GET actions
if ($action === 'get_pages') {
    $pages = $db->getRecordSet("SELECT * FROM cms_pages ORDER BY id DESC");
    echo json_encode(['success' => true, 'data' => $pages]);
    exit;
}

if ($action === 'get_menus') {
    echo json_encode(['success' => true, 'data' => $db->getRecordSet("SELECT * FROM cms_menus")]);
    exit;
}

if ($action === 'get_menu_items') {
    $id = $_GET['menu_id'];
    echo json_encode(['success' => true, 'data' => $db->getRecordSet("SELECT * FROM cms_menu_items WHERE menu_id = :id ORDER BY parent_id, order_index", ['id' => $id])]);
    exit;
}

if ($action === 'get_themes') {
    echo json_encode(['success' => true, 'data' => $db->getRecordSet("SELECT * FROM cms_themes ORDER BY is_active DESC, theme_name ASC")]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);
?>