<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
session_start();

try {
    // Ruta a la base de datos
    $dbPath = __DIR__ . '/ibo_panel.db';
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Crear todas las tablas necesarias
    $createTablesQuery = "
        CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL UNIQUE,
    password TEXT NOT NULL,
    admin INTEGER DEFAULT 0,
    dealer INTEGER DEFAULT 0,
    balance INTEGER DEFAULT 0
);
        CREATE TABLE IF NOT EXISTS themes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            theme_id TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS sports (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            header_n TEXT,
            border_c TEXT,
            background_c TEXT,
            text_c TEXT,
            days TEXT,
            api TEXT
        );
        CREATE TABLE IF NOT EXISTS settings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            note_title TEXT NOT NULL,
            note_content TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS playlist (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            dns_id INTEGER,
            mac_address TEXT NOT NULL,
            username TEXT NOT NULL,
            password TEXT NOT NULL,
            pin TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS logintheme (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            themelog TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS dns (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            url TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS ads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title VARCHAR(100),
            url TEXT
        );
        CREATE TABLE IF NOT EXISTS ad_type (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ad_type TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS adsstatus (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            adstype TEXT
        );
        CREATE TABLE IF NOT EXISTS ibo (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            mac_address VARCHAR(100),
            username VARCHAR(100),
            password VARCHAR(100),
            expire_date VARCHAR(100),
            url VARCHAR(100),
            title VARCHAR(100),
            created_at VARCHAR(100),
            access_count INTEGER DEFAULT 0
        );
    ";
    $db->exec($createTablesQuery);

    // Insertar settings default si no existe
    $settingsCount = $db->query("SELECT COUNT(*) FROM settings")->fetchColumn();
    if ($settingsCount == 0) {
        $db->exec("INSERT INTO settings (note_title, note_content) VALUES ('Rgvip', '+593980649398')");
    }

    // Insertar tema default si no existe
    $themesCount = $db->query("SELECT COUNT(*) FROM themes")->fetchColumn();
    if ($themesCount == 0) {
        $db->exec("INSERT INTO themes (theme_id) VALUES ('theme_1')");
    }

    // Crear usuario admin si no hay ningún usuario
$userCount = $db->query("SELECT COUNT(*) FROM users")->fetchColumn();
if ($userCount == 0) {
    $adminPass = password_hash('admin', PASSWORD_DEFAULT);
    $stmt = $db->prepare("INSERT INTO users (id, username, password, admin, dealer, balance) VALUES (?, ?, ?, 1, 0, 0)");
    $stmt->execute([1, 'admin', $adminPass]);
}

    // Procesar login (espera método POST con username y password)
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        if ($username === '' || $password === '') {
            echo json_encode(['success' => false, 'message' => 'Usuario y contraseña son requeridos']);
            exit;
        }

        $stmt = $db->prepare("SELECT * FROM users WHERE username = :username");
        $stmt->execute([':username' => $username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['is_admin'] = (bool)$user['admin'];
            $_SESSION['is_dealer'] = (bool)$user['dealer'];

            echo json_encode(['success' => true, 'message' => 'Login exitoso']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Credenciales inválidas']);
        }
        exit;
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error de base de datos: ' . $e->getMessage()]);
    exit;
}
