<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_device_access.php';

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

function json_out(array $payload): void {
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function normalize_mac(string $mac): ?string {
    $clean = preg_replace('/[^A-Fa-f0-9]/', '', trim($mac));
    $clean = strtoupper(substr($clean, 0, 12));
    if (strlen($clean) !== 12) {
        return null;
    }
    return implode(':', str_split($clean, 2));
}

function csv_to_array(?string $value): array {
    if ($value === null) return [];
    $parts = preg_split('/[,;|]/', $value) ?: [];
    $out = [];
    foreach ($parts as $part) {
        $item = trim((string)$part);
        if ($item !== '') $out[] = $item;
    }
    return array_values(array_unique($out));
}

$dbPath = dirname(__DIR__) . '/db.db';

try {
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    da_ensure_schema($db);
} catch (Throwable $e) {
    json_out(['status' => 'erro']);
}

try {
    $db->exec("CREATE TABLE IF NOT EXISTS access_rules (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        mac TEXT NOT NULL,
        allow_all_live INTEGER NOT NULL DEFAULT 1,
        allow_all_movies INTEGER NOT NULL DEFAULT 1,
        allow_all_series INTEGER NOT NULL DEFAULT 1,
        blocked_live_ids TEXT DEFAULT '',
        blocked_movie_ids TEXT DEFAULT '',
        blocked_series_ids TEXT DEFAULT '',
        blocked_live_categories TEXT DEFAULT '',
        blocked_movie_categories TEXT DEFAULT '',
        blocked_series_categories TEXT DEFAULT '',
        usuario_id INTEGER DEFAULT 0,
        allow_tab_movies INTEGER NOT NULL DEFAULT 1,
        allow_tab_series INTEGER NOT NULL DEFAULT 1,
        allow_tab_kids INTEGER NOT NULL DEFAULT 1,
        allow_tab_anime INTEGER NOT NULL DEFAULT 1,
        allow_tab_novelas INTEGER NOT NULL DEFAULT 1,
        allow_tab_esportes INTEGER NOT NULL DEFAULT 1,
        updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))
    )");
    $db->exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_access_rules_mac_owner ON access_rules(mac, usuario_id)");
    foreach (['allow_tab_novelas' => 'INTEGER NOT NULL DEFAULT 1', 'allow_tab_esportes' => 'INTEGER NOT NULL DEFAULT 1'] as $col => $def) {
        try { if (!da_column_exists($db, 'access_rules', $col)) $db->exec("ALTER TABLE access_rules ADD COLUMN $col $def"); } catch (Throwable $e) {}
    }
} catch (Throwable $e) {
    json_out(['status' => 'erro']);
}

$macDb = normalize_mac((string)($_POST['mac'] ?? $_GET['mac'] ?? ''));
$deviceType = da_normalize_device_type((string)($_POST['device_type'] ?? $_GET['device_type'] ?? 'tv'));
if ($macDb === null) {
    json_out(['status' => 'erro']);
}

try {
    $userRow = da_find_user_by_mac($db, $macDb) ?: [];
    $profile = da_get_profile_by_key($db, da_user_key($userRow['username'] ?? '', $userRow['password'] ?? ''));
    da_update_last_device($db, $macDb, $deviceType);
    $stmt = $db->prepare('SELECT * FROM access_rules WHERE mac = ? ORDER BY updated_at DESC, id DESC LIMIT 1');
    $stmt->execute([$macDb]);
    $row = $stmt->fetch();

    if (!$row) {
        json_out([
            'status' => 'ok',
            'mac' => $macDb,
            'rules_found' => false,
            'allow_all_live' => !empty($profile['allow_live']),
            'allow_all_movies' => !empty($profile['allow_movies']),
            'allow_all_series' => !empty($profile['allow_series']),
            'allow_tab_movies' => !empty($profile['allow_tab_movies']),
            'allow_tab_series' => !empty($profile['allow_tab_series']),
            'allow_tab_kids' => !empty($profile['allow_tab_kids']),
            'allow_tab_anime' => !empty($profile['allow_tab_anime']),
            'allow_tab_novelas' => !empty($profile['allow_tab_novelas']),
            'allow_tab_esportes' => !empty($profile['allow_tab_esportes']),
            'allow_tv' => !empty($profile['allow_tv']),
            'allow_mobile' => !empty($profile['allow_mobile']),
            'device_type' => $deviceType,
            'blocked_live_ids' => [],
            'blocked_movie_ids' => [],
            'blocked_series_ids' => [],
            'blocked_live_categories' => [],
            'blocked_movie_categories' => [],
            'blocked_series_categories' => [],
            'updated_at' => 0,
        ]);
    }

    $contentLive = !empty($profile['allow_live']);
    $contentMovies = !empty($profile['allow_movies']);
    $contentSeries = !empty($profile['allow_series']);
    $allowLive = ($contentLive && ((int)($row['allow_all_live'] ?? 1) === 1));
    $allowMovies = ($contentMovies && ((int)($row['allow_all_movies'] ?? 1) === 1));
    $allowSeries = ($contentSeries && ((int)($row['allow_all_series'] ?? 1) === 1));
    $allowTabMovies = ((int)($row['allow_tab_movies'] ?? ($allowMovies ? 1 : 0)) === 1) && !empty($profile['allow_tab_movies']);
    $allowTabSeries = ((int)($row['allow_tab_series'] ?? ($allowSeries ? 1 : 0)) === 1) && !empty($profile['allow_tab_series']);
    $allowTabKids = ((int)($row['allow_tab_kids'] ?? 1) === 1) && !empty($profile['allow_tab_kids']);
    $allowTabAnime = ((int)($row['allow_tab_anime'] ?? 1) === 1) && !empty($profile['allow_tab_anime']);
    $allowTabNovelas = ((int)($row['allow_tab_novelas'] ?? ($row['allow_tab_series'] ?? 1)) === 1) && !empty($profile['allow_tab_novelas']);
    $allowTabEsportes = ((int)($row['allow_tab_esportes'] ?? 1) === 1) && !empty($profile['allow_tab_esportes']);

    json_out([
        'status' => 'ok',
        'mac' => $macDb,
        'rules_found' => true,
        'allow_all_live' => $allowLive,
        'allow_all_movies' => $allowMovies,
        'allow_all_series' => $allowSeries,
        'allow_tab_movies' => $allowTabMovies,
        'allow_tab_series' => $allowTabSeries,
        'allow_tab_kids' => $allowTabKids,
        'allow_tab_anime' => $allowTabAnime,
        'allow_tab_novelas' => $allowTabNovelas,
        'allow_tab_esportes' => $allowTabEsportes,
        'allow_tv' => !empty($profile['allow_tv']),
        'allow_mobile' => !empty($profile['allow_mobile']),
        'device_type' => $deviceType,
        'blocked_live_ids' => (!$contentLive || $allowLive) ? [] : csv_to_array($row['blocked_live_ids'] ?? ''),
        'blocked_movie_ids' => (!$contentMovies || $allowMovies) ? [] : csv_to_array($row['blocked_movie_ids'] ?? ''),
        'blocked_series_ids' => (!$contentSeries || $allowSeries) ? [] : csv_to_array($row['blocked_series_ids'] ?? ''),
        'blocked_live_categories' => (!$contentLive || $allowLive) ? [] : csv_to_array($row['blocked_live_categories'] ?? ''),
        'blocked_movie_categories' => (!$contentMovies || $allowMovies) ? [] : csv_to_array($row['blocked_movie_categories'] ?? ''),
        'blocked_series_categories' => (!$contentSeries || $allowSeries) ? [] : csv_to_array($row['blocked_series_categories'] ?? ''),
        'updated_at' => (int)($row['updated_at'] ?? 0),
    ]);
} catch (Throwable $e) {
    json_out(['status' => 'erro', 'mac' => $macDb]);
}
