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

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

<div class="row">
    <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
                if (isset($_POST['submit'])) {
                    $searchType = $_POST['search_type'] ?? '';
                    $searchValue = strtoupper(trim($_POST['search_value'] ?? ''));

                    if (!empty($searchValue)) {
                        $amount = $user_data['pincode_verify_fee'];
                        $old_balance = $user_data['balance'];
                        $new_balance = $old_balance - $amount;

                        if ($old_balance >= $amount) {
                            $order_id = order_txn_id();
                            $api_key = p4pointsapi("p4points_apikey");
                            $api_url = "https://" . p4pointsapi("p4points_url") . "/api/v1/PincodeVerification?&apiKey=$api_key&pincode={$searchValue}";

                            $responseApi = file_get_contents($api_url);
                            $response = json_decode($responseApi, true);

                            if (!empty($response) && isset($response['status']) && $response['status'] == 100 && !empty($response['data']) && is_array($response['data'])) {
                                $postOffices = $response['data'];

                                // Try to update balance
                                if (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'        => "PINCODEVERIFY",
                                        'type'           => "Debit",
                                        'account_number' => $postOffices[0]['State'] ?? 'N/A',
                                        'app_type'       => "PINCODEVERIFY",
                                        'amount'         => $amount,
                                        'main_amount'    => $amount,
                                        'old_balance'    => $old_balance,
                                        'new_balance'    => $new_balance,
                                        'txn_id'         => $order_id,
                                        'ref_id'         => $postOffices[0]['State'] ?? 'N/A',
                                        'description'    => "Rs.{$amount} has been debited from wallet for search: {$searchValue}.",
                                        'date_time'      => current_timestamp(),
                                        'status'         => "Success"
                                    ];

                                    if ($insertId = db_insert("reports", $insData)) {
                                        $whamessage = "Dear {$user_data['name']},\nYour request for PIN Code *{$searchValue}* has been completed.\n\n";
                                        foreach ($postOffices as $office) {
                                            $whamessage .= "*Name*: {$office['Name']}\n";
                                            $whamessage .= "*Branch Type*: {$office['BranchType']}\n";
                                            $whamessage .= "*Delivery Status*: {$office['DeliveryStatus']}\n";
                                            $whamessage .= "*Circle*: {$office['Circle']}\n";
                                            $whamessage .= "*District*: {$office['District']}\n";
                                            $whamessage .= "*Block*: " . ($office['Block'] ?? 'N/A') . "\n";
                                            $whamessage .= "*State*: {$office['State']}\n";
                                            $whamessage .= "*Country*: {$office['Country']}\n\n";
                                        }
                                        $whamessage .= "Best Regards,\n_*{$site_data['brand']}.*_";

                                        send_sms($user_data['mobile'], $whamessage);
                                    } else {
                                        awal_alert_msg("Failed to insert transaction report!", 'error');
                                    }

                                } else {
                                    awal_alert_msg("Balance debited but update failed! Contact support.", 'error');
                                }

                            } else {
                                awal_alert_msg($response['error'] ?? 'Invalid or no response from API.', 'error');
                            }

                        } else {
                            awal_alert_msg("Insufficient Wallet Balance!", 'error');
                        }
                    } else {
                        awal_alert_msg("Please enter a valid Pincode!", 'error');
                    }
                }
                ?>
                <form action="" method="POST" class="row">
                    <div class="col-md-12 mb-3">
                        <label>Search By</label>
                        <select name="search_type" class="form-control" required>
                            <option value="pincode">PIN Code & Post Office Find</option>
                        </select>
                    </div>
                    <div class="col-md-12 mb-3">
                        <label>Enter Value</label>
                        <input type="text" name="search_value" placeholder="Enter PIN Code & Post Office" maxlength="20"
                               class="form-control" required>
                    </div>
                    <div class="col-md-12 mb-3 d-flex justify-content-between">
                        <button type="button" class="btn btn-secondary">
                            <i class="fas fa-inr"></i> <?= $user_data['pincode_verify_fee']; ?>
                        </button>
                        <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">
                            Submit
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- ✅ Display API Response Table -->
    <?php if (isset($postOffices) && count($postOffices) > 0) { ?>
        <div class="col-md-12 mt-4">
            <div class="card text-danger">
                <div class="card-header bg-primary text-white py-2">
                    <span>Pincode/Post Office Details</span>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                        <tr style="text-align: center;">
                            <th>Sr. No.</th>
                            <th>Name</th>
                            <th>PIN Code</th>
                            <th>Branch Type</th>
                            <th>Delivery Status</th>
                            <th>Circle</th>
                            <th>District</th>
                            <th>Region</th>
                            <th>State</th>
                            <th>Country</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $srNo = 1;
                        foreach ($postOffices as $office) { ?>
                            <tr style="text-align: center;">
                                <td><?= $srNo++; ?></td>
                                <td><?= $office['Name']; ?></td>
                                <td><?= $office['Pincode'] ?? 'N/A'; ?></td>
                                <td><?= $office['BranchType']; ?></td>
                                <td>
                                    <button class="btn btn-<?= ($office['DeliveryStatus'] == 'Delivery') ? 'success' : 'danger'; ?>">
                                        <b><?= $office['DeliveryStatus']; ?></b>
                                    </button>
                                </td>
                                <td><?= $office['Circle']; ?></td>
                                <td><?= $office['District']; ?></td>
                                <td><?= $office['Region']; ?></td>
                                <td><?= $office['State']; ?></td>
                                <td><?= $office['Country']; ?></td>
                            </tr>
                        <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php } ?>
</div>

<?php
} else {
    require_once("404.php");
}
require_once("../layouts/members/foot.php");
?>
