<?php
/**
 * Login Page
 * LandSales Pro - User authentication
 */
define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/track.php';

initSecureSession();

// Redirect if already logged in
if (isAuthenticated() && validateSession()) {
    if (isAdmin()) {
        header("Location: admin/");
    } else {
        header("Location: dashboard/");
    }
    exit;
}

$error = '';
$success = '';

// Handle login POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf_token = $_POST['csrf_token'] ?? '';

    if (!verifyCSRFToken($csrf_token)) {
        $error = 'Security token expired. Please try again.';
    } else {
        $email = sanitizeInput($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($email) || empty($password)) {
            $error = 'Email and password are required';
        } else {
            // Check rate limiting
            if (!checkLoginAttempts($email)) {
                $error = 'Too many login attempts. Please wait ' . LOGIN_LOCKOUT_MINUTES . ' minutes.';
            } else {
                // First, try to find user by email or phone
                $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? OR phone = ?");
                $stmt->bind_param("ss", $email, $email);
                $stmt->execute();
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    $user = $result->fetch_assoc();

                    // Verify password
                    if (!verifyPassword($password, $user['password'])) {
                        recordFailedLogin($email);
                        $error = 'Invalid email or password';
                    } else {
                        // Check account status
                        switch ($user['status']) {
                            case 'pending':
                                $error = 'Your account is pending activation. Please check your email.';
                                break;
                            case 'suspended':
                                $error = 'Your account has been suspended. Please contact support.';
                                break;
                            case 'deleted':
                                $error = 'This account no longer exists.';
                                break;
                            case 'active':
                                // Login successful
                                loginUser($user);

                                // Redirect based on role
                                if (in_array($user['role'], ['super_admin', 'admin'])) {
                                    header("Location: admin/");
                                } else {
                                    header("Location: dashboard/");
                                }
                                exit;
                            default:
                                $error = 'Account status unknown. Please contact support.';
                        }
                    }
                } else {
                    // User not found in main users table, check staff_users
                    $stmt = $conn->prepare("SELECT s.*, u.id as owner_id, u.company_name, u.status as owner_status
                                            FROM staff_users s
                                            JOIN users u ON s.owner_id = u.id
                                            WHERE s.email = ?");
                    $stmt->bind_param("s", $email);
                    $stmt->execute();
                    $staffResult = $stmt->get_result();

                    if ($staffResult->num_rows > 0) {
                        $staff = $staffResult->fetch_assoc();

                        // Verify password
                        if (!verifyPassword($password, $staff['password'])) {
                            recordFailedLogin($email);
                            $error = 'Invalid email or password';
                        } else {
                            // Check staff status
                            if ($staff['status'] !== 'active') {
                                $error = 'Your staff account is inactive. Please contact your administrator.';
                            } elseif ($staff['owner_status'] !== 'active') {
                                $error = 'The organization account is not active. Please contact support.';
                            } else {
                                // Get owner data
                                $ownerStmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                                $ownerStmt->bind_param("i", $staff['owner_id']);
                                $ownerStmt->execute();
                                $owner = $ownerStmt->get_result()->fetch_assoc();

                                // Staff login successful
                                loginStaffUser($staff, $owner);
                                header("Location: dashboard/");
                                exit;
                            }
                        }
                    } else {
                        recordFailedLogin($email);
                        $error = 'Invalid email or password';
                    }
                }
            }
        }
    }
}

// Get messages from URL params
if (isset($_GET['error'])) {
    $errors = [
        'session_expired' => 'Your session has expired. Please login again.',
        'access_denied' => 'Access denied. Please login with appropriate credentials.',
        'admin_required' => 'Admin access required.',
        'subscription_expired' => 'Your subscription has expired. Please renew to continue.'
    ];
    $error = $errors[$_GET['error']] ?? htmlspecialchars($_GET['error']);
}

if (isset($_GET['success'])) {
    $messages = [
        'registered' => 'Registration successful! You can now login.',
        'password_reset' => 'Password reset successful. Please login with your new password.',
        'logout' => 'You have been logged out successfully.'
    ];
    $success = $messages[$_GET['success']] ?? htmlspecialchars($_GET['success']);
}
?>
<!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 APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * {
            font-family: 'Inter', sans-serif;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            max-width: 1000px;
        }
        .login-brand {
            color: white;
            text-align: center;
            padding: 40px;
            display: none;
        }
        @media (min-width: 768px) {
            .login-brand {
                display: block;
                flex: 1;
                text-align: left;
            }
        }
        .login-brand h1 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        .login-brand p {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        .login-brand .features {
            margin-top: 30px;
        }
        .login-brand .feature-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .login-brand .feature-item i {
            width: 30px;
            height: 30px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-size: 12px;
        }
        .login-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.25);
            padding: 40px;
            width: 100%;
            max-width: 420px;
        }
        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .login-header .logo {
            width: 70px;
            height: 70px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
        }
        .login-header .logo i {
            font-size: 32px;
            color: white;
        }
        .login-header h2 {
            color: #1a1d21;
            font-weight: 700;
            font-size: 1.5rem;
            margin-bottom: 5px;
        }
        .login-header p {
            color: #6b7280;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 8px;
            font-size: 14px;
        }
        .form-control {
            border-radius: 12px;
            padding: 14px 18px;
            border: 2px solid #e5e7eb;
            font-size: 15px;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }
        .input-group .form-control {
            border-right: none;
        }
        .input-group-text {
            background: white;
            border: 2px solid #e5e7eb;
            border-left: none;
            border-radius: 0 12px 12px 0;
            cursor: pointer;
        }
        .btn-login {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 12px;
            padding: 14px;
            font-weight: 600;
            font-size: 16px;
            width: 100%;
            color: white;
            transition: all 0.3s ease;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
            color: white;
        }
        .forgot-link {
            text-align: right;
            margin-bottom: 20px;
        }
        .forgot-link a {
            color: #667eea;
            font-size: 14px;
            text-decoration: none;
        }
        .forgot-link a:hover {
            text-decoration: underline;
        }
        .divider {
            text-align: center;
            margin: 25px 0;
            position: relative;
        }
        .divider::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            width: 100%;
            height: 1px;
            background: #e5e7eb;
        }
        .divider span {
            background: white;
            padding: 0 15px;
            position: relative;
            color: #9ca3af;
            font-size: 14px;
        }
        .register-link {
            text-align: center;
        }
        .register-link p {
            color: #6b7280;
            margin-bottom: 0;
        }
        .register-link a {
            color: #667eea;
            font-weight: 600;
            text-decoration: none;
        }
        .register-link a:hover {
            text-decoration: underline;
        }
        .alert {
            border-radius: 12px;
            padding: 14px 18px;
            margin-bottom: 20px;
            border: none;
            font-size: 14px;
        }
        .alert-danger {
            background: #fef2f2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        .alert-success {
            background: #f0fdf4;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
    </style>
</head>
<body>
    <div class="login-wrapper">
        <div class="login-brand">
            <h1><?php echo APP_NAME; ?></h1>
            <p><?php echo APP_TAGLINE; ?></p>
            <div class="features">
                <div class="feature-item">
                    <i class="fas fa-check"></i>
                    <span>Manage thousands of land plots easily</span>
                </div>
                <div class="feature-item">
                    <i class="fas fa-check"></i>
                    <span>Track sales & installment payments</span>
                </div>
                <div class="feature-item">
                    <i class="fas fa-check"></i>
                    <span>Visual plot grid with status colors</span>
                </div>
                <div class="feature-item">
                    <i class="fas fa-check"></i>
                    <span>Generate reports & calculate profits</span>
                </div>
            </div>
        </div>

        <div class="login-container">
            <div class="login-header">
                <div class="logo">
                    <i class="fas fa-map-marked-alt"></i>
                </div>
                <h2>Welcome Back</h2>
                <p>Sign in to your account</p>
            </div>

            <?php if ($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
            </div>
            <?php endif; ?>

            <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
            </div>
            <?php endif; ?>

            <form action="" method="POST" id="loginForm">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

                <div class="form-group">
                    <label for="email">Email or Phone</label>
                    <input type="text" name="email" id="email" class="form-control"
                           placeholder="Enter your email or phone" required autocomplete="email">
                </div>

                <div class="form-group">
                    <label for="password">Password</label>
                    <div class="input-group">
                        <input type="password" name="password" id="password" class="form-control"
                               placeholder="Enter your password" required autocomplete="current-password">
                        <span class="input-group-text" onclick="togglePassword()">
                            <i class="fas fa-eye" id="toggleIcon"></i>
                        </span>
                    </div>
                </div>

                <div class="forgot-link">
                    <a href="forgot-password.php">Forgot Password?</a>
                </div>

                <button type="submit" class="btn btn-login" id="loginBtn">
                    <span class="btn-text">Sign In</span>
                </button>
            </form>

            <div class="divider">
                <span>or</span>
            </div>

            <div class="register-link">
                <p>Don't have an account? <a href="register.php">Create Account</a></p>
            </div>
        </div>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePassword() {
            const passwordInput = document.getElementById('password');
            const toggleIcon = document.getElementById('toggleIcon');

            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                toggleIcon.classList.remove('fa-eye-slash');
                toggleIcon.classList.add('fa-eye');
            }
        }

        // Form submission
        document.getElementById('loginForm').addEventListener('submit', function() {
            const btn = document.getElementById('loginBtn');
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Signing in...';
            btn.disabled = true;
        });
    </script>
</body>
</html>
