<?php
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if ($request_uri === '/logout') {
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
    header('Location: /login');
    exit;
}

if (isset($_SESSION['user_id'])) {
    $role = $_SESSION['role'] ?? 'owner';
    header('Location: ' . ($role === 'seller' ? '/seller/recursos' : '/inicio'));
    exit;
}

$error = '';

// Email + contraseña — para sellers y staff (no owners, ellos usan Google)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db    = DB::connect();
    $email = trim($_POST['email'] ?? '');
    $pass  = $_POST['password'] ?? '';

    if ($email !== '' && $pass !== '') {
        $stmt = $db->prepare("SELECT * FROM users WHERE email = :e LIMIT 1");
        $stmt->execute([':e' => $email]);
        $user = $stmt->fetch();

        if ($user && password_verify($pass, $user['password_hash'])) {
            session_regenerate_id(true);
            $_SESSION = [];
            $_SESSION['user_id']   = $user['id'];
            $_SESSION['tenant_id'] = $user['tenant_id'];
            $_SESSION['role']      = $user['role'];
            $_SESSION['user_name']  = $user['name'] ?? '';
            $_SESSION['user_email'] = $user['email'] ?? $email;
            if (!empty($user['seller_profile_id'])) {
                $_SESSION['seller_profile_id'] = $user['seller_profile_id'];
            }
            header('Location: ' . ($user['role'] === 'seller' ? '/seller/recursos' : '/inicio'));
            exit;
        }
        $error = 'Email o contraseña incorrectos.';
    } else {
        $error = 'Completá los dos campos.';
    }
}

require_once dirname(__DIR__) . '/views/login.php';
