<?php
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['eggzie_iboPlayer3']) || !isset($_SESSION['reseller_name'])) { echo json_encode(['success'=>false,'error'=>'Não autenticado']); exit(); }
$reseller_name = $_SESSION['reseller_name'];
$mac = isset($_POST['mac']) ? strtoupper(trim($_POST['mac'])) : '';
if (empty($mac) || !preg_match('/^([0-9A-F]{2}:){7}[0-9A-F]{2}$/', $mac)) { echo json_encode(['success'=>false,'error'=>'MAC inválido']); exit(); }
$db = new SQLite3('../a/.eggziedb.db');
$check = $db->query("SELECT COUNT(*) as c, MAX(expire_date) as last_expire FROM ibo WHERE mac_address = '$mac' AND seller = '$reseller_name'");
$row = $check->fetchArray(SQLITE3_ASSOC);
if ($row['c'] == 0) { echo json_encode(['success'=>false,'error'=>'MAC não encontrado']); exit(); }
$today = date('Y-m-d');
if ($row['last_expire'] >= $today) { echo json_encode(['success'=>false,'error'=>'MAC não está expirado']); exit(); }
$macs_result = $db->query("SELECT macs FROM sub_revenda WHERE usuario = '$reseller_name'");
$macs_row = $macs_result->fetchArray(SQLITE3_ASSOC);
$available_macs = $macs_row ? intval($macs_row['macs']) : 0;
if ($available_macs <= 0) { echo json_encode(['success'=>false,'error'=>'Saldo de MACs insuficiente']); exit(); }
$db->exec('BEGIN IMMEDIATE');
$new_expire = date('Y-m-d', strtotime('+1 year'));
$sql = "UPDATE ibo SET expire_date = '$new_expire', is_test = 0 WHERE mac_address = '$mac' AND seller = '$reseller_name'";
if ($db->exec($sql)) {
    $new_balance = $available_macs - 1;
    $db->exec("UPDATE sub_revenda SET macs = $new_balance WHERE usuario = '$reseller_name'");
    $db->exec('COMMIT');
    echo json_encode(['success'=>true,'message'=>"MAC renovado! Nova validade: ".date('d/m/Y',strtotime($new_expire)).". Saldo: $new_balance MACs."]);
} else { $db->exec('ROLLBACK'); echo json_encode(['success'=>false,'error'=>'Erro ao renovar: '.$db->lastErrorMsg()]); }
?>