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

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!empty($_GET['id'])) {
        $row = db_one('SELECT * FROM portals WHERE id = ?', [(int)$_GET['id']]);
        if (!$row) json_error('portal not found', 404);
        json_response(['portal' => $row]);
    }
    $rows = db_all('SELECT * FROM portals ORDER BY sort_order ASC, id ASC');
    json_response(['portals' => $rows]);
}

if ($action === 'create') {
    $labels = ['name' => 'a portal name', 'url' => 'a portal URL'];
    foreach (['name','url'] as $f) {
        if (empty($body[$f])) json_error('Please enter ' . $labels[$f] . '.');
    }
    if (!preg_match('#^https?://#i', trim((string)$body['url']))) {
        json_error('Portal URL must start with http:// or https://.');
    }
    $public_id = !empty($body['public_id']) ? $body['public_id']
                : next_public_id('portals');
    try {
        $id = db_insert(
            'INSERT INTO portals (public_id, name, type, url, is_protected, sort_order, enabled)
             VALUES (?, ?, ?, ?, ?, ?, ?)',
            [$public_id,
             trim((string)$body['name']),
             $body['type'] ?? 'xtream',
             trim((string)$body['url']),
             ($body['is_protected'] ?? '0') ? '1' : '0',
             (int)($body['sort_order'] ?? 0),
             truthy($body['enabled'] ?? 1)]
        );
        json_response(['ok' => true, 'id' => $id, 'public_id' => $public_id]);
    } catch (Exception $e) {
        panel_log_exception($e, ['context' => 'portals.create']);
        json_error('Could not save the portal. Try again.');
    }
}

if ($action === 'update') {
    if (empty($body['id'])) json_error('missing id');
    $row = db_one('SELECT * FROM portals WHERE id = ?', [(int)$body['id']]);
    if (!$row) json_error('portal not found', 404);
    if (array_key_exists('url', $body) && !preg_match('#^https?://#i', trim((string)$body['url']))) {
        json_error('Portal URL must start with http:// or https://.');
    }
    db_exec(
        'UPDATE portals SET name = ?, type = ?, url = ?, is_protected = ?, sort_order = ?, enabled = ?
         WHERE id = ?',
        [isset($body['name']) ? trim((string)$body['name']) : $row['name'],
         $body['type'] ?? $row['type'],
         isset($body['url']) ? trim((string)$body['url']) : $row['url'],
         ($body['is_protected'] ?? $row['is_protected']) ? '1' : '0',
         (int)($body['sort_order'] ?? $row['sort_order']),
         truthy($body['enabled'] ?? $row['enabled']),
         (int)$body['id']]
    );
    json_response(['ok' => true]);
}

if ($action === 'delete') {
    if (empty($body['id'])) json_error('missing id');
    db_exec('DELETE FROM portals WHERE id = ?', [(int)$body['id']]);
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
