<?php
// =============================================================================
// /api/trial_expiry.php — manage per-MAC trial expiry rows. Backed by the
// `subscriptions` table; a "trial row" is any subscription with is_trial=0.
//
// GET                          → { default: '2033-03-13', trials: [...] }
// POST action=set              → { mac_address, expired_date(YYYY-MM-DD) }
// POST action=delete           → { mac_address }
// POST action=set_default      → { date }   (panel-wide default expiry)
// =============================================================================
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();

list($action, $body) = read_action();

function trial_default(): string {
    $row = db_one('SELECT value FROM webview_settings WHERE key=?', ['trial_default_date']);
    return $row && $row['value'] ? (string)$row['value'] : '2033-03-13';
}

if ($action === 'list' || ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === '')) {
    $rows = db_all(
        'SELECT d.id AS device_id, d.mac_address, s.expired_date, s.is_trial, s.updated_at
         FROM subscriptions s JOIN devices d ON d.id = s.device_id
         WHERE s.is_trial = 0 AND s.expired_date != ""
         ORDER BY s.expired_date ASC, d.mac_address ASC'
    );
    json_response(['default' => trial_default(), 'trials' => $rows]);
}

require_method('POST');

if ($action === 'set') {
    $mac  = strtolower(trim((string)($body['mac_address'] ?? '')));
    $date = trim((string)($body['expired_date'] ?? ''));
    if ($mac === '' || !preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/', $mac)) json_error('valid mac required', 400);
    if (!preg_match('/^\d{4}-\d{2}-\d{2}/', $date)) json_error('YYYY-MM-DD date required', 400);
    $dev = db_one('SELECT id FROM devices WHERE mac_address = ?', [$mac]);
    if (!$dev) json_error('device with that MAC not found', 404);
    db_exec('UPDATE subscriptions SET expired_date = ?, is_trial = 0, updated_at = ? WHERE device_id = ?',
            [$date, time(), (int)$dev['id']]);
    json_response(['ok' => true]);
}

if ($action === 'delete') {
    $mac = strtolower(trim((string)($body['mac_address'] ?? '')));
    $dev = db_one('SELECT id FROM devices WHERE mac_address = ?', [$mac]);
    if (!$dev) json_error('device not found', 404);
    db_exec('UPDATE subscriptions SET expired_date = "", updated_at = ? WHERE device_id = ?',
            [time(), (int)$dev['id']]);
    json_response(['ok' => true]);
}

if ($action === 'set_default') {
    $date = trim((string)($body['date'] ?? ''));
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) json_error('YYYY-MM-DD required', 400);
    db_exec('INSERT INTO webview_settings (key, value, updated_at) VALUES (?, ?, ?)
             ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at',
            ['trial_default_date', $date, time()]);
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
