<?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';

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();

$id         = (int)($_POST['id'] ?? 0);
$event_name = substr(trim($_POST['event_name'] ?? ''), 0, 100);
$start_date = $_POST['start_date'] ?? '';
$end_date   = $_POST['end_date']   ?? '';
$type       = substr(trim($_POST['type'] ?? ''), 0, 100);
$details    = substr(trim($_POST['details'] ?? ''), 0, 2000);

if ($id <= 0 || empty($event_name)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'error' => 'Invalid input']));
}

if ($start_date && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
    die(json_encode(['success' => false, 'error' => 'Start date format invalid.']));
}
if ($end_date && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
    die(json_encode(['success' => false, 'error' => 'End date format invalid.']));
}
if ($start_date && $end_date && strtotime($end_date) < strtotime($start_date)) {
    die(json_encode(['success' => false, 'error' => 'End date cannot be before start date.']));
}

// Convert empty strings to NULL — MySQL DATE columns reject '' in strict mode
$start_date = $start_date !== '' ? $start_date : null;
$end_date   = $end_date   !== '' ? $end_date   : null;

// Update parent/template voucher
$s = $conn->prepare('UPDATE vouchers SET event_name=?, type=?, start_date=?, end_date=?, details=? WHERE id=? AND parent_voucher_id IS NULL');
$s->bind_param('sssssi', $event_name, $type, $start_date, $end_date, $details, $id);
$ok = $s->execute();
$affected = $s->affected_rows;
$s->close();

// Propagate name/dates/description to all child clones
if ($ok && $affected > 0) {
    $cs = $conn->prepare('UPDATE vouchers SET event_name=?, start_date=?, end_date=?, details=? WHERE parent_voucher_id=?');
    $cs->bind_param('ssssi', $event_name, $start_date, $end_date, $details, $id);
    $cs->execute();
    $cs->close();
}

echo json_encode(['success' => (bool)$ok && $affected > 0]);
