<?php
session_start();
require_once(__DIR__ . '/config/settings.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user = trim($_POST['user']);
    $pass = trim($_POST['pass']);

    try {
        $dsn = "dblib:host={$db_settings['host']}:1433;dbname={$db_settings['name']};charset=UTF8";
        $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Validación MuEmu Estándar
        $stmt = $pdo->prepare("SELECT memb___id, memb_name FROM MEMB_INFO WHERE memb___id = ? AND memb__pwd = ?");
        $stmt->execute([$user, $pass]);
        $account = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($account) {
            $_SESSION['logged_in'] = true;
            $_SESSION['user_id']   = $account['memb___id'];
            $_SESSION['user_name'] = $account['memb_name'];
            header("Location: panel.php"); 
        } else {
            header("Location: index.php?error=fail");
        }
    } catch (Exception $e) {
        header("Location: index.php?error=db");
    }
    exit();
}