<?php
/**
 * Shared voucher date window + per-user clone helpers.
 */

/** @return 'ok'|'not_started'|'expired' */
function voucher_window_status(array $v, ?string $today = null): string {
    $today = $today ?? date('Y-m-d');
    $start = $v['start_date'] ?? null;
    $end   = $v['end_date'] ?? null;

    if ($start && $start !== '0000-00-00' && $start > $today) {
        return 'not_started';
    }
    if ($end && $end !== '0000-00-00' && $end < $today) {
        return 'expired';
    }
    return 'ok';
}

/** Clone a template voucher row with a unique ICE-* code. Returns new voucher id or null. */
function clone_voucher_for_user(mysqli $conn, int $templateId): ?int {
    $src = $conn->prepare('SELECT * FROM vouchers WHERE id=? LIMIT 1');
    $src->bind_param('i', $templateId);
    $src->execute();
    $v = $src->get_result()->fetch_assoc();
    $src->close();
    if (!$v) {
        return null;
    }

    $code = '';
    for ($t = 0; $t < 10; $t++) {
        $candidate = 'ICE-' . strtoupper(bin2hex(random_bytes(4)));
        $c2 = $conn->prepare('SELECT id FROM vouchers WHERE code=? LIMIT 1');
        $c2->bind_param('s', $candidate);
        $c2->execute();
        if ($c2->get_result()->num_rows === 0) {
            $code = $candidate;
            $c2->close();
            break;
        }
        $c2->close();
    }
    if ($code === '') {
        return null;
    }

    $ins = $conn->prepare(
        'INSERT INTO vouchers (parent_voucher_id,code,event_name,start_date,end_date,details,type,image,max_per_user,is_public)
         VALUES (?,?,?,?,?,?,?,?,?,0)'
    );
    $ins->bind_param(
        'isssssssi',
        $templateId,
        $code,
        $v['event_name'],
        $v['start_date'],
        $v['end_date'],
        $v['details'],
        $v['type'],
        $v['image'],
        $v['max_per_user']
    );
    $ins->execute();
    $newId = (int)$conn->insert_id;
    $ins->close();

    return $newId > 0 ? $newId : null;
}

/**
 * Parse the voucher mode and display label from the type field.
 * The type field stores "private:Category" or "public:Category".
 * Legacy vouchers with no prefix are treated as public.
 *
 * Returns: ['mode' => 'public'|'private', 'label' => 'Category name']
 */
function parse_voucher_mode(string $typeField): array {
    if (str_starts_with($typeField, 'private:')) {
        return ['mode' => 'private', 'label' => substr($typeField, 8)];
    }
    if (str_starts_with($typeField, 'public:')) {
        return ['mode' => 'public', 'label' => substr($typeField, 7)];
    }
    // Legacy: no prefix = public
    return ['mode' => 'public', 'label' => $typeField];
}
