<?php
/**
 * Dismiss Banner API
 * 
 * Allows users to permanently dismiss a dismissible banner
 * Saves dismissal to user_dismissed_banners table
 * 
 * Method: POST
 * Body: { "user_id": 123, "banner_id": 2 }
 * 
 * Response:
 * {
 *   "success": true,
 *   "message": "Banner dismissed successfully"
 * }
 */

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 input
    $input = json_decode(file_get_contents('php://input'), true);
    $user_id = $input['user_id'] ?? null;
    $banner_id = $input['banner_id'] ?? null;
    
    // Validate required fields
    if (!$user_id || !$banner_id) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'User ID and Banner ID are required'
        ], JSON_PRETTY_PRINT);
        exit;
    }
    
    // Check if banner exists and is dismissible
    $check_sql = "SELECT id, banner_type FROM hero_banners WHERE id = ?";
    $check_stmt = $pdo->prepare($check_sql);
    $check_stmt->execute([$banner_id]);
    $banner = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$banner) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Banner not found'
        ], JSON_PRETTY_PRINT);
        exit;
    }
    
    // Check if banner is dismissible
    if ($banner['banner_type'] !== 'dismissible') {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'This banner cannot be dismissed. Only dismissible banners can be closed.'
        ], JSON_PRETTY_PRINT);
        exit;
    }
    
    // Check if user exists
    $user_check_sql = "SELECT id FROM users WHERE id = ?";
    $user_check_stmt = $pdo->prepare($user_check_sql);
    $user_check_stmt->execute([$user_id]);
    
    if (!$user_check_stmt->fetch()) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'User not found'
        ], JSON_PRETTY_PRINT);
        exit;
    }
    
    // Insert dismissal record (IGNORE if already dismissed)
    $sql = "INSERT IGNORE INTO user_dismissed_banners 
            (user_id, banner_id, dismissed_at) 
            VALUES (?, ?, NOW())";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $banner_id]);
    
    // Check if row was inserted (or already existed)
    $affected_rows = $stmt->rowCount();
    
    if ($affected_rows > 0) {
        echo json_encode([
            'success' => true,
            'message' => 'Banner dismissed successfully'
        ], JSON_PRETTY_PRINT);
    } else {
        // Already dismissed
        echo json_encode([
            'success' => true,
            'message' => 'Banner was already dismissed'
        ], JSON_PRETTY_PRINT);
    }
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to dismiss banner',
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
