<?php
/**
 * Hero Banners Admin API
 * 
 * CRUD operations for managing hero banners
 * 
 * Actions:
 * - list: Get all banners with dismissal stats
 * - get: Get single banner by ID
 * - create: Create new banner
 * - update: Update existing banner
 * - delete: Delete banner
 * - reorder: Update display order
 * - toggle_status: Activate/deactivate banner
 * - get_dismissal_stats: Get dismissal statistics
 * - reset_dismissals: Clear dismissals for a banner
 */

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;
}

// Check admin authentication - Use same session name as config
if (session_status() === PHP_SESSION_NONE) {
    session_name(ADMIN_SESSION_NAME);
    session_start();
}

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

try {
    switch ($action) {
        
        // ================================================
        // LIST - Get all banners with stats
        // ================================================
        case 'list':
            // Check if hero_banners table exists
            $checkTable = $pdo->query("SHOW TABLES LIKE 'hero_banners'");
            if ($checkTable->rowCount() === 0) {
                http_response_code(500);
                echo json_encode([
                    'success' => false, 
                    'message' => 'Hero banners table does not exist. Please run the SQL migration file first.',
                    'help' => 'Upload and run create_hero_banners_SAFE.sql'
                ]);
                exit;
            }
            
            // Check if dismissal table exists (safe fallback)
            $checkDismissalTable = $pdo->query("SHOW TABLES LIKE 'user_dismissed_banners'");
            $dismissalTableExists = $checkDismissalTable->rowCount() > 0;
            
            if ($dismissalTableExists) {
                $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";
            } else {
                // Fallback: work without dismissal table
                $sql = "SELECT 
                          hb.*,
                          0 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);
            
            // Convert types
            foreach ($banners as &$banner) {
                $banner['id'] = (int)$banner['id'];
                $banner['is_active'] = (bool)$banner['is_active'];
                $banner['display_order'] = (int)$banner['display_order'];
                $banner['dismissal_count'] = (int)$banner['dismissal_count'];
                $banner['image_overlay_opacity'] = (float)$banner['image_overlay_opacity'];
            }
            
            echo json_encode([
                'success' => true,
                'data' => $banners
            ], JSON_PRETTY_PRINT);
            break;
        
        // ================================================
        // GET - Single banner
        // ================================================
        case 'get':
            $id = $_GET['id'] ?? null;
            
            if (!$id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banner ID required']);
                exit;
            }
            
            $stmt = $pdo->prepare("SELECT * FROM hero_banners WHERE id = ?");
            $stmt->execute([$id]);
            $banner = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$banner) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Banner not found']);
                exit;
            }
            
            echo json_encode([
                'success' => true,
                'data' => $banner
            ], JSON_PRETTY_PRINT);
            break;
        
        // ================================================
        // CREATE - New banner
        // ================================================
        case 'create':
            $input = json_decode(file_get_contents('php://input'), true);
            
            // Validate required fields
            $required = ['title', 'description'];
            foreach ($required as $field) {
                if (empty($input[$field])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => ucfirst($field) . ' is required']);
                    exit;
                }
            }
            
            // Set defaults
            $data = [
                'title' => $input['title'],
                'description' => $input['description'],
                'icon' => $input['icon'] ?? 'star',
                'gradient_start' => $input['gradient_start'] ?? '#FF6B6B',
                'gradient_end' => $input['gradient_end'] ?? '#FFE66D',
                'text_color' => $input['text_color'] ?? '#FFFFFF',
                'image_url' => $input['image_url'] ?? null,
                'image_mode' => $input['image_mode'] ?? 'icon_only',
                'image_overlay_opacity' => $input['image_overlay_opacity'] ?? 0.50,
                'action_type' => $input['action_type'] ?? 'none',
                'action_value' => $input['action_value'] ?? null,
                'action_text' => $input['action_text'] ?? null,
                'banner_type' => $input['banner_type'] ?? 'permanent',
                'is_active' => isset($input['is_active']) ? (int)$input['is_active'] : 1,
                'display_order' => $input['display_order'] ?? 0
            ];
            
            $sql = "INSERT INTO hero_banners (
                      title, description, icon,
                      gradient_start, gradient_end, text_color,
                      image_url, image_mode, image_overlay_opacity,
                      action_type, action_value, action_text,
                      banner_type, is_active, display_order
                    ) VALUES (
                      :title, :description, :icon,
                      :gradient_start, :gradient_end, :text_color,
                      :image_url, :image_mode, :image_overlay_opacity,
                      :action_type, :action_value, :action_text,
                      :banner_type, :is_active, :display_order
                    )";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($data);
            
            $new_id = $pdo->lastInsertId();
            
            echo json_encode([
                'success' => true,
                'message' => 'Banner created successfully',
                'id' => (int)$new_id
            ], JSON_PRETTY_PRINT);
            break;
        
        // ================================================
        // UPDATE - Existing banner
        // ================================================
        case 'update':
            $input = json_decode(file_get_contents('php://input'), true);
            
            $id = $input['id'] ?? null;
            if (!$id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banner ID required']);
                exit;
            }
            
            // Build update query dynamically
            $allowed_fields = [
                'title', 'description', 'icon',
                'gradient_start', 'gradient_end', 'text_color',
                'image_url', 'image_mode', 'image_overlay_opacity',
                'action_type', 'action_value', 'action_text',
                'banner_type', 'is_active', 'display_order'
            ];
            
            $update_fields = [];
            $params = ['id' => $id];
            
            foreach ($allowed_fields as $field) {
                if (array_key_exists($field, $input)) {
                    $update_fields[] = "$field = :$field";
                    $params[$field] = $input[$field];
                }
            }
            
            if (empty($update_fields)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'No fields to update']);
                exit;
            }
            
            $sql = "UPDATE hero_banners SET " . implode(', ', $update_fields) . " WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            echo json_encode([
                'success' => true,
                'message' => 'Banner updated successfully'
            ], JSON_PRETTY_PRINT);
            break;
        
        // ================================================
        // DELETE - Remove banner
        // ================================================
        case 'delete':
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? $_GET['id'] ?? null;
            
            if (!$id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banner ID required']);
                exit;
            }
            
            $stmt = $pdo->prepare("DELETE FROM hero_banners WHERE id = ?");
            $stmt->execute([$id]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Banner deleted successfully'
                ], JSON_PRETTY_PRINT);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Banner not found']);
            }
            break;
        
        // ================================================
        // REORDER - Update display order
        // ================================================
        case 'reorder':
            $input = json_decode(file_get_contents('php://input'), true);
            $banners = $input['banners'] ?? [];
            
            if (empty($banners)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banners array required']);
                exit;
            }
            
            $pdo->beginTransaction();
            
            try {
                $stmt = $pdo->prepare("UPDATE hero_banners SET display_order = ? WHERE id = ?");
                
                foreach ($banners as $banner) {
                    $stmt->execute([$banner['display_order'], $banner['id']]);
                }
                
                $pdo->commit();
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Banner order updated successfully'
                ], JSON_PRETTY_PRINT);
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;
        
        // ================================================
        // TOGGLE STATUS - Activate/Deactivate
        // ================================================
        case 'toggle_status':
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? null;
            
            if (!$id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banner ID required']);
                exit;
            }
            
            $sql = "UPDATE hero_banners SET is_active = NOT is_active WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            // Get new status
            $stmt = $pdo->prepare("SELECT is_active FROM hero_banners WHERE id = ?");
            $stmt->execute([$id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'message' => 'Banner status updated',
                'is_active' => (bool)$result['is_active']
            ], JSON_PRETTY_PRINT);
            break;
        
        // ================================================
        // GET DISMISSAL STATS
        // ================================================
        case 'get_dismissal_stats':
            $id = $_GET['id'] ?? null;
            
            if (!$id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banner ID required']);
                exit;
            }
            
            // Get total dismissals and recent dismissals
            $sql = "SELECT 
                      COUNT(*) as total_dismissals,
                      COUNT(CASE WHEN dismissed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as last_7_days,
                      COUNT(CASE WHEN dismissed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as last_30_days
                    FROM user_dismissed_banners
                    WHERE banner_id = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => $stats
            ], JSON_PRETTY_PRINT);
            break;
        
        // ================================================
        // RESET DISMISSALS
        // ================================================
        case 'reset_dismissals':
            $input = json_decode(file_get_contents('php://input'), true);
            $banner_id = $input['banner_id'] ?? null;
            $user_id = $input['user_id'] ?? null;
            
            if (!$banner_id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Banner ID required']);
                exit;
            }
            
            if ($user_id) {
                // Reset for specific user
                $stmt = $pdo->prepare("DELETE FROM user_dismissed_banners WHERE banner_id = ? AND user_id = ?");
                $stmt->execute([$banner_id, $user_id]);
                $message = 'Dismissal reset for user';
            } else {
                // Reset for all users
                $stmt = $pdo->prepare("DELETE FROM user_dismissed_banners WHERE banner_id = ?");
                $stmt->execute([$banner_id]);
                $message = 'All dismissals reset for banner';
            }
            
            echo json_encode([
                'success' => true,
                'message' => $message,
                'deleted_count' => $stmt->rowCount()
            ], JSON_PRETTY_PRINT);
            break;
        
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error',
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
