<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Content-Type: application/json');

include 'connection.php';
require 'vendor/autoload.php'; // JWT library

use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;
use \Firebase\JWT\ExpiredException;

$secret_key = "1ED495A77B65435D317B3E6582E4C";

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}

// Get auth token from headers
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    list($auth_token) = sscanf($headers['Authorization'], 'Bearer %s');
} else {
    echo json_encode(["success" => false, "message" => "Authorization header missing"]);
    exit;
}

try {
    // Check if it's a JWT token or simple auth token
    if (strpos($auth_token, '.') !== false) {
        // It's a JWT token
        $decoded = JWT::decode($auth_token, new Key($secret_key, 'HS256'));
        $company_id = $decoded->data->companyId;
        $uid = $decoded->data->uid;
    } else {
        // It's a simple auth token from database
        $query = "SELECT id, com_id, name, mobile_no, line FROM collection_agent 
                 WHERE auth_token = ? 
                 AND token_expires_at > NOW() 
                 AND is_logged_in = 1
                 LIMIT 1";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $auth_token);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            echo json_encode(["success" => false, "message" => "Invalid or expired token"]);
            exit;
        }
        
        $agent = $result->fetch_assoc();
        $uid = $agent['id'];
        $company_id = $agent['com_id'];
        $stmt->close();
    }

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get today's date
        $today = date('Y-m-d');
        
        // Get the agent's line from the database using the uid from JWT
        $agentQuery = "SELECT line, com_id FROM collection_agent WHERE id = ?";
        $agentStmt = $conn->prepare($agentQuery);
        $agentStmt->bind_param("i", $uid);
        $agentStmt->execute();
        $agentResult = $agentStmt->get_result();
        
        if ($agentResult->num_rows === 0) {
            echo json_encode(["success" => false, "message" => "Agent not found"]);
            exit;
        }
        
        $agentData = $agentResult->fetch_assoc();
        $line = $agentData['line'];
        $company_id = $agentData['com_id'];
        $agentStmt->close();

        // Step 1: Get collection agents for the specified line
        $agentQuery = "SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
                       FROM collection_agent 
                       WHERE com_id = ? AND line = ?";
        $agentStmt = $conn->prepare($agentQuery);
        $agentStmt->bind_param("is", $company_id, $line);
        $agentStmt->execute();
        $agentResult = $agentStmt->get_result();
        
        $agents = [];
        while ($row = $agentResult->fetch_assoc()) {
            $agents[] = $row;
        }
        $agentStmt->close();

        // Step 2: Get line_entry data for the specified line
        $lineQuery = "SELECT id, com_id, area, line, created_on 
                      FROM line_entry 
                      WHERE com_id = ? AND line = ?";
        $lineStmt = $conn->prepare($lineQuery);
        $lineStmt->bind_param("is", $company_id, $line);
        $lineStmt->execute();
        $lineResult = $lineStmt->get_result();
        
        $lineEntries = [];
        $areas = [];
        while ($row = $lineResult->fetch_assoc()) {
            $lineEntries[] = $row;
            $areas[] = $row['area']; // Collect areas for loan query
        }
        $lineStmt->close();

        // Step 3: Get loan_entry data for today's due date and matching areas
        $loanEntries = [];
        if (!empty($areas)) {
            // Create placeholders for the IN clause
            $placeholders = str_repeat('?,', count($areas) - 1) . '?';
            $loanQuery = "SELECT id, loan_id, com_id, loan_date, cust_id, cus_name, cust_mobile, 
                                cust_contact, aadhaar_no, cust_address, cust_address2, area, 
                                loan_type, loan_amt, dues, interest, interest_amt, ledger, 
                                due_schedule, createdOn, total_amt, per_due_amt, next_due_date, 
                                last_due_date, pre_interest
                         FROM loan_entry 
                         WHERE com_id = ? AND area IN ($placeholders) AND next_due_date = ?";
            
            $loanStmt = $conn->prepare($loanQuery);
            
            // Bind parameters: company_id, areas, and today's date
            $params = [$company_id];
            $params = array_merge($params, $areas);
            $params[] = $today;
            
                    $types = str_repeat('s', count($areas)) . 's'; // All string types
                    $allParams = array_merge([$company_id], $areas, [$today]);
                    $loanStmt->bind_param("i" . $types, ...$allParams);
            $loanStmt->execute();
            $loanResult = $loanStmt->get_result();
            
            while ($row = $loanResult->fetch_assoc()) {
                $loanEntries[] = $row;
            }
            $loanStmt->close();
        }

        // Prepare response
        $response = [
            'success' => true,
            'data' => [
                'agents' => $agents,
                'line_entries' => $lineEntries,
                'loan_entries' => $loanEntries,
                'query_info' => [
                    'company_id' => $company_id,
                    'line' => $line,
                    'today' => $today,
                    'areas_found' => $areas,
                    'total_agents' => count($agents),
                    'total_line_entries' => count($lineEntries),
                    'total_loan_entries' => count($loanEntries)
                ]
            ]
        ];

        echo json_encode($response);

    } else {
        echo json_encode(["success" => false, "message" => "Only GET method is allowed"]);
    }

} catch (ExpiredException $e) {
    echo json_encode(["success" => false, "message" => "Token expired"]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "JWT decode failed: " . $e->getMessage()]);
}

$conn->close();
?>
