<?php
ob_start();
session_start();
include "../inc/config.php";
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    
     $stmt = $pdo->query("SELECT * FROM `pickup_entry` ORDER BY `id` DESC");
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // --- Static data (replace with dynamic if needed) ---
    $docNo = 'sum0028';
    
    $docDate = date('d/m/Y');
    
    
    
    $fromGstin = $results[0]['seller_gsts'] ?? '29AAFCC9980M1ZR';
    $fromTrdName =   $results[0]['shipper_name'] ??  'welton';
    $fromAddr1 =  $results[0]['shipper_address'] ??   '2ND CROSS NO 59  19  A';
    $fromAddr2 =  '';
    $fromPlace =  $results[0]['shipper_city'] ??  'FRAZER TOWN';
    $fromPincode =  $results[0]['shipper_pincode'] ??  560090;
    
    
    
    
    
    
    $actFromStateCode =  $results[0]['buyer_gst'] ??  29;
    $fromStateCode =  $results[0]['buyer_gst'] ??  29;
    $taxableAmount =  $results[0]['buyer_gst'] ??  5609889;
    
    
    
    $toGstin =  $results[0]['buyer_gst'] ??  '29AEKPV7203E1Z9';
    $toTrdName =  $results[0]['consignee_name'] ??  'sthuthya';
    $toAddr1 =  $results[0]['consignee_address'] ??  'Shree Nilaya';
    $toAddr2 =    '';
    $toPlace =  $results[0]['consignee_city'] ??  'Beml Nagar';
    $toPincode =  $results[0]['consignee_pincode'] ??  560090;
    
    
    /*  */
    $transactionType =   4;
    $otherValue =    0;
    
    
    
    $actToStateCode =  $results[0]['actToStateCode'] ??  29;
    $toStateCode =  $results[0]['toStateCode'] ??  27;
    $totalValue =  $results[0]['totalValue'] ??  56099;
    $cgstValue =  $results[0]['cgstValue'] ??  0;
    $sgstValue =  $results[0]['sgstValue'] ??  0;
    $igstValue =  $results[0]['igstValue'] ??  300.67;
    $cessValue =  $results[0]['cessValue'] ??  400.56;
    $cessNonAdvolValue =  $results[0]['cessNonAdvolValue'] ??  400;
    $totInvValue =  $results[0]['totInvValue'] ??  68358;
    $transporterId =  $results[0]['transporterId'] ??  '';
    $transporterName =  $results[0]['transporterName'] ??  '';
    $transDocNo =  $results[0]['transDocNo'] ??  '';
    $transMode =  $results[0]['transMode'] ??  '1';
    $transDistance =  $results[0]['transDistance'] ??  '100';
    $transDocDate =  $results[0]['transDocDate'] ??  '';
    $vehicleNo =  $results[0]['vehicleNo'] ??  'PVC1234';
    $vehicleType =  $results[0]['vehicleType'] ??  'R';
    $cgstRate =  $results[0]['cgstRate'] ??  0;
    $sgstRate =  $results[0]['sgstRate'] ??  0;
    $igstRate =  $results[0]['igstRate'] ??  3;
    $cessRate =  $results[0]['cessRate'] ??  3;
    $cessNonadvol =  $results[0]['cessNonadvol'] ??  0;
    
    
    $productName =  $results[0]['product_description'] ??  'Wheat';
    $productDesc =  $results[0]['product_description'] ??  'Wheat';
    $hsnCode =  $results[0]['hsn_code'] ??  1001;
    $quantity =  $results[0]['quantity'] ??  4;
    $qtyUnit =  'BOX';
    

    

    $payload = [
        "supplyType" => "O",
        "subSupplyType" => "1",
        "subSupplyDesc" => "",
        "docType" => "INV",
        "docNo" => $docNo,
        "docDate" => $docDate,
        "fromGstin" => $fromGstin,
        "fromTrdName" => $fromTrdName,
        "fromAddr1" => $fromAddr1,
        "fromAddr2" => $fromAddr2,
        "fromPlace" => $fromPlace,
        "fromPincode" => $fromPincode,
        "actFromStateCode" => $actFromStateCode,
        "fromStateCode" => $fromStateCode,
        "toGstin" => $toGstin,
        "toTrdName" => $toTrdName,
        "toAddr1" => $toAddr1,
        "toAddr2" => $toAddr2,
        "toPlace" => $toPlace,
        "toPincode" => $toPincode,
        "actToStateCode" => $actToStateCode,
        "toStateCode" => $toStateCode,
        "transactionType" => $transactionType,
        "otherValue" => $otherValue,
        "totalValue" => $totalValue,
        "cgstValue" => $cgstValue,
        "sgstValue" => $sgstValue,
        "igstValue" => $igstValue,
        "cessValue" => $cessValue,
        "cessNonAdvolValue" => $cessNonAdvolValue,
        "totInvValue" => $totInvValue,
        "transporterId" => $transporterId,
        "transporterName" => $transporterName,
        "transDocNo" => $transDocNo,
        "transMode" => $transMode,
        "transDistance" => $transDistance,
        "transDocDate" => $transDocDate,
        "vehicleNo" => $vehicleNo,
        "vehicleType" => $vehicleType,
        "itemList" => [
            [
                "productName" => 'test',
                "productDesc" => 'test',
                "hsnCode" => $hsnCode,
                "quantity" => $quantity,
                "qtyUnit" => $qtyUnit,
                "cgstRate" => $cgstRate,
                "sgstRate" => $sgstRate,
                "igstRate" => $igstRate,
                "cessRate" => $cessRate,
                "cessNonadvol" => $cessNonadvol,
                "taxableAmount" => $taxableAmount
            ]
        ]
    ];
    
    
    error_log(json_encode($payload));

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => 'https://my.gstzen.in/~gstzen/a/ewbapi/generate/',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_HTTPHEADER => [
            'Token: de3a3a01-273a-4a81-8b75-13fe37f14dc6',
            'gstin: ' . $fromGstin,
            'Content-Type: application/json'
        ],
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    if ($response === false) {
        echo json_encode(['status' => 'error', 'message' => 'Curl failed']);
        exit;
    }

    $responseDecoded = json_decode($response, true);

    if (isset($responseDecoded['status']) && $responseDecoded['status'] == 1) {
        $ewayBillNo = $responseDecoded['ewayBillNo'];
        $ewayBillDate = $responseDecoded['ewayBillDate'];
        $validUpto = $responseDecoded['validUpto'];
        $uuid = $responseDecoded['uuid'];

        $baseUrl = 'https://my.gstzen.in';
        $files = [
            'ewaybill' => $responseDecoded['EWayBillPdfUrl'] ?? '',
            'parta' => $responseDecoded['EWayBillPartaSlipPdfUrl'] ?? '',
            'qrcode' => $responseDecoded['EWayBillQrCodeUrl'] ?? ''
        ];

        $localUrls = [];

        foreach ($files as $folder => $relativePath) {
            $downloadUrl = $baseUrl . $relativePath;
            $targetDir = __DIR__ . "/../uploads/$folder/";
            $fileName = "{$ewayBillNo}_$folder.pdf";

            if (!file_exists($targetDir)) {
                mkdir($targetDir, 0755, true);
            }

            $fileContent = file_get_contents($downloadUrl);
            if ($fileContent !== false) {
                file_put_contents($targetDir . $fileName, $fileContent);
                $localUrls[$folder] = "/uploads/$folder/$fileName";
            } else {
                $localUrls[$folder] = 'Download failed';
            }
        }
        
        
         $stmt = $pdo->prepare("INSERT INTO tbl_ewaybill (
            ewaybill_no, ewaybill_date, valid_upto, uuid, message, alert,
            pdf_path, parta_path, qrcode_path,pickup_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $stmt->execute([
            $ewayBillNo,
            $ewayBillDate,
            $validUpto,
            $uuid,
            $message,
            $alert,
            $localUrls['ewaybill'],
            $localUrls['parta'],
            $localUrls['qrcode'],
            $id
        ]);


        echo json_encode([
            'status' => 'success',
            'message' => $responseDecoded['message'],
            'ewayBillNo' => $ewayBillNo,
            'ewayBillDate' => $responseDecoded['ewayBillDate'],
            'validUpto' => $responseDecoded['validUpto'],
            'pdfUrls' => $localUrls
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => $responseDecoded['message'].$id ?? 'Failed to generate EWay Bill'.$id
        ]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}
