<?php
session_start();

require_once __DIR__ . '/../config/database.php';

class AuthController {

    private $conn;

    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            die("Error de conexión: " . $this->conn->connect_error);
        }
    }

    public function login($username, $password) {
        $stmt = $this->conn->prepare("SELECT id, password, role FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            if (password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['role'] = $user['role'];

                $host = $_SERVER['HTTP_HOST'];                $uri = rtrim(dirname(dirname($_SERVER['PHP_SELF'])), '/');                if ($user['role'] === 'admin') {                    header("Location: https://$host$uri/views/admin/dashboard.php");                } else {                    header("Location: https://$host$uri/views/pos/index.php");                }                exit();
            } else {
                // Contraseña incorrecta
                header("Location: ../../views/auth/login.php?error=1");
        exit();
            }
        } else {
            // Usuario no encontrado
            header("Location: ../../views/auth/login.php?error=1");
            exit();
        }
    }
    public function logout() {
        session_start();
        session_unset();
        session_destroy();
        header("Location: ../../views/auth/login.php");
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $authController = new AuthController();
    if ($_POST['action'] === 'login') {
        $authController->login($_POST['username'], $_POST['password']);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    if ($_GET['action'] === 'logout') {
        $authController = new AuthController();
        $authController->logout();
    }
}
?>