<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}


function externalApiCall(string $url, array $data, string $token, string $method = 'POST'): ?array {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $headers = [
        'Content-Type: application/json',
        'Authorization: ' . $token
    ];
    $jsonData = null;

    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        $jsonData = json_encode($data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        $headers[] = 'Content-Length: ' . strlen($jsonData);
    } elseif (strtoupper($method) === 'GET' && !empty($data)) {
        
        $url .= '?' . http_build_query($data);
        curl_setopt($ch, CURLOPT_URL, $url);
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    
    $log_message = "--- External API Call Debug ---\n";
    $log_message .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
    $log_message .= "URL: " . $url . "\n";
    $log_message .= "Method: " . $method . "\n";
    $log_message .= "Request Data: " . ($jsonData ?? json_encode($data)) . "\n"; 
    $log_message .= "HTTP Code: " . $http_code . "\n";
    $log_message .= "cURL Error: " . ($curl_error ?: 'None') . "\n";
    $log_message .= "Raw Response: " . $response . "\n";
    $log_message .= "--- END ---\n";
    if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, $log_message, FILE_APPEND); }

    
    if ($curl_error) {
        return ['success' => false, 'message' => "cURL Error: " . $curl_error, 'http_code' => $http_code];
    }

    
    $decoded_response = json_decode($response, true);
    if ($decoded_response === null && json_last_error() !== JSON_ERROR_NONE) {
        return ['success' => false, 'message' => 'Failed to decode API JSON response.', 'http_code' => $http_code, 'raw_response' => $response];
    }

    
    
    if ($http_code != 200 || !($decoded_response['success'] ?? false) || ($decoded_response['code'] ?? 99) != 0) {
         $error_msg = $decoded_response['message'] ?? ($decoded_response['error'] ?? 'Unknown API error or non-successful response');
         if (!isset($decoded_response['success'])) {
             $decoded_response['success'] = false;
         }
         $decoded_response['message'] = $error_msg; 
         $decoded_response['http_code'] = $http_code; 
         return $decoded_response;
    }
    

    
    $decoded_response['http_code'] = $http_code;
    if (!isset($decoded_response['success'])) {
        $decoded_response['success'] = true;
    }

    return $decoded_response;
}


function sendSmsOTP(string $mobile, string $code): array { 
    if (!defined('API_IR_TOKEN') || !defined('API_BASE_URL')) { return ['success' => false, 'message' => 'پیکربندی API پیامک ناقص است.']; }
    $normalizedMobile = normalizePhoneNumber($mobile); 
    $response = externalApiCall(API_BASE_URL . 'SmsOTP', 
        ['mobile' => $normalizedMobile, 'code' => $code, 'template' => 1], 
        API_IR_TOKEN, 
        'POST'
    ); 
    
    // ⚠️ مهم: اگر API پیامک موفق بود اما API بله/تلگرام خطا داد (timeout)، باید این خطا را نادیده بگیریم.
    // به جای برگرداندن فقط success، کل آرایه را برمی‌گردانیم.
    return $response ?? ['success' => false, 'message' => 'خطای نامشخص در پاسخ API پیامک'];
}


function checkShahkar(string $mobile, string $nationalCode): bool {
    if (!defined('API_IR_TOKEN') || !defined('API_BASE_URL')) return false;
    $normalizedMobile = normalizePhoneNumber($mobile); 
    $response = externalApiCall(API_BASE_URL . 'Shahkar', 
        ['mobile' => $normalizedMobile, 'nationalCode' => $nationalCode, 'isCompany' => false], 
        API_IR_TOKEN, 
        'POST'
    ); 
    
    return ($response['success'] ?? false) && isset($response['data']) && $response['data'] === true; 
}


function checkCardMatch(string $nationalCode, string $birthDate, string $cardNumber): ?bool {
     if (!defined('API_IR_TOKEN') || !defined('API_BASE_URL')) return null;
     $cardNumberClean = preg_replace('/\D/', '', $cardNumber); 

     
     if (!validateNationalIdFormat($nationalCode)) {
        if(defined('ERROR_LOG_PATH')) file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CardMatch Input Validation Failed: Invalid National ID format ({$nationalCode}).\n", FILE_APPEND);
           return null;
     }
     if (!preg_match('/^\d{4}\/\d{2}\/\d{2}$/', $birthDate)) { 
            if(defined('ERROR_LOG_PATH')) file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CardMatch Input Validation Failed: Invalid Birth Date format ({$birthDate}). Expected YYYY/MM/DD.\n", FILE_APPEND);
           return null;
     }
      if (!validateCardNumberFormat($cardNumberClean)) { 
           if(defined('ERROR_LOG_PATH')) file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CardMatch Input Validation Failed: Invalid Card Number format.\n", FILE_APPEND);
           return null;
     }

     $response = externalApiCall(API_BASE_URL . 'CardMatch', 
         [
             'nationalCode' => $nationalCode,
             'birthDate' => $birthDate, 
             'cardNumber' => $cardNumberClean
         ], 
         API_IR_TOKEN,
         'POST'
     ); 

     
     if (isset($response['success']) && $response['success'] === true && isset($response['data'])) {
          
          return (bool)$response['data']; 
     }

     
     $error_msg = $response['message'] ?? 'Unknown or failed response from CardMatch API';
     if(defined('ERROR_LOG_PATH')) file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CardMatch API Error: " . $error_msg . " | NID: {$nationalCode}, BD: {$birthDate}, Card: " . maskCardNumber($cardNumberClean) . "\n", FILE_APPEND);
     return null; 
}

?>