<?php
/**
 * LOGIN PAGE - WITH SUCCESS NOTIFICATION
 * File: auth/login.php
 * Handles user authentication and login
 */

require_once '../app/Core/init.php';

// Redirect if already logged in
if (Auth::check()) {
    $user_type = $_SESSION['user_type'];
    if ($user_type === 'admin') {
        redirect('../admin/index.php');
    } elseif ($user_type === 'vendor') {
        redirect('../vendor/index.php');
    } elseif ($user_type === 'customer') {
        // For customers, redirect to previous page or home
        $redirect_to = $_SESSION['redirect_after_login'] ?? '../index.php';
        unset($_SESSION['redirect_after_login']); // Clear after use
        redirect($redirect_to);
    }
}

// Store the referring page for customers (if coming from somewhere)
if (!isset($_SESSION['redirect_after_login']) && isset($_SERVER['HTTP_REFERER'])) {
    $referer = $_SERVER['HTTP_REFERER'];
    
    // Get current domain
    $current_domain = $_SERVER['HTTP_HOST'] ?? '';
    
    // Only store if referer is from same domain and not login/register pages
    if (strpos($referer, $current_domain) !== false) {
        $parsed = parse_url($referer);
        $path = $parsed['path'] ?? '';
        
        // Exclude auth pages and admin/vendor pages
        $excluded = ['/auth/login.php', '/auth/register.php', '/auth/logout.php', 
                     '/admin/', '/vendor/', '/auth/forgot-password.php'];
        
        $is_excluded = false;
        foreach ($excluded as $exclude) {
            if (strpos($path, $exclude) !== false) {
                $is_excluded = true;
                break;
            }
        }
        
        // Don't store if it's just the homepage
        if (!$is_excluded && $path !== '/' && !empty($path)) {
            // Store just the path and query string (not full URL)
            $redirect_path = $path;
            if (isset($parsed['query'])) {
                $redirect_path .= '?' . $parsed['query'];
            }
            $_SESSION['redirect_after_login'] = $redirect_path;
        }
    }
}

// Also check for explicit redirect parameter
if (isset($_GET['redirect'])) {
    $redirect = $_GET['redirect'];
    // Security: only allow relative URLs (no http/https)
    if (strpos($redirect, 'http') === false && strpos($redirect, '//') === false) {
        // Remove leading slash if present to make it relative from auth folder
        $redirect = ltrim($redirect, '/');
        $_SESSION['redirect_after_login'] = '../' . $redirect;
    }
}

$errors = [];
$email = '';
$remember = false;

// Get flash message if any
$flash_message = flash('message');

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!Security::validateToken($token)) {
        $errors['general'] = 'Invalid security token. Please refresh and try again.';
    } else {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);
        
        // Validate inputs
        if (empty($email)) {
            $errors['email'] = 'Email is required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Please enter a valid email address';
        }
        
        if (empty($password)) {
            $errors['password'] = 'Password is required';
        }
        
        // If no validation errors, attempt login
        if (empty($errors)) {
            $result = Auth::attempt($email, $password);
            
            if ($result['success']) {
                // SET SUCCESS FLAG FOR NOTIFICATION
                $_SESSION['login_success'] = true;
                
                // Redirect based on user type
                $user_type = $result['user_type'];
                
                if ($user_type === 'admin') {
                    redirect('../admin/index.php');
                } elseif ($user_type === 'vendor') {
                    redirect('../vendor/index.php');
                } elseif ($user_type === 'customer') {
                    // Customer: redirect to stored page or home
                    $redirect_to = $_SESSION['redirect_after_login'] ?? '../index.php';
                    unset($_SESSION['redirect_after_login']); // Clear after use
                    redirect($redirect_to);
                }
            } else {
                $errors['general'] = $result['message'];
            }
        }
    }
}

$page_title = "Sign In - " . APP_NAME;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="../assets/images/favicon.png">
    <title><?= $page_title ?></title>
    <link href="../assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Header -->
    <?php include '../templates/layouts/frontend/header.php'; ?>
    
    <div class="container-fluid p-0">
        <div class="row g-0">
            <div class="col-xl-5">
                <div class="account-page-area p-4 p-md-5">
                    
                    <!-- Header -->
                    <div class="mb-4">
                        <h2 class="fw-semibold mb-2">Welcome Back!</h2>
                        <p class="text-muted">Sign in to continue to <?= APP_NAME ?></p>
                    </div>
                    
                    <!-- Flash Messages -->
                    <?php if ($flash_message): ?>
                        <div class="alert alert-<?= $flash_message['type'] ?> alert-dismissible fade show" role="alert">
                            <i class="fas fa-<?= $flash_message['type'] == 'success' ? 'check' : 'exclamation' ?>-circle me-2"></i>
                            <?php 
                                if (is_array($flash_message['message'])) {
                                    echo implode('<br>', $flash_message['message']);
                                } else {
                                    echo $flash_message['message'];
                                }
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Display general errors -->
                    <?php if (isset($errors['general'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?= Security::escapeOutput($errors['general']) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Login Form -->
                    <form method="POST" action="" class="register-form">
                        <?= Security::csrfField() ?>
                        
                        <!-- Email Field -->
                        <div class="mb-3">
                            <label class="form-label">Email Address <span class="text-danger">*</span></label>
                            <input type="email" name="email" class="form-control <?= isset($errors['email']) ? 'is-invalid' : '' ?>" 
                                   value="<?= Security::escapeOutput($email) ?>" placeholder="Enter your email" required>
                            <?php if (isset($errors['email'])): ?>
                                <div class="invalid-feedback"><?= $errors['email'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Password Field -->
                        <div class="mb-3">
                            <label class="form-label">Password <span class="text-danger">*</span></label>
                            <div class="position-relative">
                                <input id="password" type="password" name="password" 
                                       class="form-control <?= isset($errors['password']) ? 'is-invalid' : '' ?>" 
                                       placeholder="Enter your password" required>
                                <i data-bs-toggle="#password" class="fa-regular fa-eye-slash toggle-password"></i>
                            </div>
                            <?php if (isset($errors['password'])): ?>
                                <div class="invalid-feedback d-block"><?= $errors['password'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Remember Me & Forgot Password -->
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="remember" value="1" 
                                       id="rememberMe" <?= $remember ? 'checked' : '' ?>>
                                <label class="form-check-label" for="rememberMe">Remember me</label>
                            </div>
                            <a href="forgot-password.php" class="text-decoration-none">Forgot Password?</a>
                        </div>
                        
                        <!-- Submit Button -->
                        <button type="submit" class="btn btn-primary btn-lg w-100">Sign In</button>
                    </form>
                    
                    <!-- Bottom Text -->
                    <div class="bottom-text text-center mt-4">
                        Don't have an account? <a href="register.php" class="fw-medium text-decoration-underline">Sign Up</a>
                    </div>
                </div>
            </div>
            <div class="col-xl-7 d-none d-xl-block">
                <div class="background-image bg-light d-flex flex-column h-100 justify-content-center p-5 rounded-4" data-image-src="../assets/images/lines.svg">
                    <div class="py-5 text-center">
                        <div class="mb-5">
                            <h2 class="fw-semibold">Welcome to <?= APP_NAME ?></h2>
                            <p>Access your account and manage your rental items effortlessly</p>
                        </div>
                        <img src="../assets/images/png-img/login.png" alt="" class="img-fluid">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <?php include '../templates/layouts/frontend/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    
    <script>
        // Toggle password visibility
        document.querySelectorAll('.toggle-password').forEach(icon => {
            icon.addEventListener('click', function() {
                const input = document.querySelector(this.getAttribute('data-bs-toggle'));
                if (input.type === 'password') {
                    input.type = 'text';
                    this.classList.remove('fa-eye-slash');
                    this.classList.add('fa-eye');
                } else {
                    input.type = 'password';
                    this.classList.remove('fa-eye');
                    this.classList.add('fa-eye-slash');
                }
            });
        });
    </script>
</body>
</html>