<?php
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();
list($action, $body) = read_action();

function check_device($device_id) {
    $d = db_one('SELECT id FROM devices WHERE id = ?', [$device_id]);
    if (!$d) json_error('device not found', 404);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!empty($_GET['device_id'])) {
        check_device((int)$_GET['device_id']);
        $row = db_one('SELECT * FROM subscriptions WHERE device_id = ?', [(int)$_GET['device_id']]);
        json_response(['subscription' => $row]);
    }
    json_error('device_id required', 400);
}

if ($action === 'update') {
    if (empty($body['device_id'])) json_error('device_id required');
    check_device((int)$body['device_id']);
    // Validate caller-provided fields before any write.
    if (isset($body['expired_date'])) {
        $d = trim((string)$body['expired_date']);
        if ($d !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $d)) {
            json_error('Expiry date must be YYYY-MM-DD.', 400);
        }
    }
    if (isset($body['price'])) {
        $p = trim((string)$body['price']);
        if ($p !== '' && !is_numeric($p)) {
            json_error('Price must be a number.', 400);
        }
    }
    if (isset($body['plan_id']) && strlen((string)$body['plan_id']) > 80) {
        json_error('Plan label is too long (max 80 characters).', 400);
    }
    $row = db_one('SELECT * FROM subscriptions WHERE device_id = ?', [(int)$body['device_id']]);
    if (!$row) {
        db_exec('INSERT INTO subscriptions (device_id) VALUES (?)', [(int)$body['device_id']]);
        $row = ['plan_id' => '', 'price' => '', 'expired_date' => '', 'is_trial' => 0, 'lock' => 0];
    }
    // Partial update — only the fields the caller actually sent get touched.
    db_exec(
        'UPDATE subscriptions SET plan_id = ?, price = ?, expired_date = ?,
                                  is_trial = ?, lock = ?, updated_at = ?
         WHERE device_id = ?',
        [array_key_exists('plan_id', $body)      ? (string)$body['plan_id']                : $row['plan_id'],
         array_key_exists('price', $body)        ? (string)$body['price']                  : $row['price'],
         array_key_exists('expired_date', $body) ? (string)$body['expired_date']           : $row['expired_date'],
         array_key_exists('is_trial', $body)     ? (int)truthy($body['is_trial'])          : (int)$row['is_trial'],
         array_key_exists('lock', $body)         ? (int)truthy($body['lock'])              : (int)$row['lock'],
         unix_now(),
         (int)$body['device_id']]
    );
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
