<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(32767);
session_start();

$jsondata111 = file_get_contents("./includes/ansibo.json");
$json111 = json_decode($jsondata111, true);
$col1 = $json111["info"];
$col2 = $col1["aa"];

$db = new SQLite3("api/.ansdb.db");
$db2 = new SQLite3("api/.anspanel.db");

$res_login = $db2->query("SELECT * FROM USERS WHERE id='1'");
$row_login = $res_login->fetchArray();
$name_login = "MY FULL";
$logo_login = $row_login["LOGO"];
$corp_login = $row_login["CORP"];
$db2->close();

if (isset($_POST["login"])) {
    $store_id = $_POST["store"] ?? '';
    $mac = strtoupper($_POST['mac']);
    $macRegex = '/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}.[0-9a-fA-F]{4}.[0-9a-fA-F]{4})$/';
    
    if(preg_match($macRegex, $mac)){
        $sql_check = "SELECT COUNT(*) as count from ibo where mac_address='$mac' AND store_type = 2";
        $count = $db->querySingle($sql_check);
        
        $expire = date('Y-m-d', strtotime('+7 days'));
        $limited = false;

        if($count == 0){
            if($store_id){
                $dbUsers = new SQLite3("./api/.anspanel.db");
                $macCount = $dbUsers->querySingle("SELECT mac_amount FROM USERS WHERE id = '$store_id' ");
                $dbUsers->close();
                
                $currentCount = $db->querySingle("SELECT COUNT(*) FROM ibo WHERE id_user = '$store_id' AND active = 1 AND expire_date > date('now')");
                $limited = $currentCount >= $macCount;
            }
            if(!$limited){
                $db->exec("INSERT INTO ibo (title, mac_address, expire_date, id_user, store_type) VALUES ('Playlist $mac', '$mac', '$expire', '$store_id' ,2)");
            }
        }
        
        $res = $db->query("SELECT * from ibo where mac_address='$mac' AND store_type = 2");
        $userData = $res->fetchArray(SQLITE3_ASSOC);

        if (!$userData) {
            $error = $limited ? "Limite de MACs excedidos para a loja" : "Erro. Tente novamente";
        } else {
            $_SESSION["admin"] = false;
            $_SESSION["id"] = $userData['id'];
            $_SESSION["mac_address"] = $userData['mac_address'];
            header("Location: playlists_mac.php");
            exit;
        }
    } else {
        $error = "Endereço MAC Inválido";
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Painel do Usuário | Ultra MAC</title>
    
    <style>
        :root {
            --bg-deep: #020617;
            --card-bg: #0f172a;
            --accent: #3b82f6;
            --accent-glow: rgba(59, 130, 246, 0.5);
            --text-main: #f8fafc;
            --text-muted: #94a3b8;
            --warning: #f59e0b;
        }

        body {
            background: radial-gradient(circle at top, #1e293b 0%, var(--bg-deep) 100%);
            color: var(--text-main);
            font-family: 'Nunito', sans-serif;
            height: 100vh;
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        #container {
            width: 100%;
            max-width: 450px;
            padding: 20px;
        }

        .acceptContainer {
            background: var(--card-bg);
            border: 1px solid #1e293b;
            border-radius: 24px;
            padding: 40px 30px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            text-align: center;
            backdrop-filter: blur(10px);
        }

        .img-mac-login {
            max-width: 120px;
            margin-bottom: 20px;
            filter: drop-shadow(0 0 10px var(--accent-glow));
        }

        h1 {
            font-size: 1.5rem;
            font-weight: 800;
            letter-spacing: 2px;
            margin-bottom: 10px;
            color: var(--text-main);
        }

        .sub-text {
            color: var(--text-muted);
            font-size: 0.9rem;
            margin-bottom: 30px;
        }

        .formDiv {
            text-align: left;
            margin-bottom: 25px;
        }

        .formDiv p {
            font-size: 0.75rem;
            font-weight: 700;
            color: var(--accent);
            margin-left: 5px;
            text-transform: uppercase;
        }

        .form-control-ultra {
            background: #070e1b !important;
            border: 1px solid #1e293b !important;
            color: #fff !important;
            border-radius: 12px;
            padding: 15px;
            width: 100%;
            box-sizing: border-box;
            font-size: 1.1rem;
            text-align: center;
            letter-spacing: 2px;
            transition: all 0.3s;
        }

        .form-control-ultra:focus {
            outline: none;
            border-color: var(--accent) !important;
            box-shadow: 0 0 15px var(--accent-glow);
        }

        .dacceptBtn {
            background: linear-gradient(135deg, var(--accent), #2563eb);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 12px;
            width: 100%;
            font-weight: 800;
            font-size: 1rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            text-transform: uppercase;
        }

        .dacceptBtn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(37, 99, 235, 0.4);
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid #ef4444;
            color: #ef4444;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 0.85rem;
        }

        .info-footer {
            margin-top: 30px;
            font-size: 0.7rem;
            color: var(--text-muted);
        }

        .info-footer i { color: var(--warning); }
    </style>
</head>

<body>
    <div id="container">
        <div class="acceptContainer">
            <form method="POST">
                <img class="img-mac-login" src="<?php echo $logo_login; ?>"/>
                
                <h1>PAINEL DO MAC</h1>
                <p class="sub-text">Acesso exclusivo via endereço físico do dispositivo</p>

                <?php if(isset($error)): ?>
                    <div class="alert-error"><?php echo $error; ?></div>
                <?php endif; ?>

                <div class="formContainer">
                    <div class="formDiv">
                        <p>Endereço MAC do Dispositivo</p>
                        <input type="text" class="form-control-ultra" id="mac" name="mac" placeholder="00:00:00:00:00:00" maxlength='17' required autofocus autocomplete="off"/>
                    </div>
                    
                    <button class="dacceptBtn" name="login" type="submit">ACESSAR PAINEL</button>
                    
                    <div class="info-footer">
                        <p>IP: <i><?php echo real_ip(); ?></i></p>
                        <p>SINCRONIZADO EM: <i><?php echo date("d/m/Y H:i:s"); ?></i></p>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Formata o MAC automaticamente enquanto digita
        const element = document.getElementById("mac");
        element.addEventListener('input', function(e) {
            let cursor = e.target.selectionStart;
            let value = e.target.value.toUpperCase().replace(/[^0-9A-F]/g, '');
            let formatted = "";
            for(let i = 0; i < value.length && i < 12; i++) {
                if(i > 0 && i % 2 === 0) formatted += ":";
                formatted += value[i];
            }
            element.value = formatted;
        });
    </script>
</body>
</html>

<?php
function real_ip() {
    $ip = $_SERVER["REMOTE_ADDR"] ?? "0.0.0.0";
    if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    return htmlspecialchars($ip, ENT_QUOTES, "UTF-8");
}
?>