<?php
require_once 'config/database.php';

// Handle logout first
if (isset($_GET['logout']) && $_GET['logout'] == '1') {
    // Ensure session is properly destroyed
    if (function_exists('destroySession')) {
        destroySession();
    } else {
        session_destroy();
    }
    $logout_message = 'You have been successfully logged out.';
}

// Check if already logged in (after logout handling)
if (checkAuthentication()) {
    header('Location: index.php');
    exit;
}

// Check for session expiry message
$expired_message = '';
if (isset($_GET['expired']) && $_GET['expired'] == '1') {
    $expired_message = 'Your session has expired. Please log in again.';
}

require_once 'templates/header.php';
?>

<!-- Custom CSS for enhanced login page -->
<style>
    .login-page {
        min-height: 100vh;
        background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
        display: flex;
        justify-content: center;
        align-items: center;
    }
    
    .login-box {
        width: 400px;
        max-width: 90%;
    }
    
    .login-logo {
        text-align: center;
        margin-bottom: 20px;
    }
    
    .login-logo img.kso-logo {
        max-width: 150px;
        height: auto;
        margin-bottom: 15px;
        filter: drop-shadow(0 0 10px rgba(255,255,255,0.3));
        transition: all 0.3s ease;
    }
    
    .login-logo img.kso-logo:hover {
        transform: scale(1.05);
    }
    
    .login-logo a {
        color: white;
        font-size: 24px;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        display: block;
        transition: all 0.3s ease;
    }
    
    .login-logo a:hover {
        text-decoration: none;
        transform: scale(1.05);
    }
    
    .login-card-body {
        border-radius: 10px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        padding: 30px;
    }
    
    .login-box-msg {
        font-size: 18px;
        color: #2c3e50;
        margin-bottom: 25px;
        text-align: center;
    }
    
    .input-group {
        margin-bottom: 20px !important;
    }
    
    .input-group-text {
        background-color: #3498db;
        color: white;
        border: none;
    }
    
    .password-toggle {
        cursor: pointer;
    }
    
    .form-control {
        border-radius: 4px;
        height: 45px;
        border: 1px solid #ddd;
    }
    
    .btn-primary {
        background: linear-gradient(to right, #3498db, #2c3e50);
        border: none;
        border-radius: 4px;
        padding: 10px 0;
        font-weight: bold;
        transition: all 0.3s ease;
    }
    
    .btn-primary:hover {
        background: linear-gradient(to right, #2c3e50, #3498db);
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }
    
    .icheck-primary label {
        font-size: 14px;
    }
    
    .security-info {
        display: flex;
        justify-content: center;
        gap: 10px;
    }
    
    .security-info .badge {
        padding: 8px 12px;
        font-size: 12px;
        border-radius: 20px;
    }
    
    .alert {
        border-radius: 6px;
        border-left: 4px solid;
    }
    
    .alert-success {
        border-left-color: #28a745;
    }
    
    .alert-warning {
        border-left-color: #ffc107;
    }
    
    /* Responsive adjustments */
    @media (max-width: 576px) {
        .login-box {
            width: 320px;
        }
        
        .login-logo img.kso-logo {
            max-width: 120px;
        }
        
        .login-card-body {
            padding: 20px;
        }
        
        .security-info {
            flex-direction: column;
            align-items: center;
            gap: 5px;
        }
    }
</style>

<div class="login-page bg-gradient">
    <div class="login-box">
        <div class="login-logo">
            <img src="dist/img/kso-logo.png" alt="KSO Logo" class="kso-logo">
            <a href="#"><b>KSO</b> Chandigarh</a>
        </div>
        <!-- /.login-logo -->
        <div class="card shadow-lg">
            <div class="card-body login-card-body rounded">
                <p class="login-box-msg font-weight-bold">Admin Panel Login</p>

                <?php if (isset($logout_message)): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <?php echo htmlspecialchars($logout_message); ?>
                </div>
                <?php endif; ?>

                <?php if ($expired_message): ?>
                <div class="alert alert-warning alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <?php echo $expired_message; ?>
                </div>
                <?php endif; ?>

                <div id="loginMessages"></div>

                <form id="loginForm" action="auth/login.php" method="post">
                    <div class="input-group mb-3">
                        <input type="text" name="username" id="username" class="form-control" placeholder="KSO ID, Username or Email" required>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-user"></span>
                            </div>
                        </div>
                    </div>
                    <div class="input-group mb-3">
                        <input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
                        <div class="input-group-append">
                            <div class="input-group-text password-toggle">
                                <span class="fas fa-lock"></span>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-8">
                            <div class="icheck-primary">
                                <input type="checkbox" id="remember_me" name="remember_me">
                                <label for="remember_me">
                                    Remember Me (30 days)
                                </label>
                            </div>
                        </div>
                        <!-- /.col -->
                        <div class="col-4">
                            <button type="submit" id="loginBtn" class="btn btn-primary btn-block btn-elevated">
                                <span class="btn-text">Sign In</span>
                                <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                            </button>
                        </div>
                        <!-- /.col -->
                    </div>
                </form>

                <p class="mb-1 text-center">
                    <a href="forgot-password.php" class="text-primary"><i class="fas fa-key mr-1"></i> Forgot password?</a>
                </p>
                
                <div class="mt-4 text-center security-info">
                    <span class="badge badge-primary"><i class="fas fa-shield-alt"></i> Secure Login</span>
                    <span class="badge badge-info"><i class="fas fa-lock"></i> Encrypted Connection</span>
                </div>
                    </small>
                </div>
            </div>
            <!-- /.login-card-body -->
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        
        const btn = $('#loginBtn');
        const btnText = btn.find('.btn-text');
        const spinner = btn.find('.spinner-border');
        
        // Show loading state
        btn.prop('disabled', true);
        btnText.text('Signing In...');
        spinner.removeClass('d-none');
        
        // Clear previous messages
        $('#loginMessages').empty();
        
        $.ajax({
            url: 'auth/login.php',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#loginMessages').html(
                        '<div class="alert alert-success"><i class="fas fa-check"></i> ' + response.message + '</div>'
                    );
                    
                    // Redirect after short delay
                    setTimeout(function() {
                        window.location.href = response.redirect || 'index.php';
                    }, 1000);
                } else {
                    $('#loginMessages').html(
                        '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> ' + response.message + '</div>'
                    );
                }
            },
            error: function(xhr, status, error) {
                $('#loginMessages').html(
                    '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> Login failed. Please try again.</div>'
                );
            },
            complete: function() {
                // Reset button state
                btn.prop('disabled', false);
                btnText.text('Sign In');
                spinner.addClass('d-none');
            }
        });
    });
    
    // Auto-focus on username field
    $('#username').focus();
    
    // Show/hide password toggle
    $('.password-toggle').on('click', function() {
        const passwordField = $('#password');
        const icon = $(this).find('.fas');
        
        if (passwordField.attr('type') === 'password') {
            passwordField.attr('type', 'text');
            icon.removeClass('fa-lock').addClass('fa-unlock');
        } else {
            passwordField.attr('type', 'password');
            icon.removeClass('fa-unlock').addClass('fa-lock');
        }
    });
    
    // Add visual feedback on form fields
    $('.form-control').on('focus', function() {
        $(this).closest('.input-group').addClass('input-group-focus');
    }).on('blur', function() {
        $(this).closest('.input-group').removeClass('input-group-focus');
    });
    
    // Animate logo on page load
    $('.kso-logo').css('opacity', 0).animate({
        opacity: 1,
        top: 0
    }, 800, function() {
        // After logo animation, animate the form
        $('.login-card-body').addClass('animated fadeIn');
    });
    
    // Add some nice hover effects for the login button
    $('.btn-elevated').hover(
        function() { $(this).addClass('btn-hover'); },
        function() { $(this).removeClass('btn-hover'); }
    );
    
    // Add "shake" animation for invalid fields
    $('#loginForm').on('invalid', 'input', function(e) {
        $(this).addClass('shake');
        setTimeout(() => {
            $(this).removeClass('shake');
        }, 500);
    });
});
</script>

<style>
    /* Additional dynamic styles */
    .input-group-focus {
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.25);
    }
    
    .btn-hover {
        transform: translateY(-3px);
    }
    
    .animated {
        animation-duration: 0.5s;
        animation-fill-mode: both;
    }
    
    .fadeIn {
        animation-name: fadeIn;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    .shake {
        animation: shake 0.5s;
    }
    
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
        20%, 40%, 60%, 80% { transform: translateX(5px); }
    }
</style>

<?php
require_once 'templates/footer.php';
?>
