<?php
/**
 * Debug Hero Banners API
 * Use this to diagnose issues with hero_banners.php
 */

require_once '../config.php';

// Get database connection
$pdo = getDBConnection();

header('Content-Type: application/json');

$debug = [];

// 1. Check if PDO exists
$debug['pdo_exists'] = isset($pdo) && $pdo !== null;
$debug['pdo_type'] = $pdo ? get_class($pdo) : 'null';

// 2. Check if tables exist
try {
    $result = $pdo->query("SHOW TABLES LIKE 'hero_banners'");
    $debug['hero_banners_table_exists'] = $result->rowCount() > 0;
} catch (Exception $e) {
    $debug['hero_banners_table_error'] = $e->getMessage();
}

try {
    $result = $pdo->query("SHOW TABLES LIKE 'user_dismissed_banners'");
    $debug['user_dismissed_banners_table_exists'] = $result->rowCount() > 0;
} catch (Exception $e) {
    $debug['user_dismissed_banners_table_error'] = $e->getMessage();
}

// 3. If table exists, check structure
if ($debug['hero_banners_table_exists'] ?? false) {
    try {
        $result = $pdo->query("DESCRIBE hero_banners");
        $debug['hero_banners_columns'] = $result->fetchAll(PDO::FETCH_COLUMN);
    } catch (Exception $e) {
        $debug['hero_banners_structure_error'] = $e->getMessage();
    }
    
    // Count records
    try {
        $result = $pdo->query("SELECT COUNT(*) FROM hero_banners");
        $debug['hero_banners_count'] = $result->fetchColumn();
    } catch (Exception $e) {
        $debug['hero_banners_count_error'] = $e->getMessage();
    }
}

// 4. Try the actual query from the API
try {
    $sql = "SELECT 
              hb.*,
              (SELECT COUNT(*) FROM user_dismissed_banners WHERE banner_id = hb.id) as dismissal_count
            FROM hero_banners hb
            ORDER BY hb.display_order ASC, hb.id DESC";
    
    $stmt = $pdo->query($sql);
    $banners = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $debug['query_success'] = true;
    $debug['banners_found'] = count($banners);
} catch (Exception $e) {
    $debug['query_error'] = $e->getMessage();
    $debug['query_success'] = false;
}

// 5. Check admin session
session_start();
$debug['admin_logged_in'] = isset($_SESSION['admin_id']);
$debug['admin_id'] = $_SESSION['admin_id'] ?? null;

echo json_encode($debug, JSON_PRETTY_PRINT);
