<?php
/**
 * Chat API Setup & Test
 * Creates necessary tables and tests the API
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "========================================\n";
echo "Chat System Setup & Diagnostic Test\n";
echo "========================================\n\n";

// Database configuration
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'interior_db';

// Connect to database
echo "1. Connecting to database...\n";
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

if ($conn->connect_error) {
    die("❌ Connection failed: " . $conn->connect_error . "\n");
}
echo "✓ Connected successfully\n\n";

// Create tables if they don't exist
echo "2. Setting up database tables...\n\n";

// Chat Sessions table
$sqlSessions = "CREATE TABLE IF NOT EXISTS chat_sessions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(100) UNIQUE NOT NULL,
    category VARCHAR(50) NOT NULL,
    user_email VARCHAR(100),
    started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    ended_at DATETIME NULL,
    is_active TINYINT DEFAULT 1,
    INDEX idx_session_id (session_id),
    INDEX idx_user_email (user_email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";

if ($conn->query($sqlSessions) === TRUE) {
    echo "✓ chat_sessions table ready\n";
} else {
   echo "❌ Error creating chat_sessions: " . $conn->error . "\n";
}

// Chat Messages table
$sqlMessages = "CREATE TABLE IF NOT EXISTS chat_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(100) NOT NULL,
    sender VARCHAR(50) NOT NULL,
    message LONGTEXT NOT NULL,
    category VARCHAR(50),
    user_identifier VARCHAR(100),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_session_id (session_id),
    INDEX idx_created_at (created_at),
    FOREIGN KEY (session_id) REFERENCES chat_sessions(session_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";

if ($conn->query($sqlMessages) === TRUE) {
    echo "✓ chat_messages table ready\n";
} else {
    echo "❌ Error creating chat_messages: " . $conn->error . "\n";
}

echo "\n3. Database Status:\n";
// Check table existence
$tables = ['chat_sessions', 'chat_messages'];
foreach ($tables as $table) {
    $result = $conn->query("SHOW TABLES LIKE '$table'");
    if ($result && $result->num_rows > 0) {
        echo "✓ Table '$table' exists\n";
    } else {
        echo "❌ Table '$table' does NOT exist\n";
    }
}

echo "\n4. API Configuration:\n";
// Check OpenAI API key
$apiKey = getenv('OPENAI_API_KEY');
if (!empty($apiKey)) {
    echo "✓ OpenAI API Key configured: " . substr($apiKey, 0, 10) . "...\n";
} else {
    echo "⚠ OpenAI API Key not configured (fallback mode)\n";
}

echo "\n5. API Endpoint Test:\n";
// Simulate API request
$_GET['action'] = 'get_status';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/interior/auth-system/api/chat-ai-v3.php?action=get_status';
$_SERVER['SCRIPT_NAME'] = '/interior/auth-system/api/chat-ai-v3.php';
$_SERVER['PHP_SELF'] = '/interior/auth-system/api/chat-ai-v3.php';

// Capture API output
ob_start();
include __DIR__ . '/auth-system/api/chat-ai-v3.php';
$apiOutput = ob_get_clean();

echo "Raw output length: " . strlen($apiOutput) . " bytes\n";
echo "First 100 chars: " . substr($apiOutput, 0, 100) . "\n\n";

// Try to parse JSON
$jsonData = json_decode($apiOutput, true);
if ($jsonData !== null) {
    echo "✓ Valid JSON Response\n";
    echo json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
} else {
    echo "❌ Invalid JSON Response\n";
    echo "Error: " . json_last_error_msg() . "\n";
    echo "Full output:\n" . $apiOutput . "\n";
}

$conn->close();
echo "\n========================================\n";
echo "Test Complete\n";
echo "========================================\n";
