<?php
require_once("../layouts/members/head.php");
if ($user_data['gst_services'] == "YES") { 
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
$gstData = [];
$errorMessage = '';
$apiKey = p4pointsapi("p4points_apikey");
// GST Verification Logic with balance debit system
if (isset($_POST['gst_submit'])) {
    $keyword = trim($_POST['keyword']);  // Get the search keyword (name, GST number, PAN number)

    if (!empty($keyword)) {
        
        $apiUrl = "https://".p4pointsapi("p4points_url")."//api/v1/gstVerification?apiKey={$apiKey}&keyword=" . urlencode($keyword);  // URL encode the keyword to handle special characters

        // Check if the user has enough balance
        $aadharVerifyFee = $user_data['gst_verification_fee'];  // Set the fee for verification
        $old_balance = $user_data['balance'];
        
        if ($old_balance >= $aadharVerifyFee) {
            // Deduct balance from the user's wallet
            $new_balance = $old_balance - $aadharVerifyFee;
            $order_id = order_txn_id();  // Generate a transaction ID

            // Process the API request
            try {
                $responseJson = file_get_contents($apiUrl);  // Send the API request

                if ($responseJson === FALSE) {
                    throw new Exception('Failed to get response from the API.');
                }

               
               

                // Decode the API response
                $apiResponse = json_decode($responseJson, true);

                // Check if the API request was successful
                if (isset($apiResponse['success']) && $apiResponse['success'] === true) {
                    // Check if results exist
                    if (isset($apiResponse['results']) && !empty($apiResponse['results'])) {
                        // Store the results
                        $gstData = $apiResponse['results'];

                        // Update the user's balance after deduction
                        $updateSuccess = db_update("members", ["balance" => $new_balance], "user_id='{$user_data['user_id']}'");

                        if ($updateSuccess) {
                            // Insert transaction details into reports
                            $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'       => "GST_Verification",
                                'type'          => "Debit",
                                'account_number'=> $keyword,
                                'app_type'      => "GST_Verification",
                                'amount'        => $aadharVerifyFee,
                                'main_amount'   => $aadharVerifyFee,
                                'old_balance'   => $old_balance,
                                'new_balance'   => $new_balance,
                                'txn_id'        => $order_id,
                                'description'   => "Rs.{$aadharVerifyFee} Has Been Debited From Wallet for GST Verification on keyword {$keyword}",
                                'date_time'     => current_timestamp(),
                                'status'        => "Success"
                            ];

                            $insertId = db_insert("reports", $insData);
                            if ($insertId) {
                                // Prepare WhatsApp message after success
                                $whamessage = "Dear {$user_data['name']},\nYour request for GST Verification on keyword *{$keyword}* has been completed successfully.\n\n";
                                foreach ($gstData as $item) {
                                    $whamessage .= "*Name*: {$item['name']}\n";
                                    $whamessage .= "*GSTIN*: {$item['gstin']}\n";
                                    $whamessage .= "*Trade Name*: {$item['trade_name']}\n";
                                    $whamessage .= "*City*: {$item['city']}\n";
                                    $whamessage .= "*Status*: {$item['status']}\n\n";
                                }
                                $whamessage .= "Best Regards,\n_*{$site_data['brand']}.*_";

                                // Send the WhatsApp message
                                send_sms($user_data['mobile'], $whamessage);

                            } else {
                                awal_alert_msg("Insert Server !", 'error');
                            }
                        } else {
                            awal_alert_msg("Balance debited from wallet but not updated in the database. Please contact support!", 'error');
                        }
                    } else {
    awal_alert_msg('No GST data found for the provided keyword.', 'error');
}
} else {
    // Handle the API failure
    awal_alert_msg($apiResponse['message'] ?? 'Invalid keyword or API request failed.', 'error');
}
} catch (Exception $e) {
    // Catch any errors with the API request
    awal_alert_msg($e->getMessage(), 'error');
}
} else {
    awal_alert_msg('Insufficient Wallet Balance!', 'error');
}
} else {
    awal_alert_msg('Please enter a valid keyword.', 'error');
}
}
}
?>

<div class="row">
     <?php if ($user_data['gst_services'] == "YES") { ?>
    <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">
                <form method="POST">
                    <div class="form-group">
                        <label>Search Keyword (Name, GST Number, PAN Number)</label>
                        <input type="text" name="keyword" class="form-control" placeholder="Enter Name, GST Number or PAN Number" 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['gst_verification_fee']; ?>
                        </button>
                        <button type="submit" name="gst_submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Search</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- GST Data Result -->
    <div class="col-md-8">
        <?php if ($errorMessage) { ?>
            <div class="alert alert-danger">
                <strong>Message:</strong> <?= $errorMessage; ?>
            </div>
        <?php } elseif (!empty($gstData)) { ?>
            <div class="card">
                <div class="card-header bg-danger text-white py-2">
                    GST Details for Keyword: <?= htmlspecialchars($_POST['keyword']); ?>
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>GSTIN</th>
                                <th>Trade Name</th>
                                <th>City</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($gstData as $item) { ?>
                                <tr>
                                    <td><?= isset($item['name']) ? htmlspecialchars($item['name']) : 'N/A'; ?></td>
                                    <td><?= isset($item['gstin']) ? htmlspecialchars($item['gstin']) : 'N/A'; ?></td>
                                    <td><?= isset($item['trade_name']) ? htmlspecialchars($item['trade_name']) : 'N/A'; ?></td>
                                    <td><?= isset($item['city']) ? htmlspecialchars($item['city']) : 'N/A'; ?></td>
                                    <td><?= isset($item['status']) ? htmlspecialchars($item['status']) : 'N/A'; ?></td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php } else { ?>
            <p></p>
        <?php } ?>
    </div>
</div>
<?php
} else {
    require_once("404.php");
}
}else {
      awal_alert_msg('You Do Not Have Any GST Service Active!', 'info', 'dashboard');
}

require_once("../layouts/members/foot.php");
?>
