<?php
session_start();
$helper = array_keys($_SESSION);
foreach ($helper as $key){
   unset($_SESSION[$key]);
}


// Include configuration
require_once __DIR__ . '/config/config.php';

// Include the Database, User, and Logger classes
require_once __DIR__ . '/classes/Database.php';
require_once __DIR__ . '/classes/User.php';
require_once __DIR__ . '/classes/Logger.php';
require_once __DIR__ . '/classes/SystemSettings.php';

// Create a new database connection
$database = new Database();
$conn = $database->getConnection();

// Initialize the User class
$user = new User($conn);
$systemSettings = new SystemSettings();

// Initialize Logger (will be updated with user info after successful login)
$logger = new Logger($conn);

$error = isset($_GET['maintenance'])
    ? 'Maintenance mode is active. Only administrators, controllers, and users from the selected branch can sign in.'
    : '';
$maintenanceDenied = false;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    try {
        $loggedInUser = $user->login($username, $password);

        if ($loggedInUser && !$systemSettings->maintenanceAccessAllowed($loggedInUser['role'], $loggedInUser['branch_id'] ?? null)) {
            $maintenanceDenied = true;
            $logger->setUser($loggedInUser['user_id'], $loggedInUser['username'], $loggedInUser['role']);
            $logger->logAuth('LOGIN', false, 'Login blocked by maintenance mode for branch ID: ' . (string)($loggedInUser['branch_id'] ?? 'none'));
            $error = 'Maintenance mode is active. Your branch is temporarily unavailable.';
            $loggedInUser = false;
        }

        if ($loggedInUser) {
            // Set session variables
            $_SESSION['user_id'] = $loggedInUser['user_id'];
            $_SESSION['username'] = $loggedInUser['username'];
            $_SESSION['role'] = $loggedInUser['role'];
            $_SESSION['branch_id'] = $loggedInUser['branch_id'] ?? null;
            $_SESSION['terminal_id'] = $loggedInUser['terminal_id'] ?? null;

            // Update logger with user information
            $logger->setUser($loggedInUser['user_id'], $loggedInUser['username'], $loggedInUser['role']);

            // Log successful login
            $logger->logAuth('LOGIN', true, "User logged in from IP: " . $_SERVER['REMOTE_ADDR']);

            // Debugging: Print session variables
            error_log('Login successful. Session variables set:');
            error_log('user_id: ' . $_SESSION['user_id']);
            error_log('username: ' . $_SESSION['username']);
            error_log('role: ' . $_SESSION['role']);

            // Redirect based on user role
            switch ($_SESSION['role']) {
                case 'admin':
                    header("Location: " . BASE_URL . "/views/dashboard/admin.php");
                    break;
                case 'warehouse':
                    header("Location: " . BASE_URL . "/views/dashboard/warehouse.php");
                    break;
                case 'branch':
                    header("Location: " . BASE_URL . "/views/dashboard/branch.php");
                    break;
                case 'sales':
                    header("Location: " . BASE_URL . "/views/dashboard/assistant.php");
                    break;
                default:
                    header("Location: " . BASE_URL . "/index.php");
                    break;
            }
            exit();
        } elseif (!$maintenanceDenied) {
            // Log failed login attempt
            $logger->logAuth('LOGIN', false, "Failed login attempt for username: {$username} from IP: " . $_SERVER['REMOTE_ADDR']);

            error_log('Login failed for username: ' . $username);
            $error = "Invalid username or password.";
        }
    } catch (Exception $e) {
        error_log("Login error: " . $e->getMessage());
        $error = "An error occurred during login.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        .card {
            width: 100%;
            max-width: 400px;
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>
    <div class="card">
        <div class="card-header">
            <h3 class="text-center">Login</h3>
        </div>
        <div class="card-body">
            <?php if ($error): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>
            <form method="POST" action="#">
                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" name="username" id="username" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" name="password" id="password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary btn-block mt-3">Login</button>
            </form>
        </div>
    </div>
</body>
</html>
