<?php
session_start();
require_once __DIR__ . '/../config/database.php';

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

$allowedTables = ['products', 'banners', 'tutorials'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$action = $_POST['action'] ?? '';
$table  = $_POST['table']  ?? '';
$id     = (int)($_POST['id'] ?? 0);

if ($action !== 'toggle_active' || !array_key_exists($table, $allowedTables) || $id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT is_active FROM {$allowedTables[$table]} WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch();
    if (!$row) {
        echo json_encode(['success' => false, 'message' => 'Record not found']);
        exit;
    }

    $newStatus = $row['is_active'] ? 0 : 1;
    $update = $pdo->prepare("UPDATE {$allowedTables[$table]} SET is_active = :status WHERE id = :id");
    $update->execute([':status' => $newStatus, ':id' => $id]);

    echo json_encode(['success' => true, 'new_status' => $newStatus]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error']);
}