<?php
// Production Login Page - Based on Working Debug Logic
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Include database connection
require_once 'layouts/dbconn.php';

// Initialize variables
$error_message = '';
$success_message = '';
$email = '';

// Redirect if already logged in
if (isset($_SESSION['user']) && !empty($_SESSION['user'])) {
    $role_name = $_SESSION['role_name'] ?? 'Customer';
    if (in_array($role_name, ['Administrator', 'Support Agent', 'Sales Manager', 'Developer'])) {
        header('Location: index.php');
        exit();
    } else {
        header('Location: dashboard.php');
        exit();
    }
}

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

// Handle registration success message
if (isset($_GET['registered']) && $_GET['registered'] === 'success') {
    $success_message = "Registration successful! Please check your email to verify your account.";
}

// Handle session timeout messages
if (isset($_GET['error'])) {
    switch ($_GET['error']) {
        case 'session_expired':
            $error_message = "Your session has expired. Please login again.";
            break;
        case 'session_timeout':
            $error_message = "Your session timed out for security reasons. Please login again.";
            break;
        case 'access_denied':
            $error_message = "Access denied. Please login to continue.";
            break;
    }
}

// Process login form submission - USING EXACT WORKING LOGIC FROM DEBUG
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember_me = isset($_POST['remember_me']);
    
    // Basic validation
    if (empty($email)) {
        $error_message = "Please enter your email address";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = "Please enter a valid email address";
    } elseif (empty($password)) {
        $error_message = "Please enter your password";
    } else {
        
        // Check database connection
        if (!$conn || $conn->connect_error) {
            $error_message = "Database connection failed. Please try again.";
        } else {
            
            try {
                // User lookup - EXACT SAME QUERY AS DEBUG
                $stmt = $conn->prepare("
                    SELECT u.user_id, u.username, u.email, u.full_name, u.password, u.role_id, u.status, ur.role_name 
                    FROM users u
                    LEFT JOIN user_roles ur ON u.role_id = ur.role_id
                    WHERE u.email = ?
                ");
                
                if (!$stmt) {
                    throw new Exception("Failed to prepare statement: " . $conn->error);
                }
                
                $stmt->bind_param("s", $email);
                
                if (!$stmt->execute()) {
                    throw new Exception("Failed to execute query: " . $stmt->error);
                }
                
                $result = $stmt->get_result();
                
                if (!$result) {
                    throw new Exception("Failed to get result");
                }
                
                $user = $result->fetch_assoc();
                $stmt->close();
                
                if (!$user) {
                    $error_message = "Invalid email or password";
                } else {
                    
                    // Account status check
                    if ($user['status'] !== 'ACTIVE') {
                        if ($user['status'] === 'SUSPENDED') {
                            $error_message = "Your account has been suspended. Please contact support.";
                        } elseif ($user['status'] === 'PENDING_VERIFICATION') {
                            $error_message = "Please verify your email address before logging in.";
                        } else {
                            $error_message = "Your account is not active. Please contact support.";
                        }
                    } else {
                        
                        // Password verification - SAME LOGIC AS DEBUG
                        $password_verified = false;
                        
                        // Check if password hash looks correct (bcrypt format)
                        if (!preg_match('/^\$2[ayb]\$/', $user['password'])) {
                            // Try direct comparison (for plain text passwords)
                            if ($password === $user['password']) {
                                $password_verified = true;
                            }
                        } else {
                            // Use password_verify for proper hashes
                            $password_verified = password_verify($password, $user['password']);
                        }
                        
                        if (!$password_verified) {
                            $error_message = "Invalid email or password";
                        } else {
                            
                            // LOGIN SUCCESS - EXACT SAME SESSION LOGIC AS DEBUG
                            
                            // Clear and restart session
                            session_unset();
                            session_destroy();
                            session_start();
                            session_regenerate_id(true);
                            
                            // Set session variables - EXACT SAME AS DEBUG
                            $_SESSION['user'] = $user['username'];
                            $_SESSION['user_id'] = (int)$user['user_id'];
                            $_SESSION['username'] = $user['username'];
                            $_SESSION['email'] = $user['email'];
                            $_SESSION['full_name'] = $user['full_name'];
                            $_SESSION['role_id'] = (int)$user['role_id'];
                            $_SESSION['role_name'] = $user['role_name'] ?? 'Customer';
                            $_SESSION['login_time'] = time();
                            $_SESSION['logged_in'] = true;
                            
                            // Handle remember me
                            if ($remember_me) {
                                $token = bin2hex(random_bytes(32));
                                setcookie('remember_token', $token, time() + (30 * 24 * 60 * 60), '/', '', false, true);
                                
                                // Store token securely
                                $token_stmt = $conn->prepare("UPDATE users SET verification_token = ? WHERE user_id = ?");
                                if ($token_stmt) {
                                    $token_stmt->bind_param("si", $token, $user['user_id']);
                                    $token_stmt->execute();
                                    $token_stmt->close();
                                }
                            }
                            
                            // Determine redirect - EXACT SAME LOGIC AS DEBUG
                            $role_name = $_SESSION['role_name'] ?? 'Customer';
                            
                            if (in_array($role_name, ['Administrator', 'Support Agent', 'Sales Manager', 'Developer'])) {
                                $redirect_url = 'index.php';
                            } else {
                                $redirect_url = 'dashboard.php';
                            }
                            
                            // Redirect - SAME AS DEBUG
                            if (!headers_sent()) {
                                header("Location: {$redirect_url}");
                                exit();
                            } else {
                                // Fallback JavaScript redirect
                                echo "<script>window.location.href = '{$redirect_url}';</script>";
                                exit();
                            }
                        }
                    }
                }
                
            } catch (Exception $e) {
                error_log("Login error: " . $e->getMessage());
                $error_message = "An error occurred during login. Please try again.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Sign In - ConnectPay Platform</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="ConnectPay Platform Login" name="description" />
    <meta content="ConnectPay Platform" name="author" />
    
    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- FontAwesome CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        .authentication-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .login-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            background: rgba(255, 255, 255, 0.95);
        }
        
        .logo-section {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            backdrop-filter: blur(10px);
        }
        
        .logo-section h2 {
            color: white;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .logo-section p {
            color: rgba(255, 255, 255, 0.8);
            margin: 0;
        }
        
        .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .provider-status {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 1rem;
            padding: 0.75rem 1rem;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            color: white;
        }
        
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-left: 10px;
        }
        
        .status-online { background-color: #28a745; }
        .status-maintenance { background-color: #ffc107; }
        .status-offline { background-color: #dc3545; }
        
        .alert {
            border-radius: 10px;
            border: none;
        }
        
        .demo-credentials {
            background: rgba(0, 123, 255, 0.1);
            border: 1px solid rgba(0, 123, 255, 0.2);
            border-radius: 10px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .demo-credentials h6 {
            color: #0d6efd;
            margin-bottom: 0.5rem;
        }
        
        .demo-credentials small {
            color: #6c757d;
        }
        
        .features-list {
            color: rgba(255, 255, 255, 0.9);
            list-style: none;
            padding: 0;
        }
        
        .features-list li {
            margin-bottom: 0.5rem;
            padding-left: 1.5rem;
            position: relative;
        }
        
        .features-list li:before {
            content: "✓";
            position: absolute;
            left: 0;
            color: #28a745;
            font-weight: bold;
        }
        
        .input-group-text {
            border-radius: 10px 0 0 10px;
            border: 2px solid #e9ecef;
            border-right: none;
            background: #f8f9fa;
        }
        
        .input-group .form-control {
            border-left: none;
            border-radius: 0 10px 10px 0;
        }
        
        .input-group .form-control:focus {
            border-left: 2px solid #667eea;
        }

        .demo-account {
            padding: 0.5rem;
            margin: 0.25rem 0;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .demo-account:hover {
            background-color: rgba(0, 123, 255, 0.2);
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-content {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            text-align: center;
        }
    </style>
</head>

<body class="authentication-bg">

    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <i class="fas fa-spinner fa-spin fa-3x text-primary mb-3"></i>
            <h4>Signing you in...</h4>
            <p>Please wait while we verify your credentials</p>
        </div>
    </div>

    <div class="account-pages my-5">
        <div class="container">
            <div class="row justify-content-center align-items-center min-vh-100">
                
                <!-- Left Column - Branding & Info -->
                <div class="col-lg-6 d-none d-lg-block">
                    <div class="logo-section">
                        <div class="text-center mb-4">
                            <i class="fas fa-mobile-alt fa-4x text-white mb-3"></i>
                            <h2>ConnectPay Platform</h2>
                            <p class="lead">South Sudan's Premier Mobile Money Solution</p>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="text-white mb-3">Payment Providers Status</h5>
                                
                                <div class="provider-status">
                                    <span><i class="fas fa-mobile-alt me-2"></i>MTN Mobile Money</span>
                                    <span class="status-indicator status-online"></span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12">
                                <h6 class="text-white mb-3">Platform Features</h6>
                                <ul class="features-list">
                                    <li>Professional WordPress plugins</li>
                                    <li>Multi-currency support (USD, SSP)</li>
                                    <li>Real-time transaction monitoring</li>
                                    <li>Advanced security & anti-piracy</li>
                                    <li>24/7 customer support</li>
                                    <li>Virtual wallet system</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Right Column - Login Form -->
                <div class="col-lg-6 col-md-8 col-xl-5">
                    <div class="card login-card">
                        <div class="card-body p-4">
                            
                            <div class="text-center mb-4">
                                <div class="mb-3">
                                    <i class="fas fa-user-circle fa-3x text-primary"></i>
                                </div>
                                <h4 class="text-uppercase mt-0 mb-1">Welcome Back</h4>
                                <p class="text-muted">Sign in to your ConnectPay Platform account</p>
                            </div>

                            <!-- Success Message -->
                            <?php if (!empty($success_message)): ?>
                            <div class="alert alert-success" role="alert">
                                <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?>
                            </div>
                            <?php endif; ?>

                            <!-- Error Message -->
                            <?php if (!empty($error_message)): ?>
                            <div class="alert alert-danger" role="alert">
                                <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?>
                            </div>
                            <?php endif; ?>

                            <form method="POST" id="loginForm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email Address</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                        <input class="form-control" 
                                               type="email" 
                                               id="email" 
                                               name="email"
                                               placeholder="Enter your email address" 
                                               value="<?php echo htmlspecialchars($email); ?>"
                                               required>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="password" class="form-label">Password</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        <input class="form-control" 
                                               type="password" 
                                               id="password" 
                                               name="password"
                                               placeholder="Enter your password"
                                               required>
                                        <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="remember_me" name="remember_me">
                                        <label class="form-check-label" for="remember_me">
                                            Remember me for 30 days
                                        </label>
                                    </div>
                                </div>

                                <div class="mb-3 d-grid">
                                    <button class="btn btn-primary btn-lg" type="submit" name="login" id="loginBtn">
                                        <i class="fas fa-sign-in-alt me-2"></i>Sign In
                                    </button>
                                </div>
                            </form>

                            <!-- Demo Credentials -->
                            <div class="demo-credentials">
                                <h6><i class="fas fa-info-circle me-2"></i>Demo Accounts</h6>
                                <div class="demo-account" onclick="fillDemoLogin('hi@myne.co.ke', 'admin123')">
                                    <small><strong>Admin:</strong> hi@myne.co.ke / admin123</small>
                                </div>
                                <div class="demo-account" onclick="fillDemoLogin('customer@test.com', 'password123')">
                                    <small><strong>Customer:</strong> customer@test.com / password123</small>
                                </div>
                                <small class="text-muted d-block mt-2">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Click on any demo account to auto-fill credentials
                                </small>
                            </div>

                        </div> <!-- end card-body -->
                    </div>
                    <!-- end card -->

                    <div class="row mt-3">
                        <div class="col-12 text-center">
                            <p class="text-white">
                                <a href="auth-recoverpw.php" class="text-white text-decoration-none">
                                    <i class="fas fa-key me-1"></i>Forgot your password?
                                </a>
                            </p>
                            <p class="text-white">
                                Don't have an account? 
                                <a href="auth-register.php" class="text-white fw-bold text-decoration-none">
                                    <i class="fas fa-user-plus me-1"></i>Create Account
                                </a>
                            </p>
                            <p class="text-white">
                                <small>
                                    <i class="fas fa-shield-alt me-1"></i>
                                    Secured with 256-bit SSL encryption
                                </small>
                            </p>
                        </div> <!-- end col -->
                    </div>
                    <!-- end row -->

                </div> <!-- end col -->
            </div>
            <!-- end row -->
        </div>
        <!-- end container -->
    </div>
    <!-- end page -->

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Custom Login Scripts -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Production login page loaded - based on working debug logic');
            
            // Toggle password visibility
            const togglePassword = document.getElementById('togglePassword');
            const passwordField = document.getElementById('password');
            
            if (togglePassword && passwordField) {
                togglePassword.addEventListener('click', function() {
                    const type = passwordField.getAttribute('type') === 'password' ? 'text' : 'password';
                    passwordField.setAttribute('type', type);
                    
                    const icon = this.querySelector('i');
                    if (icon) {
                        icon.classList.toggle('fa-eye');
                        icon.classList.toggle('fa-eye-slash');
                    }
                });
            }
            
            // Form validation and submission
            const loginForm = document.getElementById('loginForm');
            const loginBtn = document.getElementById('loginBtn');
            const loadingOverlay = document.getElementById('loadingOverlay');
            
            if (loginForm && loginBtn) {
                loginForm.addEventListener('submit', function(e) {
                    console.log('Form submission started');
                    
                    const email = document.getElementById('email').value.trim();
                    const password = document.getElementById('password').value;
                    
                    if (!email || !password) {
                        e.preventDefault();
                        showAlert('Please fill in all required fields', 'danger');
                        return false;
                    }
                    
                    if (!isValidEmail(email)) {
                        e.preventDefault();
                        showAlert('Please enter a valid email address', 'danger');
                        return false;
                    }
                    
                    // Show loading overlay
                    loadingOverlay.style.display = 'flex';
                    
                    // Update button state
                    loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Signing In...';
                    loginBtn.disabled = true;
                    
                    console.log('Form validation passed, submitting with debug-proven logic...');
                    return true;
                });
            }
        });
        
        function fillDemoLogin(email, password) {
            console.log('Filling demo login:', email);
            document.getElementById('email').value = email;
            document.getElementById('password').value = password;
        }
        
        function isValidEmail(email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }
        
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                <i class="fas fa-exclamation-triangle me-2"></i>${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            const form = document.getElementById('loginForm');
            if (form) {
                form.insertBefore(alertDiv, form.firstChild);
            }
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        // Auto-remove success alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert-success');
            alerts.forEach(alert => {
                if (alert.parentNode) {
                    alert.remove();
                }
            });
        }, 5000);
    </script>

</body>
</html>