<?php
session_start();

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include 'layouts/dbconn.php';
    
    $login_input = trim($_POST['login_input'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($login_input) || empty($password)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Email/Phone and password are required'
        ]);
        exit;
    }
    
    $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 names: users and roles
        $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.role_name,
                       CASE 
                           WHEN r.id = 2 THEN 'LANDLORD'
                           WHEN r.id = 3 THEN 'MANAGER'
                           WHEN r.id = 4 THEN 'TENANT'
                           WHEN r.id = 5 THEN 'BUYER'
                           WHEN r.id = 6 THEN 'VENDOR'
                           WHEN r.id = 7 THEN 'ACCOUNTANT'
                           ELSE 'ADMIN'
                       END as user_category
                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();
            
            if (password_verify($password, $user['password_hash'])) {
                // 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();
                
                // Set session variables
                $_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['user_category'] = $user['user_category'];
                $_SESSION['login_time'] = time();
                $_SESSION['session_token'] = bin2hex(random_bytes(32));
                
                // 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'],
                    'user_category' => $user['user_category'],
                    '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();
                
                // Get user-specific statistics
                $stats = [];
                
                try {
                    // For Landlords - get property statistics
                    if ($user['user_category'] === 'LANDLORD') {
                        $landlord_stats_sql = "SELECT 
                                              COUNT(DISTINCT p.id) as total_properties,
                                              COUNT(DISTINCT u.id) as total_units,
                                              COUNT(DISTINCT CASE WHEN u.status = 'occupied' THEN u.id END) as occupied_units,
                                              COUNT(DISTINCT CASE WHEN u.status = 'vacant' THEN u.id END) as vacant_units,
                                              COUNT(DISTINCT l.id) as active_leases,
                                              COALESCE(SUM(l.rent_amount), 0) as total_monthly_rent,
                                              COALESCE(SUM(CASE WHEN i.status = 'unpaid' THEN i.balance ELSE 0 END), 0) as outstanding_balance
                                              FROM properties p
                                              LEFT JOIN units u ON p.id = u.property_id
                                              LEFT JOIN leases l ON u.id = l.unit_id AND l.status = 'active'
                                              LEFT JOIN invoices i ON l.id = i.lease_id
                                              WHERE p.owner_id = ?";
                        $landlord_stmt = $conn->prepare($landlord_stats_sql);
                        $landlord_stmt->bind_param("i", $user['id']);
                        $landlord_stmt->execute();
                        $landlord_result = $landlord_stmt->get_result();
                        
                        if ($landlord_result->num_rows > 0) {
                            $stats = $landlord_result->fetch_assoc();
                        }
                        $landlord_stmt->close();
                    }
                    
                    // For Tenants - get lease and payment info
                    if ($user['user_category'] === 'TENANT') {
                        $tenant_stats_sql = "SELECT 
                                           COUNT(DISTINCT l.id) as total_leases,
                                           COUNT(DISTINCT CASE WHEN l.status = 'active' THEN l.id END) as active_leases,
                                           COALESCE(SUM(CASE WHEN i.status IN ('unpaid', 'overdue') THEN i.balance ELSE 0 END), 0) as outstanding_balance,
                                           COALESCE(SUM(CASE WHEN i.status = 'paid' THEN i.amount ELSE 0 END), 0) as total_paid,
                                           COUNT(DISTINCT i.id) as total_invoices,
                                           COUNT(DISTINCT CASE WHEN i.status = 'overdue' THEN i.id END) as overdue_invoices
                                           FROM leases l
                                           LEFT JOIN invoices i ON l.id = i.lease_id
                                           WHERE l.tenant_id = ?";
                        $tenant_stmt = $conn->prepare($tenant_stats_sql);
                        $tenant_stmt->bind_param("i", $user['id']);
                        $tenant_stmt->execute();
                        $tenant_result = $tenant_stmt->get_result();
                        
                        if ($tenant_result->num_rows > 0) {
                            $stats = $tenant_result->fetch_assoc();
                        }
                        $tenant_stmt->close();
                    }
                    
                    // For Property Managers - get managed properties stats
                    if ($user['user_category'] === 'MANAGER') {
                        $manager_stats_sql = "SELECT 
                                            COUNT(DISTINCT p.id) as managed_properties,
                                            COUNT(DISTINCT u.id) as total_units,
                                            COUNT(DISTINCT CASE WHEN l.status = 'active' THEN l.id END) as active_leases,
                                            COUNT(DISTINCT CASE WHEN mr.status = 'Open' THEN mr.id END) as open_maintenance,
                                            COALESCE(SUM(CASE WHEN i.status IN ('unpaid', 'overdue') THEN i.balance ELSE 0 END), 0) as total_outstanding
                                            FROM properties p
                                            LEFT JOIN units u ON p.id = u.property_id
                                            LEFT JOIN leases l ON u.id = l.unit_id
                                            LEFT JOIN maintenance_requests mr ON p.id = mr.property_id
                                            LEFT JOIN invoices i ON p.id = i.property_id
                                            WHERE p.manager_id = ?";
                        $manager_stmt = $conn->prepare($manager_stats_sql);
                        $manager_stmt->bind_param("i", $user['id']);
                        $manager_stmt->execute();
                        $manager_result = $manager_stmt->get_result();
                        
                        if ($manager_result->num_rows > 0) {
                            $stats = $manager_result->fetch_assoc();
                        }
                        $manager_stmt->close();
                    }
                    
                    // For Accountants - get financial stats
                    if ($user['user_category'] === 'ACCOUNTANT') {
                        $accountant_stats_sql = "SELECT 
                                               COUNT(DISTINCT i.id) as total_invoices,
                                               COUNT(DISTINCT CASE WHEN i.status = 'unpaid' THEN i.id END) as unpaid_invoices,
                                               COUNT(DISTINCT p.id) as total_payments,
                                               COALESCE(SUM(CASE WHEN i.status = 'unpaid' THEN i.balance ELSE 0 END), 0) as unpaid_amount,
                                               COALESCE(SUM(p.amount), 0) as total_payments_amount,
                                               COUNT(DISTINCT e.id) as total_expenses
                                               FROM invoices i
                                               LEFT JOIN payments p ON i.id = p.invoice_id
                                               LEFT JOIN expenses e ON 1=1";
                        $accountant_result = $conn->query($accountant_stats_sql);
                        
                        if ($accountant_result && $accountant_result->num_rows > 0) {
                            $stats = $accountant_result->fetch_assoc();
                        }
                    }
                    
                } catch (Exception $e) {
                    error_log("Stats query error: " . $e->getMessage());
                }
                
                // Determine redirect URL
                $redirect_url = match($user['role_id']) {
                    1 => 'index.php',
                    2 => 'landlord_dashboard.php',
                    3 => 'manager_dashboard.php',
                    4 => 'tenant_dashboard.php',
                    5 => 'buyer_dashboard.php',
                    6 => 'vendor_dashboard.php',
                    7 => 'accountant_dashboard.php',
                    default => 'index.php'
                };
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Login successful',
                    'user' => [
                        'user_id' => $user['id'],
                        'full_name' => $_SESSION['full_name'],
                        'email' => $user['email'],
                        'phone' => $user['phone'],
                        'role_id' => $user['role_id'],
                        'role_name' => $user['role_name'],
                        'user_category' => $user['user_category']
                    ],
                    'stats' => $stats,
                    'redirect_url' => $redirect_url,
                    'session_token' => $_SESSION['session_token'],
                    'login_time' => date('Y-m-d H:i:s')
                ]);
                
            } else {
                // Log failed login
                $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'),
                    'login_attempted' => $login_input
                ]);
                $log_stmt->bind_param("iisss", $user['id'], $user['id'], $failed_data, $ip_address, substr($user_agent, 0, 255));
                $log_stmt->execute();
                $log_stmt->close();
                
                echo json_encode([
                    'success' => false,
                    'message' => 'Invalid email/phone or password'
                ]);
            }
        } else {
            // User not found
            $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();
            
            echo json_encode([
                'success' => false,
                'message' => 'Invalid email/phone or password'
            ]);
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        error_log("Login error: " . $e->getMessage());
        
        echo json_encode([
            'success' => false,
            'message' => 'A system error occurred. Please try again.',
            'error_type' => 'system_error'
        ]);
    }
    
    $conn->close();
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method',
        'error_type' => 'method_not_allowed'
    ]);
}
?>