<?php
/**
 * handlers/manage_vouchers_handler.php
 * Handles all POST actions for manage_vouchers.php
 * Actions: create_voucher, bulk_delete_vouchers
 *
 * Expects: $conn, $flash, $flashType to be defined by the caller.
 * Sets:    $flash, $flashType on completion.
 */

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'])) return;

// Auth already enforced by manage_vouchers.php (require_admin_role at page level)
csrf_verify();

$action = $_POST['action'];

// ── Create a new voucher template ─────────────────────────────────────────────
if ($action === 'create_voucher') {
    $event_name   = substr(trim($_POST['event_name'] ?? ''), 0, 100);
    $type         = substr(trim($_POST['type']       ?? ''), 0, 100);
    $details      = substr(trim($_POST['details']    ?? ''), 0, 2000);
    $start_date   = $_POST['start_date'] ?? '';
    $end_date     = $_POST['end_date']   ?? '';
    $max_per_user = max(1, (int)($_POST['max_per_user'] ?? 1));
    // voucher_mode: 'public'  = anyone can claim once published
    //               'private' = exclusive, only released to specific users
    $voucher_mode = ($_POST['voucher_mode'] ?? 'public') === 'private' ? 'private' : 'public';

    // 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;

    if (empty($event_name)) {
        $flash = 'Voucher name is required.'; $flashType = 'error';
    } elseif (!$start_date) {
        $flash = 'Start date is required.'; $flashType = 'error';
    } elseif (!$end_date) {
        $flash = 'End date is required.'; $flashType = 'error';
    } elseif (strtotime($end_date) < strtotime($start_date)) {
        $flash = 'End date cannot be before start date.'; $flashType = 'error';
    } else {
        // Generate unique code
        $code = '';
        for ($t = 0; $t < 10; $t++) {
            $candidate = 'ICE-' . strtoupper(bin2hex(random_bytes(4)));
            $ck = $conn->prepare('SELECT id FROM vouchers WHERE code=? LIMIT 1');
            $ck->bind_param('s', $candidate);
            $ck->execute();
            if ($ck->get_result()->num_rows === 0) { $code = $candidate; $ck->close(); break; }
            $ck->close();
        }

        if (!$code) {
            $flash = 'Code generation failed. Try again.'; $flashType = 'error';
        } else {
            // Store mode as prefix in type field: "private:Category" or "public:Category"
            $typeStored = $voucher_mode . ($type ? ':' . $type : '');
            // is_public = 0 always on creation — admin publishes manually via toggle
            $ins = $conn->prepare('
                INSERT INTO vouchers
                    (code, event_name, type, details, start_date, end_date, max_per_user, is_public, parent_voucher_id, image)
                VALUES (?,?,?,?,?,?,?,0,NULL,"")
            ');
            $ins->bind_param('ssssssi', $code, $event_name, $typeStored, $details, $start_date, $end_date, $max_per_user);
            $ok = $ins->execute();
            $ins->close();

            $modeLabel = $voucher_mode === 'private' ? 'Private (exclusive)' : 'Public';
            $flash     = $ok
                ? "Voucher \"{$event_name}\" created as {$modeLabel} — Hidden. Publish it when ready."
                : 'Could not create voucher.';
            if (!$ok) $flashType = 'error';
        }
    }
}

// ── Bulk delete voucher templates ─────────────────────────────────────────────
if ($action === 'bulk_delete_vouchers') {
    $ids = isset($_POST['voucher_ids']) ? array_filter(array_map('intval', $_POST['voucher_ids'])) : [];

    if (empty($ids)) {
        $flash = 'No vouchers selected.'; $flashType = 'error';
    } else {
        $deleted = 0; $skipped = 0;
        foreach ($ids as $vid) {
            // Delete child clones first (FK cascade also handles claims)
            $dc = $conn->prepare('DELETE FROM vouchers WHERE parent_voucher_id = ?');
            $dc->bind_param('i', $vid);
            $dc->execute();
            $dc->close();

            // Delete the parent template
            $dp = $conn->prepare('DELETE FROM vouchers WHERE id = ? AND parent_voucher_id IS NULL');
            $dp->bind_param('i', $vid);
            $dp->execute();
            $dp->affected_rows > 0 ? $deleted++ : $skipped++;
            $dp->close();
        }
        $flash = "Deleted {$deleted} voucher(s).";
        if ($skipped > 0) $flash .= " {$skipped} could not be deleted.";
        if ($deleted === 0) $flashType = 'error';
    }
}

// ── Edit voucher template ──────────────────────────────────────────────────────
// Migrated from edit_voucher.php (was a standalone AJAX endpoint).
// Returns JSON — caller must set Content-Type: application/json before including
// this handler, or check $action upstream and output JSON directly.
if ($action === 'edit_voucher') {
    header('Content-Type: application/json');

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

    // Update parent/template voucher
    // Convert empty strings to null — MySQL DATE columns reject empty string in strict mode
    $start_date = $start_date !== '' ? $start_date : null;
    $end_date   = $end_date   !== '' ? $end_date   : null;

    $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 so existing claimants see updates
    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]);
    exit;
}
