<?php
/**
 * WIMAS - Secure Login Page (App Theme)
 * Location: /login.php
 */
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

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

// Redirect to dashboard if already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Escape username to prevent SQL injection
    $username = $db->escape($_POST['username']);
    
    // Do NOT escape the password, password_verify needs the exact raw input
    $password = $_POST['password']; 

    // Fetch user by username only using direct values
    $sql = "SELECT * FROM TBL_USERS WHERE USERNAME = '$username' AND STATUS = 'ACTIVE'";
    $result = $db->query($sql);

    if (mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result);
        
        // Securely verify the hashed password
        if (password_verify($password, $user['PASSWORD'])) {
            
            $user_id = $user['USER_ID'];
            
            // Update Last Login Time using direct values
            $update_login_sql = "UPDATE TBL_USERS SET LAST_LOGIN = CURRENT_TIMESTAMP WHERE USER_ID = $user_id";
            $db->query($update_login_sql);

           // Set secure session variables
            $_SESSION['user_id'] = $user['USER_ID'];
            $_SESSION['username'] = $user['USERNAME'];
            $_SESSION['full_name'] = $user['FULL_NAME'];
            
            // Fetch ALL assigned roles AND calculate their Highest Priority
            $role_query = $db->query("SELECT ur.ROLE_ID, r.ROLE_PRIORITY 
                                      FROM TBL_USER_ROLES ur 
                                      JOIN TBL_ROLES r ON ur.ROLE_ID = r.ROLE_ID 
                                      WHERE ur.USER_ID = " . $user['USER_ID']);
            $roles = [];
            $best_priority = 99; // Default to lowest
            
            while($r = mysqli_fetch_assoc($role_query)) {
                $roles[] = (int)$r['ROLE_ID'];
                if ((int)$r['ROLE_PRIORITY'] < $best_priority) {
                    $best_priority = (int)$r['ROLE_PRIORITY'];
                }
            }
            $_SESSION['all_role_ids'] = $roles; 
            $_SESSION['role_priority'] = $best_priority; // THE NEW GATEKEEPER VARIABLE
            
            header("Location: index.php");
            exit;
        } else {
            $error_message = 'Invalid password. Please try again.';
        }
    } else {
        $error_message = 'Invalid username or account is disabled.';
    }
}

// 1. Load the customized SLCMC Auth Header
include __DIR__ . '/includes/auth_header.php';
?>

<!-- Optional Language Toggle -->
<div class="lang-toggle">English <span><i class="fas fa-language"></i></span></div>

<!-- 2. The Form UI -->
<div class="login-card">
    <div class="logo-wrapper">
        <img src="assets/img/slmc-logo.png" alt="SLCMC Logo">
    </div>
    
    <h2>Login</h2>
    <p class="subtitle">Enter your credentials to access the Lakhra Coal Mining Portal</p>

    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger shadow-sm border-0 py-2 mb-3 text-center" style="font-size: 0.9rem; border-radius: 8px;">
            <i class="fas fa-exclamation-circle mr-1"></i> <?php echo $error_message; ?>
        </div>
    <?php endif; ?>

    <form action="login.php" method="post">
        
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text"><i class="fas fa-user"></i></span>
            </div>
            <input type="text" name="username" class="form-control" placeholder="Username / Miner ID" required autofocus autocomplete="off">
        </div>

        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text"><i class="fas fa-lock"></i></span>
            </div>
            <input type="password" id="password_input" name="password" class="form-control" placeholder="Password" required>
            <div class="input-group-append">
                <span class="input-group-text" style="cursor: pointer;" onclick="togglePassword()">
                    <i class="fas fa-eye" id="eye_icon"></i>
                </span>
            </div>
        </div>

        <a href="#" class="forgot-pass">Forgot Password?</a>

        <button type="submit" class="btn-orange">Sign In</button>
    </form>
</div>

<!-- Password Visibility Script -->
<script>
function togglePassword() {
    var pwdInput = document.getElementById('password_input');
    var eyeIcon = document.getElementById('eye_icon');
    
    if (pwdInput.type === 'password') {
        pwdInput.type = 'text';
        eyeIcon.classList.remove('fa-eye');
        eyeIcon.classList.add('fa-eye-slash');
    } else {
        pwdInput.type = 'password';
        eyeIcon.classList.remove('fa-eye-slash');
        eyeIcon.classList.add('fa-eye');
    }
}
</script>

<!-- 3. Load the Auth Footer (Scripts) -->
<?php include __DIR__ . '/includes/auth_footer.php'; ?>