<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/includes/api_helpers.php';

$db = gpc_db();
$body = gpc_parse_body();

if (!is_array($body)) {
    gpc_json_out(['status' => false, 'message' => 'invalid_payload']);
    exit;
}

if (!gpc_validate_key(isset($body['app_key_dev']) ? (string) $body['app_key_dev'] : null)) {
    gpc_json_out(['status' => false, 'message' => 'invalid_app_key']);
    exit;
}

$mac = gpc_mac_from_device_id(isset($body['app_device_id']) ? (string) $body['app_device_id'] : null);
$user = trim((string) ($body['username'] ?? ''));
$pass = trim((string) ($body['password'] ?? ''));
$dnsId = (int) ($body['dns_id'] ?? 0);
$cod = trim((string) ($body['codRevenda'] ?? ''));

if (!$mac || $user === '' || $pass === '') {
    gpc_json_out(['status' => false, 'message' => 'missing_fields']);
    exit;
}

$dnsUrl = '';
$resolvedDnsId = 0;
$accessType = 'app_license';
$partnerExpire = null;

// Nova lógica: Priorizar o código enviado (codRevenda) para buscar a DNS
if ($cod !== '') {
    $stmt = $db->prepare('SELECT ds.id, ds.url, ds.status, ds.validity, ds.reseller_id, r.active AS reseller_active, r.validity AS reseller_validity FROM dns_servers ds LEFT JOIN resellers r ON r.id = ds.reseller_id WHERE ds.code = :code LIMIT 1');
    $stmt->execute([':code' => $cod]);
    $dnsRow = $stmt->fetch();

    if (!$dnsRow) {
        gpc_json_out(['status' => false, 'message' => 'Código inválido']);
        exit;
    }

    if (!gpc_dns_row_effectively_active($dnsRow)) {
        if (!empty($dnsRow['reseller_id']) && ((int)($dnsRow['reseller_active'] ?? 0) !== 1 || (!empty($dnsRow['reseller_validity']) && gpc_expired((string)$dnsRow['reseller_validity'])))) {
            gpc_json_out(['status' => false, 'message' => 'Revenda vencida ou bloqueada']);
        } elseif ((int)$dnsRow['status'] !== 1) {
            gpc_json_out(['status' => false, 'message' => 'DNS desativada']);
        } else {
            gpc_json_out(['status' => false, 'message' => 'DNS vencida']);
        }
        exit;
    }

    $dnsUrl = gpc_base_url((string) $dnsRow['url']);
    $resolvedDnsId = (int) $dnsRow['id'];
    $accessType = 'partner_code';
    $partnerExpire = '2099-12-31';
    foreach ([(string)($dnsRow['validity'] ?? ''), (string)($dnsRow['reseller_validity'] ?? '')] as $limitDate) {
        if ($limitDate !== '' && $limitDate < $partnerExpire) { $partnerExpire = $limitDate; }
    }
} elseif ($dnsId > 0) {
    // Fallback para seleção manual de DNS se não houver código
    $stmt = $db->prepare('SELECT url FROM dns_servers WHERE id = :id LIMIT 1');
    $stmt->execute([':id' => $dnsId]);
    $row = $stmt->fetch();
    if ($row) {
        $dnsUrl = gpc_base_url((string) $row['url']);
        $resolvedDnsId = $dnsId;
    }
}

if ($dnsUrl === '') {
    gpc_json_out(['status' => false, 'message' => 'Nenhuma DNS encontrada']);
    exit;
}

$key = gpc_new_device_key();
$keyCreated = date('Y-m-d H:i:s');
$keyExpire = '';

$playlist = $dnsUrl !== ''
    ? rtrim($dnsUrl, '/') . '/get.php?username=' . rawurlencode($user)
        . '&password=' . rawurlencode($pass) . '&type=m3u_plus&output=mpegts'
    : '';

if ($accessType === 'partner_code') {
    // Login via código/parceiro não consome nem renova licença do APP.
    // Ele segue a validade da DNS/parceiro quando preenchida, ou fica sem vencimento operacional.
    $expire = $partnerExpire ?: '2099-12-31';
    $stmt = $db->prepare("SELECT id, device_key, license_type, key_created_at FROM devices WHERE mac_address = :m AND COALESCE(access_type,'app_license') = 'partner_code' AND dns = :d AND username = :u ORDER BY id ASC LIMIT 1");
    $stmt->execute([':m' => $mac, ':d' => $dnsUrl, ':u' => $user]);
    $existing = $stmt->fetch();
} else {
    gpc_auto_register_mac($mac, $key);
    $days = max(1, (int) gpc_setting('auto_register_days', '365'));
    $expire = date('Y-m-d', strtotime('+' . $days . ' days'));
    $stmt = $db->prepare("SELECT id, device_key, license_type, key_created_at FROM devices WHERE mac_address = :m AND COALESCE(access_type,'app_license') = 'app_license' ORDER BY id ASC LIMIT 1");
    $stmt->execute([':m' => $mac]);
    $existing = $stmt->fetch();
}

if ($existing) {
    $key = trim((string)($existing['device_key'] ?? '')) ?: $key;
    $licenseType = (string)($existing['license_type'] ?? ($accessType === 'partner_code' ? 'trial' : 'trial'));
    $keyCreated = trim((string)($existing['key_created_at'] ?? '')) ?: $keyCreated;

    // Proteção profissional: se o MAC já é licença oficial, o auto cadastro do APP
    // não pode reduzir a validade para os dias do teste grátis.
    if ($accessType === 'app_license' && $licenseType !== 'trial') {
        $keepStmt = $db->prepare('SELECT expire_date, key_expire_at FROM devices WHERE id = :id LIMIT 1');
        $keepStmt->execute([':id' => $existing['id']]);
        $keepRow = $keepStmt->fetch() ?: [];
        $expire = (string)($keepRow['expire_date'] ?? $expire);
        $keyExpire = (string)(($keepRow['key_expire_at'] ?? '') ?: $expire);
    } else {
        $keyExpire = $expire;
    }

    $upd = $db->prepare('UPDATE devices SET username=:u, password=:p, dns=:d, playlist_url=:pl,
        expire_date=:e, device_key=:k, license_type=:lt, key_created_at=:kc, key_expire_at=:ke, title=:t, access_type=:a WHERE id=:id');
    $upd->execute([
        ':u' => $user, ':p' => $pass, ':d' => $dnsUrl, ':pl' => $playlist,
        ':e' => $expire, ':k' => $key, ':lt'=>$licenseType, ':kc'=>$keyCreated, ':ke'=>$keyExpire, ':t' => ($accessType === 'partner_code' ? 'Código DNS' : 'GPC'), ':a' => $accessType, ':id' => $existing['id'],
    ]);
} else {
    $ins = $db->prepare('INSERT INTO devices (mac_address, username, password, dns, playlist_url, expire_date, device_key, license_type, key_created_at, key_expire_at, title, access_type)
        VALUES (:m,:u,:p,:d,:pl,:e,:k,:lt,:kc,:ke,:t,:a)');
    $ins->execute([
        ':m' => $mac, ':u' => $user, ':p' => $pass, ':d' => $dnsUrl, ':pl' => $playlist,
        ':e' => $expire, ':k' => $key, ':lt'=>($accessType === 'partner_code' ? 'trial' : 'trial'), ':kc'=>$keyCreated, ':ke'=>$expire, ':t' => ($accessType === 'partner_code' ? 'Código DNS' : 'GPC'), ':a' => $accessType,
    ]);
}

gpc_log_register([
    'mac' => $mac, 'user' => $user, 'pass' => $pass, 'cod' => $cod,
    'dns_id' => $resolvedDnsId, 'dns_url' => $dnsUrl,
]);

gpc_json_out([
    'status' => true,
    'message' => 'registered',
    'mac_address' => $mac,
    'dns_id' => $resolvedDnsId,
]);
