<?php
require_once __DIR__ . '/../connection.php';

class CollectionAgentController {
    private $conn;

    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * Fetch collection agent data with line and loan information
     * Filters data based on report_in and reporting_time
     */
    public function fetchAgentData($auth_token) {
        try {
            // Get today's date
            $today = date('Y-m-d');
            
            // First, get the authenticated user to determine their line
            $user = $this->getAuthenticatedUser($auth_token);
            if (!$user) {
                return [
                    'status' => 'error', 
                    'message' => 'Not authenticated'
                ];
            }

            // Get the agent's line from the database
            $agentQuery = "SELECT line, com_id FROM collection_agent WHERE id = ?";
            $agentStmt = $this->conn->prepare($agentQuery);
            $agentStmt->bind_param("i", $user['id']);
            $agentStmt->execute();
            $agentResult = $agentStmt->get_result();
            
            if ($agentResult->num_rows === 0) {
                return [
                    'status' => 'error', 
                    'message' => 'Agent not found'
                ];
            }
            
            $agentData = $agentResult->fetch_assoc();
            $line = $agentData['line'];
            $company_id = $agentData['com_id'];
            $agentStmt->close();

            // Step 1: Get collection agents for the specified line
            // Filter by report_in and reporting_time (between these times)
            $agentQuery = "SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
                           FROM collection_agent 
                           WHERE com_id = ? AND line = ? 
                           AND report_in IS NOT NULL 
                           AND reporting_time IS NOT NULL
                           AND report_in <= NOW() 
                           AND reporting_time >= NOW()";
            $agentStmt = $this->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 = $this->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 = $this->conn->prepare($loanQuery);
                
                // Bind parameters: company_id, areas, and today's date
                $allParams = array_merge([$company_id], $areas, [$today]);
                $types = str_repeat('s', count($areas)) . 's'; // All string types
                $loanStmt->bind_param("i" . $types, ...$allParams);
                $loanStmt->execute();
                $loanResult = $loanStmt->get_result();
                
                while ($row = $loanResult->fetch_assoc()) {
                    $loanEntries[] = $row;
                }
                $loanStmt->close();
            }

            // Prepare response
            return [
                'status' => 'success',
                '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),
                        'filter_info' => [
                            'filtered_by_report_time' => true,
                            'report_in_condition' => 'report_in <= NOW()',
                            'reporting_time_condition' => 'reporting_time >= NOW()'
                        ]
                    ]
                ]
            ];

        } catch (Exception $e) {
            return [
                'status' => 'error', 
                'message' => 'Database error: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Get authenticated user from auth token
     */
    private function getAuthenticatedUser($auth_token) {
        try {
            if (empty($auth_token)) {
                return false;
            }

            $query = "SELECT id, name, mobile_no, is_logged_in, device_id 
                     FROM collection_agent 
                     WHERE auth_token = ? 
                     AND token_expires_at > NOW() 
                     AND is_logged_in = 1
                     LIMIT 1";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bind_param("s", $auth_token);
            $stmt->execute();
            $result = $stmt->get_result();
            
            return $result->num_rows > 0 ? $result->fetch_assoc() : false;

        } catch (Exception $e) {
            error_log("Session Check Error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Get agents in particular format with report_in and reporting_time
     */
    public function getAgentsInParticularFormat($auth_token) {
        try {
            $user = $this->getAuthenticatedUser($auth_token);
            if (!$user) {
                return [
                    'status' => 'error', 
                    'message' => 'Not authenticated'
                ];
            }

            // Get agent's line, company, and time information
            $agentQuery = "SELECT line, com_id, report_in, reporting_time FROM collection_agent WHERE id = ?";
            $agentStmt = $this->conn->prepare($agentQuery);
            $agentStmt->bind_param("i", $user['id']);
            $agentStmt->execute();
            $agentResult = $agentStmt->get_result();
            
            if ($agentResult->num_rows === 0) {
                return [
                    'status' => 'error', 
                    'message' => 'Agent not found'
                ];
            }
            
            $agentData = $agentResult->fetch_assoc();
            $line = $agentData['line'];
            $company_id = $agentData['com_id'];
            $agentStmt->close();

            // Check if the authenticated agent is currently within their reporting time
            $isCurrentlyActive = $this->isCurrentlyActive($agentData['report_in'], $agentData['reporting_time']);
            
            if (!$isCurrentlyActive) {
                return [
                    'status' => 'api offline',
                    'message' => 'Agent is not within reporting time',
                    'agent_info' => [
                        'agent_id' => $user['id'],
                        'agent_name' => $user['name'],
                        'report_in_time' => $agentData['report_in'],
                        'reporting_time' => $agentData['reporting_time'],
                        'current_time' => date('Y-m-d H:i:s'),
                        'is_currently_active' => false,
                        'time_duration' => $this->calculateTimeDuration($agentData['report_in'], $agentData['reporting_time'])
                    ]
                ];
            }

            // Get all agents with their report_in and reporting_time
            $query = "SELECT 
                        id, 
                        name, 
                        mobile_no, 
                        address, 
                        aadhar_no, 
                        report_in, 
                        reporting_time, 
                        status, 
                        line,
                        created_at
                     FROM collection_agent 
                     WHERE com_id = ? AND line = ?
                     ORDER BY report_in ASC";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bind_param("is", $company_id, $line);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $agents = [];
            while ($row = $result->fetch_assoc()) {
                // Format the time information
                $agents[] = [
                    'agent_id' => $row['id'],
                    'agent_name' => $row['name'],
                    'mobile_number' => $row['mobile_no'],
                    'address' => $row['address'],
                    'aadhar_number' => $row['aadhar_no'],
                    'report_in_time' => $row['report_in'],
                    'reporting_time' => $row['reporting_time'],
                    'status' => $row['status'],
                    'assigned_line' => $row['line'],
                    'created_at' => $row['created_at'],
                    'time_duration' => $this->calculateTimeDuration($row['report_in'], $row['reporting_time']),
                    'is_currently_active' => $this->isCurrentlyActive($row['report_in'], $row['reporting_time'])
                ];
            }
            $stmt->close();

            // Get line entries for the company and line
            $lineQuery = "SELECT id, com_id, area, line, created_on 
                          FROM line_entry 
                          WHERE com_id = ? AND line = ?";
            $lineStmt = $this->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();

            // Get loan entries 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 = $this->conn->prepare($loanQuery);
                
                // Bind parameters: company_id, areas, and today's date
                $today = date('Y-m-d');
                $allParams = array_merge([$company_id], $areas, [$today]);
                $types = str_repeat('s', count($areas)) . 's'; // All string types
                $loanStmt->bind_param("i" . $types, ...$allParams);
                $loanStmt->execute();
                $loanResult = $loanStmt->get_result();
                
                while ($row = $loanResult->fetch_assoc()) {
                    $loanEntries[] = $row;
                }
                $loanStmt->close();
            }

            return [
                'status' => 'success',
                'data' => [
                    'agents' => $agents,
                    'line_entries' => $lineEntries,
                    'loan_entries' => $loanEntries,
                    'total_agents' => count($agents),
                    'total_line_entries' => count($lineEntries),
                    'total_loan_entries' => count($loanEntries),
                    'line_info' => [
                        'line_name' => $line,
                        'company_id' => $company_id
                    ],
                    'areas_found' => $areas,
                    'today' => date('Y-m-d'),
                    'time_analysis' => [
                        'active_agents' => count(array_filter($agents, function($agent) {
                            return $agent['is_currently_active'];
                        })),
                        'inactive_agents' => count(array_filter($agents, function($agent) {
                            return !$agent['is_currently_active'];
                        }))
                    ]
                ]
            ];

        } catch (Exception $e) {
            return [
                'status' => 'error', 
                'message' => 'Database error: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Get agents by time range (custom method)
     */
    public function getAgentsByTimeRange($auth_token, $start_time = null, $end_time = null) {
        try {
            $user = $this->getAuthenticatedUser($auth_token);
            if (!$user) {
                return [
                    'status' => 'error', 
                    'message' => 'Not authenticated'
                ];
            }

            // Get agent's line and company
            $agentQuery = "SELECT line, com_id FROM collection_agent WHERE id = ?";
            $agentStmt = $this->conn->prepare($agentQuery);
            $agentStmt->bind_param("i", $user['id']);
            $agentStmt->execute();
            $agentResult = $agentStmt->get_result();
            
            if ($agentResult->num_rows === 0) {
                return [
                    'status' => 'error', 
                    'message' => 'Agent not found'
                ];
            }
            
            $agentData = $agentResult->fetch_assoc();
            $line = $agentData['line'];
            $company_id = $agentData['com_id'];
            $agentStmt->close();

            // Build time filter conditions
            $timeConditions = [];
            $params = [$company_id, $line];
            $types = "is";

            if ($start_time) {
                $timeConditions[] = "report_in >= ?";
                $params[] = $start_time;
                $types .= "s";
            }

            if ($end_time) {
                $timeConditions[] = "reporting_time <= ?";
                $params[] = $end_time;
                $types .= "s";
            }

            $timeFilter = !empty($timeConditions) ? "AND " . implode(" AND ", $timeConditions) : "";

            $query = "SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
                     FROM collection_agent 
                     WHERE com_id = ? AND line = ? $timeFilter";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $agents = [];
            while ($row = $result->fetch_assoc()) {
                $agents[] = $row;
            }
            $stmt->close();

            return [
                'status' => 'success',
                'data' => [
                    'agents' => $agents,
                    'total_agents' => count($agents),
                    'time_range' => [
                        'start_time' => $start_time,
                        'end_time' => $end_time
                    ]
                ]
            ];

        } catch (Exception $e) {
            return [
                'status' => 'error', 
                'message' => 'Database error: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Calculate time duration between report_in and reporting_time
     */
    private function calculateTimeDuration($report_in, $reporting_time) {
        if (!$report_in || !$reporting_time) {
            return null;
        }
        
        $start = new DateTime($report_in);
        $end = new DateTime($reporting_time);
        $duration = $start->diff($end);
        
        return [
            'hours' => $duration->h,
            'minutes' => $duration->i,
            'total_minutes' => ($duration->h * 60) + $duration->i,
            'formatted' => $duration->format('%H:%I')
        ];
    }

    /**
     * Check if agent is currently active based on report_in and reporting_time
     */
    private function isCurrentlyActive($report_in, $reporting_time) {
        if (!$report_in || !$reporting_time) {
            return false;
        }
        
        $now = new DateTime();
        $start = new DateTime($report_in);
        $end = new DateTime($reporting_time);
        
        return ($now >= $start && $now <= $end);
    }
}
?>
