<?php
require_once("../layouts/members/head.php");

if ($user_data['uid_ration_pdf_Service'] === "YES") {
    if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
        ?>

        <div class="row">
            <!-- Search Section - 30% Width -->
            <div class="col-md-4 mb-2">
                <div class="card text-danger">
                    <div class="card-header bg-primary text-white py-2">
                        <div class="d-flex align-items-center">
                            <span class="mr-auto"><?= file_name() ?></span>
                            <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()">
                                <i class="fas fa-arrow-left"></i> Back
                            </button>
                        </div>
                    </div>
                    <div class="p-3 text-dark">
                        <?php
                        // Initialize variable to hold the generated PDF file name (not saving)
                        $pdfData = null;

                        // Check if the form has been submitted
                        if (isset($_POST['submit'])) {
                            $docno = strtoupper(trim($_POST['docno']));
                            $doctype = $_POST['doctype'] ?? 'ration';  // Default to 'ration' if not set
                            $pdftype = "original";

                            // Validate input
                            if (!empty($docno) && in_array($doctype, ['aadhar', 'ration'])) {
                                $amount = $user_data['ration_pdf_fee'];
                                $old_balance = $user_data['balance'];
                                $new_balance = $old_balance - $amount;

                                // Check if the user has sufficient balance
                                if ($old_balance >= $amount) {
                                    $order_id = order_txn_id();
                                    $api_key = p4pointsapi("p4points_apikey");
                                    $base_url = p4pointsapi("p4points_url");

                                    // ✅ Construct API URL safely
                                    $url = "https://{$base_url}/panel/serviceapi/ration/ration_pdf.php";

                                    // ✅ Prepare API parameters
                                    $params = [
                                        'apiKey' => $api_key,
                                        'docno' => $docno,
                                        'doctype' => $doctype,
                                        'pdftype' => $pdftype
                                    ];

                                    // ✅ Initialize cURL request
                                    $ch = curl_init();
                                    curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable only if API uses self-signed certs
                
                                    $apiResponse = curl_exec($ch);
                                    $curlError = curl_error($ch);
                                    curl_close($ch);

                                    // ✅ Handle cURL errors
                                    if ($apiResponse === false) {
                                        awal_alert_msg("Unable to connect to the server. Please try again later. ($curlError)", 'error');
                                    } else {
                                        $response = json_decode($apiResponse, true);

                                        // ✅ Check API response for success
                                        if ($response && isset($response['status']) && $response['status'] === 'success' && !empty($response['file'])) {
                                            // Decode the base64 encoded PDF file
                                            $pdfBase64 = preg_replace('/^data:application\/pdf;base64,/', '', $response['file']);
                                            $pdfDecoded = base64_decode($pdfBase64);

                                            if ($pdfDecoded) {
                                                // ✅ Deduct balance after successful transaction
                                                db_update("members", ["balance" => $new_balance], "user_id='" . $user_data['user_id'] . "'");

                                                $insData = [
                                                    'site_id' => $site_data['site_id'],
                                                    'user_id' => $user_data['user_id'],
                                                    'username' => $user_data['username'],
                                                    'name' => $user_data['name'],
                                                    'operator' => $user_data['usertype'],
                                                    'parent_id' => $user_data['parent_id'],
                                                    'order_id' => $order_id,
                                                    'service' => "RATIONPDF",
                                                    'type' => "Debit",
                                                    'account_number' => $docno,
                                                    'app_type' => "RATIONPDF",
                                                    'amount' => $amount,
                                                    'main_amount' => $amount,
                                                    'old_balance' => $old_balance,
                                                    'new_balance' => $new_balance,
                                                    'txn_id' => $order_id,
                                                    'ref_id' => $docno,
                                                    'description' => "Rs.{$amount} Has Been Debited From Wallet for Ration PDF Download",
                                                    'date_time' => current_timestamp(),
                                                    'status' => "Success"
                                                ];
                                                db_insert("reports", $insData);

                                                // ✅ Build WhatsApp message
                                                $fields = [
                                                    'uidNumber' => 'UID Number',
                                                    'name' => 'Name',
                                                    'gender' => 'Gender',
                                                    'dob' => 'Date of Birth',
                                                    'address' => 'Address'
                                                ];

                                                $whamessage = "Dear {$user_data['name']},\nYour Request for UID Number *{$docno}* TO RATION Verification has been Complete.\n\n";
                                                foreach ($fields as $key => $label) {
                                                    if (!empty($response[$key])) {
                                                        $whamessage .= "*$label*: {$response[$key]}\n";
                                                    }
                                                }
                                                $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";

                                                send_sms($user_data['mobile'], $whamessage);

                                                // ✅ Set PDF data for iframe display
                                                $pdfData = "data:application/pdf;base64," . $pdfBase64;
                                            } else {
                                                awal_alert_msg("Error decoding PDF file.", 'error');
                                            }
                                        } else {
                                            awal_alert_msg($response['message'] ?? 'Server Down', 'error');
                                        }
                                    }
                                } else {
                                    awal_alert_msg("Insufficient Wallet Balance!", 'error');
                                }
                            } else {
                                awal_alert_msg("Please Fill All Valid Details!", 'error');
                            }
                        }
                        ?>



                        <!-- Search Form -->
                        <form action="" method="POST" class="row">
                            <div class="col-md-12 mb-3">
                                <label>Document Type</label>
                                <select name="doctype" class="form-control" required>
                                    <option value="ration" <?= isset($_POST['doctype']) && $_POST['doctype'] === 'ration' ? 'selected' : '' ?>>Ration Number</option>
                                    <option value="aadhar" <?= isset($_POST['doctype']) && $_POST['doctype'] === 'aadhar' ? 'selected' : '' ?>>Aadhaar Number</option>
                                </select>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label>Document Number</label>
                                <input type="text" name="docno" placeholder="Enter Document Number" maxlength="20"
                                    class="form-control" required>
                            </div>
                            <div class="col-md-12 mb-3 d-flex justify-content-center">
                                <button type="button" class="btn btn-secondary mr-2">
                                    <i class="fas fa-inr"></i> <?= htmlspecialchars($user_data['ration_pdf_fee']) ?>
                                </button>
                                <button type="submit" name="submit" class="btn btn-primary"
                                    onclick="return confirm('Are you sure?');">Submit</button>
                            </div>
                        </form>

                    </div>
                </div>
            </div>

            <!-- PDF Preview Section - 70% Width -->
            <div class="col-md-8 mb-2">
                <?php if ($pdfData): ?>
                    <div class="card">
                        <div class="card-header bg-success text-white py-2">
                            <div class="d-flex align-items-center">
                                <span class="mr-auto">PDF Preview</span>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="d-flex justify-content-center">
                                <!-- PDF Preview: Embedded base64 encoded PDF -->
                                <iframe src="<?= htmlspecialchars($pdfData) ?>" width="100%" height="600px"
                                    class="border rounded"></iframe>
                            </div>
                            <div class="d-flex justify-content-center">
                                <a href="<?= htmlspecialchars($pdfData) ?>" download="RationCard.pdf"
                                    class="btn btn-success mt-3">Download PDF</a>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php
    } else {
        require_once("404.php");
    }
} else {
    awal_alert_msg('You Do Not Have Any Ration Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>