<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../config/cors.php';
require_once '../../config/database.php';

$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        // Test database connection and check tables
        $tables = ['users', 'orders', 'products', 'categories', 'order_items'];
        $tableStatus = [];
        
        foreach ($tables as $table) {
            try {
                $stmt = $db->prepare("SELECT COUNT(*) as count FROM $table LIMIT 1");
                $stmt->execute();
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $tableStatus[$table] = [
                    'exists' => true,
                    'count' => (int)$result['count']
                ];
            } catch (PDOException $e) {
                $tableStatus[$table] = [
                    'exists' => false,
                    'error' => $e->getMessage()
                ];
            }
        }

        // Test a simple query
        $testQuery = $db->prepare("SELECT NOW() as current_time");
        $testQuery->execute();
        $currentTime = $testQuery->fetch(PDO::FETCH_ASSOC);

        $response = [
            'success' => true,
            'message' => 'Database connection successful',
            'current_time' => $currentTime['current_time'],
            'tables' => $tableStatus
        ];

        http_response_code(200);
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);

    } catch (PDOException $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'error' => 'Database connection failed: ' . $e->getMessage()
        ]);
    }
} else {
    http_response_code(405);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'error' => 'Method not allowed'
    ]);
}
?>