<?php
/**
 * Enterprise HRM ERP System - Login Page
 * Features:
 * - Email/Username login
 * - Password hashing (bcrypt)
 * - Role-based redirect
 * - Session handling
 */

require_once __DIR__ . '/includes/init.php';

// Redirect if already logged in
if (isLoggedIn()) {
    // Redirect based on role
    $redirectUrl = getRoleBasedRedirect();
    header('Location: ' . $redirectUrl);
    exit;
}

$error = null;
$success = null;

// Handle logout
if (isset($_GET['logout'])) {
    logout();
    $success = 'You have been logged out successfully.';
}

// Handle cancel branch selection
if (isset($_GET['cancel'])) {
    startSession();
    unset($_SESSION['temp_user_id']);
    unset($_SESSION['temp_username']);
    unset($_SESSION['temp_user_sites']);
    unset($_SESSION['temp_role_code']);
    unset($_SESSION['temp_full_name']);
    unset($_SESSION['temp_permissions']);
    $showBranchSelection = false;
    $userSites = [];
}

// Handle branch selection (if user has multiple branches)
$showBranchSelection = false;
$userSites = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['selected_site_id'])) {
    // User selected a branch
    $username = sanitize($_SESSION['temp_username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (!empty($password)) {
        // Re-verify password and complete login with selected branch
        $result = login($username, $password);
        if ($result['success']) {
            // Get role-based redirect URL
            $redirectUrl = getRoleBasedRedirect();
            
            // Check if there's a redirect_after_login (from requireLogin)
            if (isset($_SESSION['redirect_after_login'])) {
                $redirectUrl = $_SESSION['redirect_after_login'];
                unset($_SESSION['redirect_after_login']);
            }
            
            header('Location: ' . $redirectUrl);
            exit;
        } else {
            $error = $result['message'];
            // Reload branch selection
            if (isset($_SESSION['temp_user_sites'])) {
                $showBranchSelection = true;
                $userSites = $_SESSION['temp_user_sites'];
            }
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Initial login attempt
    $username = sanitize($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = 'Please enter both username/email and password.';
    } else {
        $result = login($username, $password);
        if ($result['success']) {
            // Get role-based redirect URL
            $redirectUrl = getRoleBasedRedirect();
            
            // Check if there's a redirect_after_login (from requireLogin)
            if (isset($_SESSION['redirect_after_login'])) {
                $redirectUrl = $_SESSION['redirect_after_login'];
                unset($_SESSION['redirect_after_login']);
            }
            
            header('Location: ' . $redirectUrl);
            exit;
        } elseif ($result['message'] === 'branch_selection_required' && isset($result['sites'])) {
            // User has multiple branches, show selection
            $showBranchSelection = true;
            $userSites = $result['sites'];
        } else {
            $error = $result['message'];
        }
    }
}

// Check if we need to show branch selection from session
if (!$showBranchSelection && isset($_SESSION['temp_user_sites']) && count($_SESSION['temp_user_sites']) > 1) {
    $showBranchSelection = true;
    $userSites = $_SESSION['temp_user_sites'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo getSetting('SYSTEM_NAME', APP_NAME); ?></title>
    <link rel="stylesheet" href="<?php echo assetUrl('assets/css/style.css'); ?>">
    <style>
        .login-container {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
        }
        .login-box {
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            width: 100%;
            max-width: 420px;
        }
        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .login-header h1 {
            font-size: 28px;
            color: var(--text-primary);
            margin-bottom: 10px;
        }
        .login-header p {
            color: var(--text-secondary);
            font-size: 14px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-primary);
        }
        .form-control {
            width: 100%;
            padding: 12px;
            font-size: 14px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            transition: border-color 0.2s;
            box-sizing: border-box;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }
        .btn-login {
            width: 100%;
            padding: 12px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .btn-login:hover {
            background-color: var(--primary-dark);
        }
        .btn-login:active {
            transform: scale(0.98);
        }
        .alert-error {
            background-color: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            border-left: 4px solid var(--error-color);
        }
        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            border-left: 4px solid #10b981;
        }
        .login-footer {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid var(--border-color);
            color: var(--text-secondary);
            font-size: 12px;
        }
        .password-toggle {
            position: relative;
        }
        .password-toggle-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: var(--text-secondary);
            font-size: 18px;
        }
        .password-toggle-icon:hover {
            color: var(--text-primary);
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-box">
            <div class="login-header">
                <h1><?php echo getSetting('SYSTEM_NAME', APP_NAME); ?></h1>
                <p>Enterprise HRM ERP System</p>
            </div>
            
            <?php if ($error): ?>
            <div class="alert-error">
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
            <div class="alert-success">
                <?php echo htmlspecialchars($success); ?>
            </div>
            <?php endif; ?>
            
            <?php if ($showBranchSelection && !empty($userSites)): ?>
            <!-- Branch Selection Form -->
            <div style="margin-bottom: 20px;">
                <p style="color: var(--text-secondary); margin-bottom: 15px;">
                    <strong><?php echo htmlspecialchars($_SESSION['temp_full_name'] ?? 'User'); ?></strong>, 
                    you have access to multiple branches. Please select a branch to continue:
                </p>
            </div>
            <form method="POST" action="" id="branchForm">
                <input type="hidden" name="username" value="<?php echo htmlspecialchars($_SESSION['temp_username'] ?? ''); ?>">
                
                <div class="form-group">
                    <label class="form-label" for="selected_site_id">Select Branch *</label>
                    <select id="selected_site_id" name="selected_site_id" class="form-control" required autofocus>
                        <option value="">-- Select Branch --</option>
                        <?php foreach ($userSites as $site): ?>
                        <option value="<?php echo $site['site_id']; ?>">
                            <?php echo htmlspecialchars($site['site_name']); ?> 
                            (<?php echo htmlspecialchars($site['site_code']); ?>)
                            <?php if ($site['is_primary'] == 1): ?>
                            - Primary
                            <?php endif; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group password-toggle">
                    <label class="form-label" for="password">Confirm Password *</label>
                    <input type="password" id="password" name="password" class="form-control" 
                           required autocomplete="current-password"
                           placeholder="Enter your password to confirm">
                    <span class="password-toggle-icon" onclick="togglePassword()">👁️</span>
                </div>
                
                <button type="submit" class="btn-login">Continue to Branch</button>
                <a href="?cancel=1" class="btn btn-secondary" style="display: block; text-align: center; margin-top: 10px; text-decoration: none;">Cancel</a>
            </form>
            <?php else: ?>
            <!-- Normal Login Form -->
            <form method="POST" action="" id="loginForm">
                <div class="form-group">
                    <label class="form-label" for="username">Username or Email *</label>
                    <input type="text" id="username" name="username" class="form-control" 
                           required autofocus autocomplete="username"
                           placeholder="Enter your username or email"
                           value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
                </div>
                
                <div class="form-group password-toggle">
                    <label class="form-label" for="password">Password *</label>
                    <input type="password" id="password" name="password" class="form-control" 
                           required autocomplete="current-password"
                           placeholder="Enter your password">
                    <span class="password-toggle-icon" onclick="togglePassword()">👁️</span>
                </div>
                
                <button type="submit" class="btn-login">Login</button>
            </form>
            <?php endif; ?>
            
            <div class="login-footer">
                <p>&copy; <?php echo date('Y'); ?> <?php echo getSetting('SYSTEM_NAME', APP_NAME); ?>. All rights reserved.</p>
            </div>
        </div>
    </div>
    
    <script>
        function togglePassword() {
            const passwordInput = document.getElementById('password');
            const toggleIcon = document.querySelector('.password-toggle-icon');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleIcon.textContent = '🙈';
            } else {
                passwordInput.type = 'password';
                toggleIcon.textContent = '👁️';
            }
        }
        
        // Auto-submit on Enter key
        document.getElementById('loginForm').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.submit();
            }
        });
        
        // Focus on username field if empty
        document.addEventListener('DOMContentLoaded', function() {
            const usernameField = document.getElementById('username');
            if (!usernameField.value) {
                usernameField.focus();
            }
        });
    </script>
</body>
</html>
