<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();

/**
 * ----------------------------
 * Method check
 * ----------------------------
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/**
 * ----------------------------
 * Required fields
 * ----------------------------
 */
Validator::required($_POST, ['id', 'is_active']);

$sliderId = (int)$_POST['id'];
$isActive = (int)$_POST['is_active'];

/**
 * ----------------------------
 * Validate is_active value
 * ----------------------------
 */
if (!in_array($isActive, [0, 1], true)) {
    Response::error('Invalid status value', 422);
}

/**
 * ----------------------------
 * Check slider exists
 * ----------------------------
 */
$stmt = $db->prepare("SELECT id FROM home_page_sliders WHERE id = :id");
$stmt->execute(['id' => $sliderId]);

if (!$stmt->fetch()) {
    Response::error('Slider not found', 404);
}

/**
 * ----------------------------
 * Update status
 * ----------------------------
 */
$stmt = $db->prepare("
    UPDATE home_page_sliders
    SET is_active = :is_active, updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'id'        => $sliderId,
    'is_active'=> $isActive
]);

/**
 * ----------------------------
 * Response
 * ----------------------------
 */
Response::success(
    $isActive ? 'Slider activated successfully' : 'Slider deactivated successfully'
);
