<?php
class GatewayAutoJurnal extends MY_Controller
{
    var $db;
    private $host;
    private $endpointTypes = [
        'SALES' => 'insertSales',
        'AR' => 'insertAr',
        'ARPAYMENT' => 'insertArPayment',
        'RKTAGIHAN' => 'insertRkTagihan',
        'RKPELUNASAN' => 'insertRkPelunasan'
    ];

    public function __construct() {
        parent::__construct();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $this->host = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/one-api/mockup/masterdata/accounting/Mediajurnalauto';
    }

    public function index()
    {
        echo "GATEWAY INJECT AUTO COUNT MEDIA JURNAL CABANG PER TANGGAL";
    }

    /**
     * API endpoint to inject data based on POST parameters
     */
    public function inject($branchCode, $startDate, $endDate, $autoJurnalType) {
        // Validate required fields
        $requiredFields = ['branchCode' => $branchCode, 'startDate' => $startDate, 'endDate' => $endDate, 'autoJurnalType' => $autoJurnalType];
        foreach ($requiredFields as $field => $value) {
            if (empty($value)) {
                $this->sys_error("Missing required parameter: {$field}");
                return;
            }
        }
        
        // Process the request
        $result = $this->injectData(
            $startDate,
            $endDate,
            $branchCode,
            $autoJurnalType
        );
        
        // Send response
        $this->sys_ok($result);
    }

    public function injectData($startDate, $endDate, $branchCode, $endpointType = 'ALL', $verbose = false) {
        // Validate inputs
        if (!$this->validateDate($startDate) || !$this->validateDate($endDate)) {
            $this->sys_error("Invalid date format. Use Y-m-d format.");
            exit;
        }
        
        if (empty($branchCode)) {
            $this->sys_error("Branch code is required.");
            exit;
        }

        if (strtotime($startDate) > strtotime($endDate)) {
            $this->sys_error("Start date cannot be greater than end date.");
            exit;
        }
        
        // Define endpoints to use based on type
        $selectedEndpoints = [];
        
        // Process single or multiple endpoint types
        $typesToProcess = is_array($endpointType) ? $endpointType : [$endpointType];
        
        foreach ($typesToProcess as $type) {
            $type = strtoupper($type);
            
            // If 'ALL' is specified, use all endpoints
            if ($type === 'ALL') {
                foreach ($this->endpointTypes as $key => $endpoint) {
                    $selectedEndpoints[$endpoint] = "{$this->host}/{$endpoint}/{$branchCode}/%s";
                }
                break;
            }
            
            // Check if the specified type exists
            if (isset($this->endpointTypes[$type])) {
                $endpointName = $this->endpointTypes[$type];
                $selectedEndpoints[$endpointName] = "{$this->host}/{$endpointName}/{$branchCode}/%s";
            }
        }
        
        // If no valid endpoint types were provided
        if (empty($selectedEndpoints)) {
            $this->sys_error("Invalid endpoint type specified. Valid types are: " . implode(', ', array_keys($this->endpointTypes)) . ", or ALL");
            exit;
        }
        
        // Convert dates to DateTime objects for iteration
        $currentDate = new DateTime($startDate);
        $end = new DateTime($endDate);
        
        $results = [];
        
        // Loop through each day in the range
        while ($currentDate <= $end) {
            $dateStr = $currentDate->format('Y-m-d');
            
            // Call each selected endpoint for the current date
            foreach ($selectedEndpoints as $endpointName => $endpointUrl) {
                $url = sprintf($endpointUrl, $dateStr);
                $response = $this->curlGet($url);
                
                $results[$dateStr][$endpointName] = $response;
                
                // Optional: Add delay to prevent overwhelming the API
                usleep(100000); // 0.1 second delay
            }
            
            // Move to next day
            $currentDate->modify('+1 day');
        }
        
        return [
            'status' => 'success',
            'data' => $results,
            'summary' => [
                'startDate' => $startDate,
                'endDate' => $endDate,
                'branchCode' => $branchCode,
                'endpointTypes' => $typesToProcess,
                'totalDays' => count($results)
            ]
        ];
    }

    private function curlGet($url) {
        $ch = curl_init($url);
        
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        if ($error) {
            return [
                'success' => false,
                'code' => 0,
                'message' => $error
            ];
        }
        
        return [
            'success' => ($httpCode >= 200 && $httpCode < 300),
            'code' => $httpCode,
            'response' => $response
        ];
    }
    
    /**
     * Validate date format
     * 
     * @param string $date Date to validate
     * @return bool Whether the date is valid
     */
    private function validateDate($date) {
        $d = DateTime::createFromFormat('Y-m-d', $date);
        return $d && $d->format('Y-m-d') === $date;
    }
}