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

try {
   $db = new PDO('sqlite:' . dirname(__DIR__) . '/ibo_panel.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Crear tabla users si no existe (simplificado)
    $db->exec("CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL UNIQUE,
        password TEXT NOT NULL,
        admin BOOLEAN NOT NULL DEFAULT 0,
        dealer BOOLEAN NOT NULL DEFAULT 0,
        balance REAL NOT NULL DEFAULT 0
    )");

    
    // Leer JSON raw input
    $inputJSON = file_get_contents('php://input');
    $input = json_decode($inputJSON, true);

    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';

    $stmt = $db->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();

    $user = $stmt->fetch(PDO::FETCH_ASSOC);

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

        echo json_encode(['success' => true, 'redirect' => 'dns.php']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Usuario o contraseña inválidos']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error en la base de datos: ' . $e->getMessage()]);
}
?>
