<?php
/**
 * Hero Banners API - Public Endpoint
 * 
 * Returns active hero banners for display in app home screen
 * Excludes banners that the user has dismissed (if user_id provided)
 * 
 * Method: POST
 * Body: { "user_id": 123 } (optional)
 * 
 * Response:
 * {
 *   "success": true,
 *   "data": [
 *     {
 *       "id": 1,
 *       "title": "Start Your Journey",
 *       "description": "Learn English...",
 *       "icon": "star",
 *       "gradient_start": "#FF9A56",
 *       "gradient_end": "#FFC371",
 *       "text_color": "#FFFFFF",
 *       "image_url": null,
 *       "image_mode": "icon_only",
 *       "image_overlay_opacity": "0.00",
 *       "action_type": "none",
 *       "action_value": null,
 *       "action_text": null,
 *       "banner_type": "permanent",
 *       "dismissible": false
 *     }
 *   ]
 * }
 */

require_once 'config.php';

// Get database connection
$pdo = getDBConnection();
if (!$pdo) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    // Get user_id from POST body (optional - for excluding dismissed banners)
    $input = json_decode(file_get_contents('php://input'), true);
    $user_id = $input['user_id'] ?? null;
    
    // Build query to get active banners
    $sql = "SELECT 
              hb.id,
              hb.title,
              hb.description,
              hb.icon,
              hb.gradient_start,
              hb.gradient_end,
              hb.text_color,
              hb.image_url,
              hb.image_mode,
              hb.image_overlay_opacity,
              hb.action_type,
              hb.action_value,
              hb.action_text,
              hb.banner_type,
              (hb.banner_type = 'dismissible') AS dismissible
            FROM hero_banners hb
            WHERE hb.is_active = 1";
    
    // If user is logged in, exclude banners they've dismissed
    if ($user_id) {
        $sql .= " AND hb.id NOT IN (
                    SELECT banner_id 
                    FROM user_dismissed_banners 
                    WHERE user_id = :user_id
                  )";
    }
    
    // Order by display_order
    $sql .= " ORDER BY hb.display_order ASC";
    
    $stmt = $pdo->prepare($sql);
    
    if ($user_id) {
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    }
    
    $stmt->execute();
    $banners = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Convert dismissible to boolean and ensure proper types
    foreach ($banners as &$banner) {
        $banner['id'] = (int)$banner['id'];
        $banner['dismissible'] = (bool)$banner['dismissible'];
        
        // Convert image_overlay_opacity to float
        $banner['image_overlay_opacity'] = (float)$banner['image_overlay_opacity'];
        
        // Ensure nulls are properly set
        if (empty($banner['image_url'])) {
            $banner['image_url'] = null;
        }
        if (empty($banner['action_value'])) {
            $banner['action_value'] = null;
        }
        if (empty($banner['action_text'])) {
            $banner['action_text'] = null;
        }
    }
    
    echo json_encode([
        'success' => true,
        'data' => $banners,
        'count' => count($banners)
    ], JSON_PRETTY_PRINT);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch banners',
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
