<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$dbFile = '../chat_history.sqlite';
$db = new SQLite3($dbFile);

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

switch ($action) {
    case 'create':
    case 'update':
        $id = $_POST['id'] ?? '';
        $name = $_POST['name'] ?? '';
        $region = $_POST['region'] ?? '';
        $max_tokens = $_POST['max_tokens'] ?? '';
        $stop_sequences = $_POST['stop_sequences'] ?? '';
        $temperature = $_POST['temperature'] ?? '';
        $top_p = $_POST['top_p'] ?? '';
        $knowledge_base_id = $_POST['knowledge_base_id'] ?? '';
        $model_arn = $_POST['model_arn'] ?? '';
        $number_of_results = $_POST['number_of_results'] ?? '';
        $override_search_type = $_POST['override_search_type'] ?? '';
        $instructions = $_POST['instructions']

            ?? '';
        $prompt_template = $_POST['prompt_template'] ?? '';

        if (empty($name)) {
            echo json_encode(['success' => false, 'message' => 'Profile name is required']);
            exit;
        }

        if ($action === 'create') {
            $stmt = $db->prepare('INSERT INTO profiles (name, region, max_tokens, stop_sequences, temperature, top_p, knowledge_base_id, model_arn, number_of_results, override_search_type, instructions) VALUES (:name, :region, :max_tokens, :stop_sequences, :temperature, :top_p, :knowledge_base_id, :model_arn, :number_of_results, :override_search_type, :instructions)');
        } else {
            $stmt = $db->prepare('UPDATE profiles SET name = :name, region = :region, max_tokens = :max_tokens, stop_sequences = :stop_sequences, temperature = :temperature, top_p = :top_p, knowledge_base_id = :knowledge_base_id, model_arn = :model_arn, number_of_results = :number_of_results, override_search_type = :override_search_type, instructions = :instructions WHERE id = :id');
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        }

        $stmt->bindValue(':name', $name, SQLITE3_TEXT);
        $stmt->bindValue(':region', $region, SQLITE3_TEXT);
        $stmt->bindValue(':max_tokens', $max_tokens, SQLITE3_INTEGER);
        $stmt->bindValue(':stop_sequences', $stop_sequences, SQLITE3_TEXT);
        $stmt->bindValue(':temperature', $temperature, SQLITE3_FLOAT);
        $stmt->bindValue(':top_p', $top_p, SQLITE3_FLOAT);
        $stmt->bindValue(':knowledge_base_id', $knowledge_base_id, SQLITE3_TEXT);
        $stmt->bindValue(':model_arn', $model_arn, SQLITE3_TEXT);
        $stmt->bindValue(':number_of_results', $number_of_results, SQLITE3_INTEGER);
        $stmt->bindValue(':override_search_type', $override_search_type, SQLITE3_TEXT);
        $stmt->bindValue(':instructions', $instructions, SQLITE3_TEXT);

        $result = $stmt->execute();

        if ($result) {
            if ($action === 'create') {
                $profileId = $db->lastInsertRowID();
            } else {
                $profileId = $id;
            }

            // Update or insert prompt template
            $stmtTemplate = $db->prepare('INSERT OR REPLACE INTO prompt_templates (profile_id, template) VALUES (:profile_id, :template)');
            $stmtTemplate->bindValue(':profile_id', $profileId, SQLITE3_INTEGER);
            $stmtTemplate->bindValue(':template', $prompt_template, SQLITE3_TEXT);
            $stmtTemplate->execute();

            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error']);
        }
        break;

    case 'delete':
        $id = $_POST['id'] ?? '';
        if (empty($id)) {
            echo json_encode(['success' => false, 'message' => 'Profile ID is required']);
            exit;
        }

        $stmt = $db->prepare('DELETE FROM profiles WHERE id = :id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();

        if ($result) {
            // Delete associated prompt template
            $stmtTemplate = $db->prepare('DELETE FROM prompt_templates WHERE profile_id = :profile_id');
            $stmtTemplate->bindValue(':profile_id', $id, SQLITE3_INTEGER);
            $stmtTemplate->execute();

            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error']);
        }
        break;

    case 'get':
        $id = $_GET['id'] ?? '';
        if (empty($id)) {
            echo json_encode(['success' => false, 'message' => 'Profile ID is required']);
            exit;
        }

        $stmt = $db->prepare('
            SELECT p.*, pt.template AS prompt_template 
            FROM profiles p 
            LEFT JOIN prompt_templates pt 
            ON p.id = pt.profile_id 
            WHERE p.id = :id
            ORDER BY pt.id DESC
            LIMIT 1
        ');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $profile = $result->fetchArray(SQLITE3_ASSOC);

        if ($profile) {
            echo json_encode($profile);
        } else {
            echo json_encode(['success' => false, 'message' => 'Profile not found']);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
