<?php
require_once __DIR__ . '/includes/config.php';
require_once 'db.php';
require_once __DIR__ . '/includes/permissions.php';
session_start();

$error      = '';
$timeoutMsg = isset($_GET['timeout'])    ? "Your session expired due to inactivity. Please login again." : '';
$noCompany  = isset($_GET['no_company']) ? "No company assigned to your account. Please contact the administrator." : '';
$noAccess   = isset($_GET['no_access'])  ? "Your account has no module access. Please contact the administrator." : '';

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

    $stmt = $conn->prepare(
        "SELECT id, name, password, role, role_id
         FROM users
         WHERE username = ? AND status = 1"
    );
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id']      = $user['id'];
        $_SESSION['user_name']    = $user['name'];
        $_SESSION['user_role']    = $user['role'];
        $_SESSION['user_role_id'] = $user['role_id'];
        $_SESSION['last_activity'] = time();

        $uid  = (int)$user['id'];
        $role = $user['role'];

        if ($role === 'admin') {
            // Admin: auto-assign first company
            $r = $conn->query("SELECT id FROM company_master ORDER BY id ASC LIMIT 1");
            if ($r && $r->num_rows > 0) {
                $_SESSION['active_company_id'] = (int)$r->fetch_row()[0];
            }
            loadPermissions($conn);
            header("Location: " . getDefaultLandingUrl());
            exit;
        } else {
            // Staff: resolve company assignments
            $r = $conn->query("SELECT company_id FROM user_companies WHERE user_id = $uid ORDER BY company_id ASC");
            $companies = [];
            if ($r) {
                while ($row = $r->fetch_row()) {
                    $companies[] = (int)$row[0];
                }
            }

            if (count($companies) === 0) {
                // Destroy the session we just created and show error
                session_unset();
                session_destroy();
                session_start();
                $error = "No company assigned to your account. Please contact the administrator.";
            } elseif (count($companies) === 1 || $role === 'master_staff') {
                // master_staff: auto-assign first company regardless of how many assigned
                $_SESSION['active_company_id'] = $companies[0];
                loadPermissions($conn);
                header("Location: " . getDefaultLandingUrl());
                exit;
            } else {
                // Multiple companies — let user choose after login
                // permissions loaded after company_select.php sets active_company_id
                header("Location: company_select.php");
                exit;
            }
        }
    } else {
        $error = "Invalid username or password.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Login — SNH Accounts</title>
    <meta name="theme-color" content="#0f172a">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="SNH Accounts">
    <link rel="manifest" href="<?= BASE_URL ?>/manifest.json">
    <link rel="apple-touch-icon" href="<?= BASE_URL ?>/assets/icons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="<?= BASE_URL ?>/assets/icons/favicon-32.png">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
</head>
<body class="login-page">

<div class="login-card">

    <div class="login-logo">
        <div class="login-logo-icon">
            <i class="fas fa-store-alt"></i>
        </div>
        <h2>My ERP</h2>
        <p>Retail Management System</p>
    </div>

    <?php if ($error): ?>
    <div class="alert alert-danger" style="margin-bottom:16px;">
        <i class="fas fa-exclamation-circle"></i>
        <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>
    <?php if ($timeoutMsg): ?>
    <div class="alert alert-warning" style="margin-bottom:16px;">
        <i class="fas fa-clock"></i>
        <?= htmlspecialchars($timeoutMsg) ?>
    </div>
    <?php endif; ?>
    <?php if ($noCompany && !$error): ?>
    <div class="alert alert-warning" style="margin-bottom:16px;">
        <i class="fas fa-building"></i>
        <?= htmlspecialchars($noCompany) ?>
    </div>
    <?php endif; ?>
    <?php if ($noAccess && !$error): ?>
    <div class="alert alert-warning" style="margin-bottom:16px;">
        <i class="fas fa-lock"></i>
        <?= htmlspecialchars($noAccess) ?>
    </div>
    <?php endif; ?>

    <form method="post">

        <div class="form-group">
            <label for="username">Username</label>
            <div style="position:relative;">
                <i class="fas fa-user" style="position:absolute;left:11px;top:50%;transform:translateY(-50%);color:#94a3b8;font-size:13px;"></i>
                <input type="text" id="username" name="username"
                       placeholder="Enter username"
                       style="padding-left:34px;"
                       required autofocus>
            </div>
        </div>

        <div class="form-group">
            <label for="password">Password</label>
            <div style="position:relative;">
                <i class="fas fa-lock" style="position:absolute;left:11px;top:50%;transform:translateY(-50%);color:#94a3b8;font-size:13px;"></i>
                <input type="password" id="password" name="password"
                       placeholder="Enter password"
                       style="padding-left:34px;"
                       required>
            </div>
        </div>

        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;margin-top:8px;padding:11px;">
            <i class="fas fa-sign-in-alt"></i> Sign In
        </button>

    </form>

</div>

</body>
</html>
