<?php
/**
 * Hero Slider Handler Diagnostic Test
 * Test the handler and debug any issues
 */

session_start();

// Set user as admin for testing
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = 1;
    $_SESSION['user_type'] = 'admin';
    $_SESSION['admin_name'] = 'Test Admin';
}

header('Content-Type: text/html; charset=utf-8');

?><!DOCTYPE html>
<html>
<head>
    <title>Hero Slider Handler Diagnostic</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #109c3d;
            border-bottom: 2px solid #109c3d;
            padding-bottom: 10px;
        }
        .test-section {
            margin: 30px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: #f9f9f9;
        }
        .test-title {
            font-weight: bold;
            color: #0f172a;
            margin-bottom: 15px;
            font-size: 16px;
        }
        button {
            background: #109c3d;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
        }
        button:hover {
            background: #0f8c3d;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 5px;
            background: #f0f0f0;
            border-left: 4px solid #109c3d;
        }
        .result.error {
            background: #fee2e2;
            border-left-color: #ef4444;
        }
        .result.success {
            background: #d1fae5;
            border-left-color: #10b981;
        }
        pre {
            background: #f5f5f5;
            padding: 10px;
            border-radius: 3px;
            overflow-x: auto;
            font-size: 12px;
        }
        .form-group {
            margin: 15px 0;
        }
        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: Arial;
        }
        textarea {
            resize: vertical;
            min-height: 80px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 Hero Slider Handler Diagnostic</h1>
        
        <div class="test-section">
            <div class="test-title">📋 Test 1: PHP Version & Configuration</div>
            <button onclick="testPhpVersion()">Check PHP Info</button>
            <div id="phpResult"></div>
        </div>

        <div class="test-section">
            <div class="test-title">🗄️ Test 2: Database Connection</div>
            <button onclick="testDbConnection()">Test Database</button>
            <div id="dbResult"></div>
        </div>

        <div class="test-section">
            <div class="test-title">📊 Test 3: Check Database Table</div>
            <button onclick="testTableExists()">Check Table</button>
            <div id="tableResult"></div>
        </div>

        <div class="test-section">
            <div class="test-title">✅ Test 4: Test GET Request (Load All Slides)</div>
            <button onclick="testGetAllSlides()">Load All Slides</button>
            <div id="getAllResult"></div>
        </div>

        <div class="test-section">
            <div class="test-title">➕ Test 5: Test POST Request (Add Slide)</div>
            <div class="form-group">
                <label>Title:</label>
                <input type="text" id="testTitle" value="Test Slide" placeholder="Enter slide title">
            </div>
            <div class="form-group">
                <label>Description:</label>
                <textarea id="testDesc" placeholder="Enter slide description">This is a test slide</textarea>
            </div>
            <button onclick="testAddSlide()">Add Test Slide</button>
            <div id="addResult"></div>
        </div>

        <div class="test-section">
            <div class="test-title">🔧 Handler File Info</div>
            <button onclick="checkHandlerFile()">Check Handler File</button>
            <div id="handlerResult"></div>
        </div>
    </div>

    <script>
        function showResult(elementId, message, isError = false) {
            const element = document.getElementById(elementId);
            const className = isError ? 'result error' : 'result success';
            element.innerHTML = `<div class="${className}"><pre>${escapeHtml(message)}</pre></div>`;
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function testPhpVersion() {
            const result = "PHP Version: <?php echo phpversion(); ?>\n" +
                          "Server Software: <?php echo $_SERVER['SERVER_SOFTWARE']; ?>\n" +
                          "MySQLi Available: <?php echo extension_loaded('mysqli') ? 'Yes' : 'No'; ?>";
            showResult('phpResult', result);
        }

        function testDbConnection() {
            fetch('hero_slider_handler.php?action=get_all', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                return response.text();
            })
            .then(text => {
                console.log('Raw response:', text);
                try {
                    const data = JSON.parse(text);
                    if (data.success !== undefined) {
                        if (data.success) {
                            showResult('dbResult', 'Database Connected Successfully!\n\nSlides found: ' + (data.data ? data.data.length : 0) + '\n\nResponse: ' + JSON.stringify(data, null, 2));
                        } else {
                            showResult('dbResult', 'Database Issue:\n' + data.message, true);
                        }
                    } else {
                        showResult('dbResult', 'Invalid JSON response:\n' + text, true);
                    }
                } catch (e) {
                    showResult('dbResult', 'JSON Parse Error:\n' + e.message + '\n\nRaw Response:\n' + text.substring(0, 500), true);
                }
            })
            .catch(error => {
                showResult('dbResult', 'Fetch Error:\n' + error.message, true);
            });
        }

        function testTableExists() {
            fetch('hero_slider_handler.php?action=get_all')
                .then(r => r.text())
                .then(text => {
                    try {
                        const data = JSON.parse(text);
                        if (data.message && data.message.includes('table not found')) {
                            showResult('tableResult', 'Table Not Found!\n\nError: ' + data.message + '\n\nSolution: Run create_hero_slider_table.sql file', true);
                        } else if (data.success) {
                            showResult('tableResult', 'Table Exists!\n\nTotal slides: ' + (data.data ? data.data.length : 0));
                        } else {
                            showResult('tableResult', 'Table check result: ' + JSON.stringify(data, null, 2));
                        }
                    } catch (e) {
                        showResult('tableResult', 'Error: ' + e.message + '\nRaw: ' + text.substring(0, 300), true);
                    }
                });
        }

        function testGetAllSlides() {
            document.getElementById('getAllResult').innerHTML = '<p>Loading...</p>';
            fetch('hero_slider_handler.php?action=get_all')
                .then(r => r.text())
                .then(text => {
                    try {
                        const data = JSON.parse(text);
                        const msg = 'Success: ' + data.success + '\nSlides: ' + JSON.stringify(data, null, 2);
                        showResult('getAllResult', msg, !data.success);
                    } catch (e) {
                        showResult('getAllResult', 'Parse error: ' + e.message + '\nRaw:\n' + text.substring(0, 500), true);
                    }
                });
        }

        function testAddSlide() {
            const title = document.getElementById('testTitle').value;
            const desc = document.getElementById('testDesc').value;
            
            if (!title || !desc) {
                showResult('addResult', 'Please fill in Title and Description', true);
                return;
            }

            const formData = new FormData();
            formData.append('action', 'add');
            formData.append('title', title);
            formData.append('description', desc);
            formData.append('badge', 'Test Badge');
            formData.append('badge_icon', 'fa-star');

            document.getElementById('addResult').innerHTML = '<p>Sending request...</p>';
            
            fetch('hero_slider_handler.php', {
                method: 'POST',
                body: formData
            })
            .then(r => r.text())
            .then(text => {
                console.log('Response:', text);
                try {
                    const data = JSON.parse(text);
                    if (data.success) {
                        showResult('addResult', 'Slide Added Successfully!\n\nResponse:\n' + JSON.stringify(data, null, 2));
                    } else {
                        showResult('addResult', 'Failed to Add Slide:\n\nError: ' + data.message + '\n\nResponse:\n' + JSON.stringify(data, null, 2), true);
                    }
                } catch (e) {
                    showResult('addResult', 'JSON Parse Error: ' + e.message + '\n\nRaw Response:\n' + text.substring(0, 1000), true);
                }
            })
            .catch(error => {
                showResult('addResult', 'Fetch Error: ' + error.message, true);
            });
        }

        function checkHandlerFile() {
            fetch('hero_slider_handler.php?action=invalid')
                .then(r => r.text())
                .then(text => {
                    try {
                        const data = JSON.parse(text);
                        const msg = 'Handler file is working!\n\nChecking response format...\n\n' + JSON.stringify(data, null, 2);
                        showResult('handlerResult', msg);
                    } catch (e) {
                        showResult('handlerResult', 'Handler error or file not found:\n' + text.substring(0, 500), true);
                    }
                })
                .catch(e => {
                    showResult('handlerResult', 'File not found or server error:\n' + e.message, true);
                });
        }

        // Auto-run basic tests
        window.addEventListener('load', function() {
            console.log('Page loaded - you can run diagnostics');
            testPhpVersion();
        });
    </script>
</body>
</html>
