<?php
session_start();
if (!isset($_SESSION['admin'])) {
    exit('Admin access required');
}

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

$profiles = $db->query('SELECT * FROM profiles');
$config = require '../config.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Profiles</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <h1 class="text-3xl font-bold mb-6 text-center text-gray-800">Manage Profiles</h1>
        
        <button id="addProfileBtn" class="mb-4 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition duration-300">Add Profile</button>
        
        <div class="bg-white rounded-lg shadow-md overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-gray-200 text-gray-600 uppercase text-sm leading-normal">
                        <th class="py-3 px-6 text-left">Name</th>
                        <th class="py-3 px-6 text-left">Region</th>
                        <th class="py-3 px-6 text-left">Max Tokens</th>
                        <th class="py-3 px-6 text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm font-light">
                    <?php while ($profile = $profiles->fetchArray(SQLITE3_ASSOC)): ?>
                        <tr class="border-b border-gray-200 hover:bg-gray-100">
                            <td class="py-3 px-6 text-left whitespace-nowrap">
                                <?= htmlspecialchars($profile['name']) ?>
                            </td>
                            <td class="py-3 px-6 text-left">
                                <?= htmlspecialchars($profile['region']) ?>
                            </td>
                            <td class="py-3 px-6 text-left">
                                <?= htmlspecialchars($profile['max_tokens']) ?>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <button class="editProfileBtn bg-yellow-500 text-white px-3 py-1 rounded hover:bg-yellow-600 transition duration-300" data-id="<?= $profile['id'] ?>">Edit</button>
                                <button class="deleteProfileBtn bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition duration-300" data-id="<?= $profile['id'] ?>">Delete</button>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Add/Edit Profile Modal -->
    <div id="profileModal" class="fixed z-10 inset-0 overflow-y-auto hidden" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form id="profileForm">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title"></h3>
                        <div class="mt-2">
                            <input type="hidden" id="profileId" name="id">
                            <div class="mb-4">
                                <label for="name" class="block text-gray-700 text-sm font-bold mb-2">Name</label>
                                <input type="text" id="name" name="name" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="region" class="block text-gray-700 text-sm font-bold mb-2">Region</label>
                                <input type="text" id="region" name="region" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="max_tokens" class="block text-gray-700 text-sm font-bold mb-2">Max Tokens</label>
                                <input type="number" id="max_tokens" name="max_tokens" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="stop_sequences" class="block text-gray-700 text-sm font-bold mb-2">Stop Sequences</label>
                                <input type="text" id="stop_sequences" name="stop_sequences" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="temperature" class="block text-gray-700 text-sm font-bold mb-2">Temperature</label>
                                <input type="number" id="temperature" name="temperature" step="0.1" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="top_p" class="block text-gray-700 text-sm font-bold mb-2">Top P</label>
                                <input type="number" id="top_p" name="top_p" step="0.1" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="knowledge_base_id" class="block text-gray-700 text-sm font-bold mb-2">Knowledge Base ID</label>
                                <input type="text" id="knowledge_base_id" name="knowledge_base_id" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="model_arn" class="block text-gray-700 text-sm font-bold mb-2">Model ARN</label>
                                <input type="text" id="model_arn" name="model_arn" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="number_of_results" class="block text-gray-700 text-sm font-bold mb-2">Number of Results</label>
                                <input type="number" id="number_of_results" name="number_of_results" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="override_search_type" class="block text-gray-700 text-sm font-bold mb-2">Override Search Type</label>
                                <input type="text" id="override_search_type" name="override_search_type" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="instructions" class="block text-gray-700 text-sm font-bold mb-2">Instructions</label>
                                <textarea id="instructions" name="instructions" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" rows="3" required></textarea>
                            </div>
                            <div class="mb-4">
                                <label for="prompt_template" class="block text-gray-700 text-sm font-bold mb-2">Prompt Template</label>
                                <textarea id="prompt_template" name="prompt_template" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" rows="3" ></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                            Save
                        </button>
                        <button type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" onclick="closeProfileModal()">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        const config = <?= json_encode($config) ?>;

        function openProfileModal(title, profileId = '', profileData = null) {
            $('#modal-title').text(title);
            $('#profileId').val(profileId);
            
            if (profileData) {
                $('#name').val(profileData.name);
                $('#region').val(profileData.region);
                $('#max_tokens').val(profileData.max_tokens);
                $('#stop_sequences').val(profileData.stop_sequences);
                $('#temperature').val(profileData.temperature);
                $('#top_p').val(profileData.top_p);
                $('#knowledge_base_id').val(profileData.knowledge_base_id);
                $('#model_arn').val(profileData.model_arn);
                $('#number_of_results').val(profileData.number_of_results);
                $('#override_search_type').val(profileData.override_search_type);
                $('#instructions').val(profileData.instructions);
                $('#prompt_template').val(profileData.prompt_template);
            } else {
                $('#name').val('');
                $('#region').val(config.region);
                $('#max_tokens').val(config.maxTokens);
                $('#stop_sequences').val(config.stopSequences);
                $('#temperature').val(config.temperature);
                $('#top_p').val(config.topP);
                $('#knowledge_base_id').val(config.knowledgeBaseId);
                $('#model_arn').val(config.modelArn);
                $('#number_of_results').val(config.numberOfResults);
                $('#override_search_type').val(config.overrideSearchType);
                $('#instructions').val(config.instructions);
                $('#prompt_template').val(config.prompt_template);
            }
            
            $('#profileModal').removeClass('hidden');
        }

        function closeProfileModal() {
            $('#profileModal').addClass('hidden');
        }

        $(document).ready(function() {
            $('#addProfileBtn').click(function() {
                openProfileModal('Add Profile');
            });

            $('.editProfileBtn').click(function() {
                var profileId = $(this).data('id');
                $.getJSON('admin/profile_actions.php', { action: 'get', id: profileId }, function(profileData) {
                    openProfileModal('Edit Profile', profileId, profileData);
                });
            });

            $('.deleteProfileBtn').click(function() {
                var profileId = $(this).data('id');
                if (confirm('Are you sure you want to delete this profile?')) {
                    $.post('admin/profile_actions.php', { action: 'delete', id: profileId }, function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert('Error: ' + response.message);
                        }
                    }, 'json');
                }
            });

            $('#profileForm').submit(function(e) {
                e.preventDefault();
                var formData = $(this).serialize();
                var action = $('#profileId').val() ? 'update' : 'create';
                formData += '&action=' + action;
                console.log(formData);
                $.post('admin/profile_actions.php', formData, function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + response.message);
                    }
                }, 'json');
            });
        });
    </script>
</body>
</html>