<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include 'layouts/dbconn.php';

    $login_input = trim($_POST['login_input']);
    $password = $_POST['password'];

    if (empty($login_input) || empty($password)) {
        $error_message = "Email/Phone and password are required";
    } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        try {
            // Query using correct table and field names from schema
            $sql = "SELECT u.id, u.role_id, u.first_name, u.middle_name, u.last_name, 
                           u.email, u.phone, u.phone_secondary, u.password_hash, u.status,
                           r.id as role_table_id, r.role_name 
                    FROM users u 
                    INNER JOIN roles r ON u.role_id = r.id 
                    WHERE (u.email = ? OR u.phone = ?) AND u.status = 'active'";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $login_input, $login_input);
            $stmt->execute();
            $result = $stmt->get_result();

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

                // Verify password
                if (password_verify($password, $user['password_hash'])) {
                    // Set session variables based on actual schema
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['email'] = $user['email'];
                    $_SESSION['first_name'] = $user['first_name'];
                    $_SESSION['middle_name'] = $user['middle_name'];
                    $_SESSION['last_name'] = $user['last_name'];
                    $_SESSION['full_name'] = trim($user['first_name'] . ' ' . ($user['middle_name'] ? $user['middle_name'] . ' ' : '') . $user['last_name']);
                    $_SESSION['phone'] = $user['phone'];
                    $_SESSION['phone_secondary'] = $user['phone_secondary'];
                    $_SESSION['role_id'] = $user['role_id'];
                    $_SESSION['role_name'] = $user['role_name'];
                    $_SESSION['login_time'] = time();
                    $_SESSION['session_token'] = bin2hex(random_bytes(32));

                    // Update last login
                    $update_sql = "UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?";
                    $update_stmt = $conn->prepare($update_sql);
                    $update_stmt->bind_param("i", $user['id']);
                    $update_stmt->execute();
                    $update_stmt->close();

                    // Log successful login
                    $log_sql = "INSERT INTO activity_logs (user_id, action_type, module, reference_id, new_values, ip_address, user_agent) 
                               VALUES (?, 'LOGIN', 'AUTHENTICATION', ?, ?, ?, ?)";
                    $log_stmt = $conn->prepare($log_sql);
                    $login_data = json_encode([
                        'login_time' => date('Y-m-d H:i:s'),
                        'ip_address' => $ip_address,
                        'role' => $user['role_name'],
                        'session_id' => session_id()
                    ]);
                    $log_stmt->bind_param("iisss", $user['id'], $user['id'], $login_data, $ip_address, substr($user_agent, 0, 255));
                    $log_stmt->execute();
                    $log_stmt->close();

                    // Role-based redirects using role_id
                    $redirect_url = match($user['role_id']) {
                        1 => 'index.php', // Super Admin
                        2 => 'landlord_dashboard.php', // Landlord
                        3 => 'manager_dashboard.php', // Property Manager
                        4 => 'tenant_dashboard.php', // Tenant
                        5 => 'buyer_dashboard.php', // Buyer
                        6 => 'vendor_dashboard.php', // Vendor
                        7 => 'accountant_dashboard.php', // Accountant
                        default => 'index.php'
                    };
                    
                    header("Location: $redirect_url");
                    exit();
                } else {
                    // Log failed login attempt
                    $log_sql = "INSERT INTO activity_logs (user_id, action_type, module, reference_id, new_values, ip_address, user_agent) 
                               VALUES (?, 'FAILED_LOGIN', 'AUTHENTICATION', ?, ?, ?, ?)";
                    $log_stmt = $conn->prepare($log_sql);
                    $failed_data = json_encode([
                        'reason' => 'invalid_password',
                        'attempt_time' => date('Y-m-d H:i:s')
                    ]);
                    $log_stmt->bind_param("iisss", $user['id'], $user['id'], $failed_data, $ip_address, substr($user_agent, 0, 255));
                    $log_stmt->execute();
                    $log_stmt->close();

                    $error_message = "Invalid email/phone or password";
                }
            } else {
                // User not found - log without user_id
                $log_sql = "INSERT INTO activity_logs (action_type, module, new_values, ip_address, user_agent) 
                           VALUES ('FAILED_LOGIN', 'AUTHENTICATION', ?, ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $failed_data = json_encode([
                    'reason' => 'user_not_found',
                    'login_attempted' => $login_input,
                    'attempt_time' => date('Y-m-d H:i:s')
                ]);
                $log_stmt->bind_param("sss", $failed_data, $ip_address, substr($user_agent, 0, 255));
                $log_stmt->execute();
                $log_stmt->close();

                $error_message = "Invalid email/phone or password";
            }

            $stmt->close();

        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            $error_message = "An error occurred during login. Please try again.";
        }

        $conn->close();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sign In - Property Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root {
            --primary-blue: #1e3a8a;
            --primary-blue-light: #3b82f6;
            --primary-blue-dark: #1e40af;
            --accent-blue: #60a5fa;
            --success-blue: #2563eb;
            --light-blue: #dbeafe;
            --very-light-blue: #eff6ff;
            --property-teal: #0891b2;
            --property-teal-light: #06b6d4;
            --text-dark: #1f2937;
            --text-muted: #6b7280;
            --white: #ffffff;
            --light-gray: #f9fafb;
            --border-color: #e5e7eb;
        }

        body {
            background: linear-gradient(135deg, var(--very-light-blue) 0%, var(--light-blue) 100%);
            min-height: 100vh;
        }

        .card {
            border: none;
            box-shadow: 0 10px 30px rgba(30, 58, 138, 0.1);
            border-radius: 16px;
            overflow: hidden;
        }

        .bg-primary {
            background: linear-gradient(135deg, #ffffff 0%, #f8faff 30%, #eff6ff 100%) !important;
            border-right: 4px solid var(--primary-blue);
        }

        .form-control {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 0.2rem rgba(30, 58, 138, 0.25);
        }

        .input-group-text {
            background-color: var(--light-blue);
            border: 2px solid var(--border-color);
            border-right: none;
            color: var(--primary-blue);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-blue-light) 100%);
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-blue-dark) 0%, var(--primary-blue) 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(30, 58, 138, 0.3);
        }

        .text-primary {
            color: var(--primary-blue) !important;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-blue) 0%, var(--property-teal) 100%);
            z-index: 1;
        }

        .feature-item {
            background: rgba(30, 58, 138, 0.08);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }

        .feature-item:hover {
            transform: translateY(-2px);
            background: rgba(30, 58, 138, 0.12);
        }

        .alert-danger {
            background-color: #fef2f2;
            border-color: #fecaca;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }
    </style>
</head>

<body>
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        <div class="auth-page-content overflow-hidden pt-lg-5">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card overflow-hidden border-0 shadow-lg">
                            <div class="row g-0">
                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4 h-100 bg-primary bg-gradient">
                                        <div class="position-relative h-100 d-flex flex-column align-items-center justify-content-center text-center">
                                            <div class="mb-4">
                                                <a href="index.php" class="d-block">
                                                    <img src="assets/images/logo.png" alt="Property Management" height="80" class="mb-3">
                                                </a>
                                                <h4 class="text-dark mb-3">Property Management System</h4>
                                                <p class="text-muted mb-4">Comprehensive platform for managing properties, tenants, leases, and finances.</p>
                                            </div>
                                            
                                            <div class="row text-center w-100">
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-building-line text-primary h4 mb-2 d-block"></i>
                                                        <small class="text-dark">Property Management</small>
                                                    </div>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-team-line text-primary h4 mb-2 d-block"></i>
                                                        <small class="text-dark">Tenant Portal</small>
                                                    </div>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-money-dollar-circle-line text-primary h4 mb-2 d-block"></i>
                                                        <small class="text-dark">Financial Tracking</small>
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div class="feature-item">
                                                        <i class="ri-file-text-line text-primary h4 mb-2 d-block"></i>
                                                        <small class="text-dark">Lease Management</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4">
                                        <div class="text-center mb-4">
                                            <h5 class="text-primary mb-2">Welcome Back!</h5>
                                            <p class="text-muted">Sign in to continue to Property Management System</p>
                                        </div>

                                        <div class="mt-4">
                                            <?php if(isset($error_message)): ?>
                                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                    <i class="ri-error-warning-line me-2"></i>
                                                    <?php echo htmlspecialchars($error_message); ?>
                                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                                </div>
                                            <?php endif; ?>

                                            <form id="login-form" method="POST" novalidate>
                                                <div class="mb-3">
                                                    <label for="login_input" class="form-label">Email or Phone Number</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text"><i class="ri-user-line"></i></span>
                                                        <input type="text" class="form-control" id="login_input" name="login_input" 
                                                               placeholder="Enter email or phone number" 
                                                               value="<?php echo isset($_POST['login_input']) ? htmlspecialchars($_POST['login_input']) : ''; ?>"
                                                               required>
                                                    </div>
                                                </div>

                                                <div class="mb-3">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <label class="form-label mb-0" for="password">Password</label>
                                                        <a href="forgot_password.php" class="text-muted text-decoration-none small">
                                                            <i class="ri-lock-line me-1"></i>Forgot password?
                                                        </a>
                                                    </div>
                                                    <div class="input-group">
                                                        <span class="input-group-text"><i class="ri-lock-line"></i></span>
                                                        <input type="password" class="form-control" placeholder="Enter password" 
                                                               id="password" name="password" required>
                                                        <button class="btn btn-outline-secondary" type="button" id="password-addon">
                                                            <i class="ri-eye-line"></i>
                                                        </button>
                                                    </div>
                                                </div>

                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="checkbox" id="auth-remember-check">
                                                    <label class="form-check-label" for="auth-remember-check">
                                                        Remember me
                                                    </label>
                                                </div>

                                                <div class="mt-4">
                                                    <button class="btn btn-primary w-100" type="submit" id="login-btn">
                                                        <i class="ri-login-box-line me-2"></i>Sign In
                                                    </button>
                                                </div>

                                                <div class="mt-4 p-3 bg-light rounded">
                                                    <h6 class="text-muted mb-2">
                                                        <i class="ri-information-line me-2"></i>User Roles
                                                    </h6>
                                                    <small class="text-muted">
                                                        <strong>Landlords:</strong> Property owners<br>
                                                        <strong>Property Managers:</strong> Property management<br>
                                                        <strong>Tenants:</strong> Rent and pay online<br>
                                                        <strong>Staff:</strong> Administrative access
                                                    </small>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0 text-muted">
                                &copy; <script>document.write(new Date().getFullYear())</script> 
                                <span class="text-primary fw-semibold">Property Management System</span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script>
    document.getElementById('password-addon').addEventListener('click', function() {
        const passwordInput = document.getElementById('password');
        const icon = this.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.className = 'ri-eye-off-line';
        } else {
            passwordInput.type = 'password';
            icon.className = 'ri-eye-line';
        }
    });

    document.getElementById('login-form').addEventListener('submit', function(event) {
        const form = this;
        const loginBtn = document.getElementById('login-btn');
        
        if (!form.checkValidity()) {
            event.preventDefault();
            form.classList.add('was-validated');
            return;
        }
        
        loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Signing in...';
        loginBtn.disabled = true;
    });

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('login_input').focus();
    });

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('logout') === 'success') {
        Swal.fire({
            icon: 'success',
            title: 'Logged Out',
            text: 'You have been successfully logged out.',
            timer: 2000,
            showConfirmButton: false
        });
    }
    </script>
</body>
</html>