<?php
if (session_status() === PHP_SESSION_NONE) session_start();
include('../config/db.php');
include('../includes/auth.php');
require_admin_role();
require_once '../includes/csrf.php';
require_once '../includes/rate_limit.php';

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

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

csrf_verify();

$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
rate_limit('toggle', $ip, 60, 60);

$id  = isset($_POST['id'])  ? (int)$_POST['id']  : 0;
$val = isset($_POST['val']) ? (int)$_POST['val']  : -1;

if ($id <= 0 || !in_array($val, [0, 1], true)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'error' => 'Invalid parameters']));
}

$today = date('Y-m-d');

if ($val === 0) {
    // HIDING: always allowed — no expiry or redemption restriction for hiding
    // Also cascade-hide all child clone vouchers
    $s = $conn->prepare("
        UPDATE vouchers
        SET is_public = 0
        WHERE id = ?
          AND parent_voucher_id IS NULL
    ");
    $s->bind_param('i', $id);
    $ok = $s->execute();
    $affected = $s->affected_rows;

    if ($affected > 0) {
        // Hide child clones too so users can't see them
        $hc = $conn->prepare("UPDATE vouchers SET is_public = 0 WHERE parent_voucher_id = ?");
        $hc->bind_param('i', $id);
        $hc->execute();
        $hc->close();
    }
} else {
    // PUBLISHING: only allow if not expired
    $s = $conn->prepare("
        UPDATE vouchers
        SET is_public = 1
        WHERE id = ?
          AND parent_voucher_id IS NULL
          AND is_redeemed = 0
          AND (end_date IS NULL OR end_date = '0000-00-00' OR end_date >= ?)
    ");
    $s->bind_param('is', $id, $today);
    $ok = $s->execute();
    $affected = $s->affected_rows;
}

echo json_encode([
    'success' => (bool)$ok && $affected > 0,
    'error'   => $affected > 0 ? null : ($val === 1 ? 'Cannot publish — voucher may be expired.' : 'Voucher cannot be toggled.'),
]);
