<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'db.php';

function post_kpra_invoice($conn, $sale_id)
{
    $errors = [];

    // 🔧 Load KPRA config
    $kpra = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM kpra_config LIMIT 1"));
    if (!$kpra || !$kpra['is_enabled']) {
        return ['success' => false, 'error' => 'KPRA integration is disabled.'];
    }

    // Get NTN from branch_info
    $branch = mysqli_fetch_assoc(mysqli_query($conn, "SELECT ntn FROM branch_info LIMIT 1"));
    if (!$branch || empty($branch['ntn'])) {
        return ['success' => false, 'error' => 'Branch NTN is not configured. Please set NTN in branch settings.'];
    }
    
    // Validate NTN format (allow alphanumeric for flexibility)
    if (empty($branch['ntn']) || strlen($branch['ntn']) < 3) {
        return ['success' => false, 'error' => 'Invalid NTN format. NTN should be at least 3 characters.'];
    }

    // Validate required KPRA credentials
    if (empty($kpra['key'])) {
        return ['success' => false, 'error' => 'KPRA private key is not configured.'];
    }

    // 🔎 Fetch sale
    $sale = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM sales WHERE id = $sale_id"));
    if (!$sale) {
        return ['success' => false, 'error' => 'Sale not found.'];
    }

    // 🔎 Calculate tax amounts
    $total_amount = $sale['total_amount']; // Total including tax
    $tax_amount = $sale['tax_amount'];   // Tax amount
    $amount_excluding_tax = $total_amount - $tax_amount; // Amount excluding tax
    
    // Calculate tax rate percentage
    $tax_rate = 0;
    if ($amount_excluding_tax > 0) {
        $tax_rate = ($tax_amount / $amount_excluding_tax) * 100;
    }

    // 🔎 Format date time for KPRA (YYYY-MM-DD HH:MM:SS)
    $invoice_datetime = date('Y-m-d H:i:s', strtotime($sale['sale_date']));

    // ✅ Build KPRA payload according to documentation
    $kpra_data = [
        'ntn' => $branch['ntn'],
        'key' => $kpra['key'],
        'invoice_no' => $sale['invoice_number'],
        'amount' => number_format($amount_excluding_tax, 2, '.', ''),
        'sts' => number_format($tax_amount, 2, '.', ''),
        'date' => $invoice_datetime
    ];

    // 📤 Send to KPRA API
    $api_url = $kpra['api_url'];
    
    // Build URL with parameters
    $url = $api_url . '?' . http_build_query($kpra_data);
    
    // Log the request
    $request_log = [
        'sale_id' => $sale_id,
        'url' => $url,
        'data' => $kpra_data,
        'timestamp' => date('Y-m-d H:i:s')
    ];

    // Make the API call
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        $error = 'CURL Error: ' . curl_error($ch);
        curl_close($ch);
        
        // Log the error
        $stmt = $conn->prepare("INSERT INTO kpra_logs (sale_id, request_data, response_data, status_code) VALUES (?, ?, ?, ?)");
        $request_json = json_encode($request_log);
        $response_json = json_encode(['error' => $error]);
        $stmt->bind_param("isss", $sale_id, $request_json, $response_json, $http_code);
        $stmt->execute();
        
        return ['success' => false, 'error' => $error];
    }
    
    curl_close($ch);

    // 📝 Log the response
    $stmt = $conn->prepare("INSERT INTO kpra_logs (sale_id, request_data, response_data, status_code) VALUES (?, ?, ?, ?)");
    $request_json = json_encode($request_log);
    $response_json = $response;
    $stmt->bind_param("isss", $sale_id, $request_json, $response_json, $http_code);
    $stmt->execute();

    // 🔍 Parse response
    $response_text = trim($response);
    
    // Check for success (KPRA returns simple text responses)
    if ($response_text === 'Success' || $response_text === '1') {
        // ✅ Success - Generate QR code URL
        $qr_code_url = generate_kpra_qr_code_url($sale['invoice_number'], $kpra['business_id'] ?? '');
        
        // Save KPRA invoice record
        $stmt = $conn->prepare("INSERT INTO kpra_invoices (sale_id, kpra_invoice_number, qr_code_url, response_status, response_message) VALUES (?, ?, ?, ?, ?)");
        $kpra_invoice_number = $sale['invoice_number'];
        $response_status = 'success';
        $response_message = 'Success';
        $stmt->bind_param("issss", $sale_id, $kpra_invoice_number, $qr_code_url, $response_status, $response_message);
        $stmt->execute();
        
        // Update sales table to mark KPRA integration
        $stmt = $conn->prepare("UPDATE sales SET is_kpra_enabled = 1, kpra_invoice_number = ?, kpra_qr_code_url = ? WHERE id = ?");
        $stmt->bind_param("ssi", $kpra_invoice_number, $qr_code_url, $sale_id);
        $stmt->execute();
        
        return [
            'success' => true, 
            'data' => [
                'invoice_number' => $kpra_invoice_number,
                'qr_code_url' => $qr_code_url,
                'response' => $response_text
            ]
        ];
    } else {
        // ❌ Error - Handle different error cases
        $error_message = 'Unknown KPRA response: ' . $response_text;
        
        // Map common KPRA error responses
        switch ($response_text) {
            case 'NTN Not found':
                $error_message = 'KPRA NTN not found. Please verify your NTN number.';
                break;
            case 'Private Key Mismatched':
                $error_message = 'KPRA private key is incorrect. Please verify your key.';
                break;
            case 'Insertion Error for example duplicate invoice no or any other':
                $error_message = 'Invoice number already exists in KPRA system.';
                break;
            case 'Empty or missing field request':
                $error_message = 'Missing required fields in KPRA request.';
                break;
        }
        
        // Save error record
        $stmt = $conn->prepare("INSERT INTO kpra_invoices (sale_id, kpra_invoice_number, response_status, response_message) VALUES (?, ?, ?, ?)");
        $kpra_invoice_number = $sale['invoice_number'];
        $response_status = 'error';
        $stmt->bind_param("isss", $sale_id, $kpra_invoice_number, $response_status, $error_message);
        $stmt->execute();
        
        return ['success' => false, 'error' => $error_message];
    }
}

function generate_kpra_qr_code_url($invoice_number, $business_id = '')
{
    $base_url = 'https://kpra.gov.pk/api/?id=' . urlencode($invoice_number);
    
    if (!empty($business_id)) {
        $base_url .= '&businessID=' . urlencode($business_id);
    }
    
    return $base_url;
}

function generate_kpra_qr_code_image($invoice_number, $business_id = '')
{
    $qr_url = generate_kpra_qr_code_url($invoice_number, $business_id);
    
    // Use Google Charts API for QR code generation (free and reliable)
    $google_qr_url = 'https://chart.googleapis.com/chart?chs=150x150&chld=L|0&cht=qr&chl=' . urlencode($qr_url);
    
    return $google_qr_url;
}
?>
