<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>

<?php //include 'visitor_counter.php'; ?>

<?php

//session started
require_once 'session_config_emp.php';

// Database connection details
include_once 'connect.php';

$message = '';
$rememberMe = false;

// Check for forgot password error
if (isset($_GET['forgot_error'])) {
    $message = htmlspecialchars($_GET['forgot_error']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $cnic = $_POST['cnic'];
    $password = $_POST['password'];
    $rememberMe = isset($_POST['remember']) ? true : false;

    // Validate input
    if (empty($cnic) || empty($password)) {
        $message = 'Please fill out both fields.';
    } else {
        // Remove any non-digit characters from CNIC
        $plain_cnic = preg_replace('/[^0-9]/', '', $cnic);
        
        if (!preg_match('/^\d{13}$/', $plain_cnic)) {
            $message = 'CNIC must be exactly 13 digits (can be with or without hyphens).';
        } else {
            // Format CNIC to xxxxx-xxxxxxx-x for database search
            $formatted_cnic = substr($plain_cnic, 0, 5) . '-' . substr($plain_cnic, 5, 7) . '-' . substr($plain_cnic, 12, 1);
            
            // Prepare and bind - search with formatted CNIC
            $stmt = $conn->prepare("SELECT * FROM registrations_emp WHERE cnic = ?");
            $stmt->bind_param("s", $formatted_cnic);

            // Execute and store result
            $stmt->execute();
            $result = $stmt->get_result();

            // Check if employee exists
            if ($result->num_rows > 0) {
                $employee = $result->fetch_assoc();
                
                // Check account status
                if ($employee['status'] == 1) {
                    // Verify password
                    if (password_verify($password, $employee['password'])) {
                        // Update last login time
                        $update_stmt = $conn->prepare("UPDATE registrations_emp SET last_login = NOW() WHERE id = ?");
                        $update_stmt->bind_param("i", $employee['id']);
                        $update_stmt->execute();
                        $update_stmt->close();
                       
					   // Call this after setting session variables
						secureSessionRegeneration();
 
                        // Set session variables
                        $_SESSION['employee_id'] = $employee['id'];
                        $_SESSION['cnic'] = $formatted_cnic;  // Store formatted CNIC
                        $_SESSION['employee_name'] = $employee['full_name']; // Changed from 'name' to 'full_name'
                        $_SESSION['role_id'] = $employee['role_id'];
                        
                        // Set department and designation if they exist
                        if (isset($employee['department'])) {
                            $_SESSION['department'] = $employee['department'];
                        }
                        if (isset($employee['designation'])) {
                            $_SESSION['designation'] = $employee['designation'];
                        }

                        // Remember me functionality
                        if ($rememberMe) {
                            $cookieValue = json_encode([
                                'cnic' => $formatted_cnic,  // Store formatted CNIC in cookie
                                'token' => bin2hex(random_bytes(16))
                            ]);
                            setcookie('remember_employee', $cookieValue, time() + 86400 * 30, "/", "", true, true);
                        }

                        // Redirect to dashboard
                        header("Location: employee_dashboard.php");
                        exit();
                    } else {
                        $message = 'Invalid CNIC or Password.';
                    }
                } else {
                    $message = 'Your account is inactive. Please contact the Database Administrator to activate your account.';
                }
            } else {
                $message = 'Employee not found.';
            }
            $stmt->close();
        }
    }
}

// Auto-login from remember me cookie
if (empty($_SESSION['employee_id']) && isset($_COOKIE['remember_employee'])) {
    $rememberData = json_decode($_COOKIE['remember_employee'], true);
    if (json_last_error() === JSON_ERROR_NONE && isset($rememberData['cnic'])) {
        $cnic = $rememberData['cnic'];
        
        $stmt = $conn->prepare("SELECT * FROM registrations_emp WHERE cnic = ?");
        $stmt->bind_param("s", $cnic);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $employee = $result->fetch_assoc();
            if ($employee['status'] == 1) {
                // Update last login time for auto-login
                $update_stmt = $conn->prepare("UPDATE registrations_emp SET last_login = NOW() WHERE id = ?");
                $update_stmt->bind_param("i", $employee['id']);
                $update_stmt->execute();
                $update_stmt->close();
                
                $_SESSION['employee_id'] = $employee['id'];
                $_SESSION['cnic'] = $cnic;
                $_SESSION['employee_name'] = $employee['full_name'];
                $_SESSION['role_id'] = $employee['role_id'];
                header("Location: employee_dashboard.php");
                exit();
            } else {
                $message = 'Your account is inactive. Please contact the Database Administrator.';
            }
        }
        $stmt->close();
    }
}

//$conn->close();
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Employee Login</title>
    <link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css">
    <style>
        :root {
            --primary: #3498db;
            --primary-dark: #2980b9;
            --secondary: #2c3e50;
            --light: #ecf0f1;
            --dark: #34495e;
            --success: #2ecc71;
            --warning: #f39c12;
            --danger: #e74c3c;
            --gray: #95a5a6;
            --light-gray: #f5f7fa;
            --border-radius: 8px;
            --box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, rgba(52, 152, 219, 0.85), rgba(46, 204, 113, 0.85)),
                        url('images/login_bg.jpg') center/cover no-repeat fixed;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .login-container {
            width: 100%;
            max-width: 450px;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }
        
        .login-header {
            background: var(--secondary);
            color: white;
            padding: 25px 30px;
            text-align: center;
        }
        
        .login-header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .login-header p {
            font-size: 16px;
            opacity: 0.8;
        }
        
        .login-body {
            padding: 30px;
        }
        
        .input-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--secondary);
            font-size: 14px;
        }
        
        .input-group input {
            width: 100%;
            padding: 14px 15px 14px 45px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 15px;
            transition: var(--transition);
        }
        
        .input-group input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
            outline: none;
        }
        
        .input-group i {
            position: absolute;
            left: 15px;
            top: 40px;
            color: var(--gray);
            font-size: 20px;
        }
        
        .options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            font-size: 14px;
        }
        
        .remember-me {
            display: flex;
            align-items: center;
        }
        
        .remember-me input {
            margin-right: 8px;
            accent-color: var(--primary);
        }
        
        .forgot-password {
            color: var(--primary);
            text-decoration: none;
            transition: var(--transition);
        }
        
        .forgot-password:hover {
            text-decoration: underline;
        }
        
        .btn {
            padding: 14px;
            border: none;
            border-radius: var(--border-radius);
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn-login {
            background: var(--primary);
            color: white;
            width: 100%;
            margin-bottom: 15px;
        }
        
        .btn-login:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
        }
        
        .btn-secondary {
            background: var(--light-gray);
            color: var(--secondary);
            border: 1px solid #ddd;
            flex: 1;
            margin-right: 10px;
        }
        
        .btn-secondary:hover {
            background: #eaeef2;
        }
        
        .btn-danger {
            background: var(--light-gray);
            color: var(--danger);
            border: 1px solid #ddd;
            flex: 1;
        }
        
        .btn-danger:hover {
            background: #fdecea;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .register-link {
            text-align: center;
            font-size: 15px;
            color: var(--secondary);
        }
        
        .register-link a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
            transition: var(--transition);
        }
        
        .register-link a:hover {
            text-decoration: underline;
        }
        
        .notification {
            padding: 12px 15px;
            margin-bottom: 20px;
            border-radius: var(--border-radius);
            background: #fdecea;
            color: var(--danger);
            font-size: 14px;
            display: none;
            border-left: 4px solid var(--danger);
        }
        
        .notification.success {
            background: #eafaf1;
            color: var(--success);
            border-left-color: var(--success);
        }
        
        .notification.info {
            background: #e8f4fd;
            color: var(--primary);
            border-left-color: var(--primary);
        }
        
        .password-strength {
            margin-top: 5px;
            font-size: 12px;
            display: none;
        }
        
        .password-strength.weak {
            color: var(--danger);
        }
        
        .password-strength.medium {
            color: var(--warning);
        }
        
        .password-strength.strong {
            color: var(--success);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        
        .shake {
            animation: shake 0.5s;
        }
        
        @media (max-width: 480px) {
            .login-container {
                margin: 0;
            }
            
            .login-body {
                padding: 25px;
            }
            
            .options {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .btn-secondary, .btn-danger {
                margin-right: 0;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
    
    <?php include 'visitor_counter.php'; ?>  <!-- ✅ HERE, inside body, after all PHP logic -->

    <div class="login-container">
        <div class="login-header">
            <h1><i class='bx bxs-user header-icon'></i> <strong>Employee Portal</strong></h1>
            <p>Login with your CNIC number</p>
        </div>
        
        <div class="login-body">
            <div id="notification" class="notification"></div>
            
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return validateForm()">
            
                <!-- ✅ ADD CSRF TOKEN HERE -->
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
    
                <div class="input-group">
                    <label for="cnic">CNIC Number</label>
                    <i class='bx bx-id-card'></i>
                    <input type="text" name="cnic" id="cnic" placeholder="Enter 13 digits CNIC only." 
                           required maxlength="15" oninput="formatCnic()"
                           value="<?php 
                                if (isset($_COOKIE['remember_employee'])) {
                                    $cookieData = json_decode($_COOKIE['remember_employee'], true);
                                    if (json_last_error() === JSON_ERROR_NONE && isset($cookieData['cnic'])) {
                                        echo htmlspecialchars($cookieData['cnic']);
                                    }
                                }
                           ?>">
                </div>
                
                <div class="input-group">
                    <label for="password">Password</label>
                    <i class='bx bx-lock-alt'></i>
                    <input type="password" name="password" id="password" placeholder="Enter your password" required>
                    <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('password')" style="left: auto; right: 15px; cursor: pointer;"></i>
                </div>
                
                <div class="options">
                    <div class="remember-me">
                        <input type="checkbox" name="remember" id="remember" <?php echo $rememberMe ? 'checked' : ''; ?>>
                        <label for="remember">Remember me</label>
                    </div>
                    <a href="#" id="forgot-password-link">Forgot Password?</a>
                </div>
                
                <script>
                    document.getElementById('forgot-password-link').addEventListener('click', function(e) {
                        e.preventDefault();
                        var cnic = document.getElementById('cnic').value.trim();
                        
                        if (cnic === '') {
                            alert('Please enter your CNIC first.');
                            return;
                        }
                        
                        // Remove hyphens and validate CNIC format
                        var plainCnic = cnic.replace(/\D/g, '');
                        if (!/^\d{13}$/.test(plainCnic)) {
                            alert('Please enter a valid 13-digit CNIC first.');
                            return;
                        }
                        
                        // Format CNIC for the query string
                        var formattedCnic = plainCnic.substring(0, 5) + '-' + plainCnic.substring(5, 12) + '-' + plainCnic.substring(12, 13);
                        
                        // Redirect to forgot password page with CNIC in query string
                        window.location.href = 'forgot_password_emp.php?cnic=' + encodeURIComponent(formattedCnic);
                    });
                </script>
                
                <button type="submit" class="btn btn-login">
                    <i class='bx bx-log-in' style="margin-right: 8px;"></i> Login
                </button>
                
                <div class="button-group">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        <i class='bx bx-reset' style="margin-right: 8px;"></i> Reset
                    </button>
                    <button type="button" class="btn btn-danger" onclick="cancelRegistration()">
                        <i class='bx bx-x' style="margin-right: 8px;"></i> Cancel
                    </button>
                </div>
                
                <div class="register-link">
                    New employee OR Don't have an Account? <a href="register_emp.php">Register here</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        function resetForm() {
            document.querySelector('form').reset();
            document.getElementById('notification').style.display = 'none';
            document.getElementById('cnic').style.borderColor = '';
        }

        function cancelRegistration() {
            if (confirm('Are you sure you want to cancel?')) {
                window.location.href = 'index.php';
            }
        }
        
        // Show message if exists
        window.onload = function() {
            <?php if (!empty($message)): ?>
                showNotification('<?php echo $message; ?>', 'error');
            <?php endif; ?>
            
            // Auto-focus on CNIC field
            document.getElementById('cnic').focus();
            
            // Format CNIC on page load if there's a value
            var cnicInput = document.getElementById('cnic');
            if (cnicInput.value) {
                formatCnic();
            }
        };

        function showNotification(message, type = 'error') {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification';
            
            if (type === 'success') {
                notification.classList.add('success');
            } else if (type === 'info') {
                notification.classList.add('info');
            }
            
            notification.style.display = 'block';
            
            // Hide after 5 seconds
            setTimeout(() => {
                notification.style.display = 'none';
            }, 5000);
        }

        function togglePasswordVisibility(fieldId) {
            var field = document.getElementById(fieldId);
            var icon = field.nextElementSibling;
            if (field.type === "password") {
                field.type = "text";
                icon.classList.remove('bx-show');
                icon.classList.add('bx-hide');
            } else {
                field.type = "password";
                icon.classList.remove('bx-hide');
                icon.classList.add('bx-show');
            }
        }

        function formatCnic() {
            var cnicInput = document.getElementById('cnic');
            var value = cnicInput.value;
            
            // Get cursor position before formatting
            var cursorPos = cnicInput.selectionStart;
            
            // Remove all non-digit characters
            var digits = value.replace(/\D/g, '');
            
            // Format as user types
            var formatted = '';
            if (digits.length > 0) {
                if (digits.length <= 5) {
                    formatted = digits;
                } else if (digits.length <= 12) {
                    formatted = digits.substring(0, 5) + '-' + digits.substring(5);
                } else {
                    formatted = digits.substring(0, 5) + '-' + digits.substring(5, 12) + '-' + digits.substring(12, 13);
                }
            }
            
            // Update the input value
            cnicInput.value = formatted;
            
            // Simple cursor positioning - if we added a hyphen, move cursor forward
            var oldLength = value.length;
            var newLength = formatted.length;
            
            if (newLength > oldLength && cursorPos >= 5 && digits.length > 5) {
                // We added a hyphen at position 5, move cursor forward
                cursorPos++;
            }
            if (newLength > oldLength && cursorPos >= 13 && digits.length > 12) {
                // We added a hyphen at position 13, move cursor forward
                cursorPos++;
            }
            
            // Set cursor position
            setTimeout(function() {
                cnicInput.setSelectionRange(cursorPos, cursorPos);
            }, 0);
            
            // Add visual feedback for valid/invalid CNIC
            if (digits.length === 13) {
                cnicInput.style.borderColor = 'var(--success)';
            } else {
                cnicInput.style.borderColor = '';
            }
        }

        function validateForm() {
            var cnic = document.getElementById('cnic').value;
            var password = document.getElementById('password').value;
            var isValid = true;

            // Remove hyphens for validation
            var plainCnic = cnic.replace(/\D/g, '');
            
            if (plainCnic === '') {
                showNotification('Please enter your CNIC number');
                document.getElementById('cnic').classList.add('shake');
                setTimeout(() => {
                    document.getElementById('cnic').classList.remove('shake');
                }, 500);
                isValid = false;
            } else if (!/^\d{13}$/.test(plainCnic)) {
                showNotification('CNIC must be exactly 13 digits (can be with or without hyphens)');
                document.getElementById('cnic').classList.add('shake');
                setTimeout(() => {
                    document.getElementById('cnic').classList.remove('shake');
                }, 500);
                isValid = false;
            }

            if (password === '') {
                showNotification('Please enter your password');
                document.getElementById('password').classList.add('shake');
                setTimeout(() => {
                    document.getElementById('password').classList.remove('shake');
                }, 500);
                isValid = false;
            }

            // Update the CNIC field value to plain format before submission
            if (isValid) {
                document.getElementById('cnic').value = plainCnic;
            }

            return isValid;
        }
    </script>
</body>
</html>
<?php $conn->close(); ?>  <!-- ✅ safest place, nothing needs $conn after this -->
