<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../connection.php';
require_once __DIR__ . '/AuthController.php';
require_once __DIR__ . '/AdminController.php';
require_once __DIR__ . '/CollectionAgentController.php';

// Initialize controllers
$authController = new AuthController($conn);
$adminController = new AdminController($conn);
$collectionAgentController = new CollectionAgentController($conn);

// Get request method and input data
$method = $_SERVER['REQUEST_METHOD'];
$data = json_decode(file_get_contents('php://input'), true);

// Get auth token from header or request
$auth_token = $_SERVER['HTTP_AUTHORIZATION'] ?? null;
if ($auth_token !== null && strpos($auth_token, 'Bearer ') === 0) {
    $auth_token = substr($auth_token, 7);
}

// Log the request for debugging
error_log("Request: " . print_r([
    'method' => $method,
    'get' => $_GET,
    'post' => $_POST,
    'input' => $data
], true));

// Route the request
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$endpoint = trim($uri, '/');
$endpoint = str_replace('collection_agent_auth.php', '', $endpoint);

// API Routes
switch ($method) {
    case 'POST':
        // Admin login with company validation
        if (strpos($endpoint, 'admin/login') !== false) {
            if (!empty($data['username']) && !empty($data['password']) && !empty($data['company_id'])) {
                // Use the new adminLogin method with company validation
                $response = $authController->adminLogin(
                    $data['username'],
                    $data['password'],
                    $data['company_id']
                );
                
                // Set appropriate HTTP status code based on response
                if ($response['status'] === 'error') {
                    http_response_code(401); // Unauthorized
                }
                
                echo json_encode($response);
            } else {
                http_response_code(400); // Bad Request
                echo json_encode([
                    'status' => 'error', 
                    'message' => 'Username, password, and company ID are required'
                ]);
            }
        }
        // Handle OTP generation - for both agents and admins
        elseif (isset($_GET['generate_otp']) && !empty($data['mobile_no'])) {
            $response = $authController->generateOTP($data['mobile_no']);
            
            // If the response indicates an admin login, handle it differently
            if (isset($response['status']) && $response['status'] === 'admin') {
                // This is an admin login attempt via registered company mobile number
                $adminResponse = $adminController->login(
                    $response['admin']['username'], // username
                    null, // No password needed for phone login
                    true, // Flag this as a phone-based login
                    $response['admin'] // Pass the admin data directly
                );
                
                // Add admin flag and redirect URL to the response
                if ($adminResponse['status'] === 'success') {
                    $adminResponse['is_admin'] = true;
                    $adminResponse['redirect_url'] = '/admin/dashboard.php';
                    // Include company information in the response
                    $adminResponse['company'] = [
                        'id' => $response['admin']['company_id'],
                        'name' => $response['admin']['company_name']
                    ];
                }
                echo json_encode($adminResponse);
            } else {
                // Regular agent OTP response
                echo json_encode($response);
            }
        }
        elseif (isset($_GET['verify_otp']) && !empty($data['mobile_no']) && !empty($data['otp']) && !empty($data['device_id'])) {
            $device_token = $data['device_token'] ?? null;
            $device_type = $data['device_type'] ?? null;
            echo json_encode($authController->verifyOTP(
                $data['mobile_no'], 
                $data['otp'], 
                $data['device_id'], 
                $device_token, 
                $device_type
            ));
        } 
        // Logout routes
        elseif (isset($_GET['logout'])) {
            if (isset($_GET['admin'])) {
                echo json_encode($adminController->logout());
            } else {
                echo json_encode($authController->logout($auth_token));
            }
        } 
        else {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
        }
        break;

    case 'GET':
        // Check admin auth
        if (strpos($endpoint, 'admin/check_auth') !== false) {
            if ($adminController->isLoggedIn($auth_token)) {
                echo json_encode([
                    'status' => 'success', 
                    'authenticated' => true,
                    'admin' => [
                        'id' => $_SESSION['admin_id'] ?? null,
                        'name' => $_SESSION['admin_name'] ?? null
                    ]
                ]);
            } else {
                http_response_code(401);
                echo json_encode(['status' => 'error', 'authenticated' => false, 'message' => 'Not authenticated']);
            }
        }
        // Check collection agent auth
        elseif (isset($_GET['check_auth'])) {
            $user = $authController->isLoggedIn($auth_token);
            if ($user) {
                echo json_encode(['status' => 'success', 'authenticated' => true, 'user' => $user]);
            } else {
                http_response_code(401);
                echo json_encode(['status' => 'error', 'authenticated' => false, 'message' => 'Not authenticated']);
            }
        }
        // Fetch collection agent data with line and loan information
        elseif (isset($_GET['fetch_agent_data'])) {
            $response = $collectionAgentController->fetchAgentData($auth_token);
            
            if ($response['status'] === 'error') {
                if ($response['message'] === 'Not authenticated') {
                    http_response_code(401);
                } elseif ($response['message'] === 'Agent not found') {
                    http_response_code(404);
                } else {
                    http_response_code(500);
                }
            }
            
            echo json_encode($response);
        }
        // Get agents in particular format with report_in and reporting_time
        elseif (isset($_GET['get_agents_format'])) {
            $response = $collectionAgentController->getAgentsInParticularFormat($auth_token);
            
            if ($response['status'] === 'error') {
                if ($response['message'] === 'Not authenticated') {
                    http_response_code(401);
                } else {
                    http_response_code(500);
                }
            }
            
            echo json_encode($response);
        }
        // Get agents by time range
        elseif (isset($_GET['get_agents_by_time'])) {
            $start_time = $_GET['start_time'] ?? null;
            $end_time = $_GET['end_time'] ?? null;
            
            $response = $collectionAgentController->getAgentsByTimeRange($auth_token, $start_time, $end_time);
            
            if ($response['status'] === 'error') {
                if ($response['message'] === 'Not authenticated') {
                    http_response_code(401);
                } else {
                    http_response_code(500);
                }
            }
            
            echo json_encode($response);
        } else {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        break;
}
