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

// Check if voter service is active for the user
if ($user_data['voter_Mobile_Link_Service'] === "YES") {
    if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {

        $api_key = p4pointsapi("p4points_apikey");
        $epic_no = '';
        $mobile = '';
        $message = '';
        $alertType = '';
        $response = [];

        // Handle POST submission
        if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['submit_link'])) {

            $epic_no = trim($_POST['epic_no']);
            $mobile  = trim($_POST['mobile']);

            $price = $user_data['voter_mobile_link_fee'] ?? 0;
            $old_balance = $user_data['balance'] ?? 0;
            $order_id = order_txn_id();

            if (!empty($epic_no) && !empty($mobile)) {

                if ($old_balance >= $price) {

                    // API URL
                    $url = "https://" . p4pointsapi('p4points_url') .
                           "/panel/serviceapi/voter/voter_mob_link_without_otp.php?apikey=$api_key&epic=$epic_no&mobile=$mobile&type=otpv&otp=123456&cid=123";

                    /** ============================
                     *  cURL CALL
                     * ============================ */
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                    $apiResponse = curl_exec($ch);
                    $curlError   = curl_error($ch);
                    curl_close($ch);

                    if ($apiResponse !== false && empty($curlError)) {

                        $response = json_decode($apiResponse, true);

                        // Normalize status
                        $apiStatus = strtolower($response['status'] ?? '');
                        $statusCode = (int)($response['statusCode'] ?? 0);

                        /** ------------------------------------
                         * SUCCESS CONDITIONS:
                         * status = success OR Success
                         * OR statusCode = 200
                         * ------------------------------------ */
                        if ($apiStatus === "success" || $statusCode === 200) {

                            $refId = $response['refId'] ?? '';
                            $apiMessage = $response['message'] ?? 'Mobile Link Success';

                            // Deduct balance
                            $new_balance = $old_balance - $price;

                            $updateSuccess = db_update("members",
                                ["balance" => $new_balance],
                                " user_id='" . $user_data['user_id'] . "' "
                            );

                            if ($updateSuccess) {

                                // REPORT ENTRY
                                db_insert("reports", [
                                    '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'       => "VOTER MOBILE LINK WITHOUT OTP",
                                    'type'          => "Debit",
                                    'account_number'=> $epic_no,
                                    'app_type'      => "VOTER MOBILE LINK WITHOUT OTP",
                                    'amount'        => $price,
                                    'main_amount'   => $price,
                                    'old_balance'   => $old_balance,
                                    'new_balance'   => $new_balance,
                                    'txn_id'        => $order_id,
                                    'ref_id'        => $refId,
                                    'description'   => "Rs.{$price} debited for Mobile Link (Without OTP). Ref No: {$refId}",
                                    'date_time'     => date('Y-m-d H:i:s'),
                                    'status'        => "Success"
                                ]);

                                // SMS MESSAGE
                                $whamessage =
                                    "Dear {$user_data['name']},\n".
                                    "Your Voter Number *{$epic_no}* Mobile Link Completed.\n\n".
                                    "*Reference ID*: {$refId}\n".
                                    "*Message*: {$apiMessage}\n\n".
                                    "Regards,\n{$site_data['brand']}";

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

                                // SUCCESS MSG
                                $message = "Mobile linked successfully! Reference: $refId";
                                $alertType = 'success';

                            } else {
                                awal_alert_msg("Balance deducted but not saved to database. Contact support!", 'error');
                            }

                        } else {
                            awal_alert_msg("Failed: " . ($response['message'] ?? "Unknown error"), 'error');
                        }

                    } else {
                        awal_alert_msg("API Error! No response from server.", 'error');
                    }

                } else {
                    awal_alert_msg("Insufficient Wallet Balance!", 'error');
                }

            } else {
                awal_alert_msg("Please enter both Voter Number & Mobile Number!", 'error');
            }
        }
    
?>


<!-- HTML FORM -->
<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 (!empty($message)) { ?>
                    <div class="alert alert-<?= $alertType ?> text-center"><?= $message ?></div>
                <?php } ?>

                <form method="POST" class="row">
                    <div class="col-md-12 mb-3">
                        <label>Voter Number</label>
                        <input type="text" name="epic_no" placeholder="Enter Voter Number" maxlength="15"
                            class="form-control"
                            value="<?= htmlspecialchars($epic_no) ?>"
                            oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');"
                            required>
                    </div>

                    <div class="col-md-12 mb-3">
                        <label>New Mobile Number</label>
                        <input type="text" name="mobile" placeholder="Enter Mobile Number" maxlength="15"
                            class="form-control"
                            value="<?= htmlspecialchars($mobile) ?>"
                            oninput="this.value = this.value.replace(/\s+/g, '');"
                            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['voter_mobile_link_fee']; ?>
                        </button>
                        <button type="submit" name="submit_link" class="btn btn-primary"
                            onclick="return confirm('Are you sure you want to submit?');">
                            Submit
                        </button>
                        <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#showDetailsModal">
                            Show
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- MODAL SECTION -->
<div class="modal fade" id="showDetailsModal" tabindex="-1" role="dialog" aria-labelledby="showDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title" id="showDetailsModalLabel">Fetched Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
        <?php if (!empty($epic_no)) { ?>
          <form class="row">

            <!-- Show POST: epic_no -->
            <div class="col-md-6 mb-3">
              <label>Voter Number</label>
              <input type="text" value="<?= htmlspecialchars($epic_no) ?>" class="form-control" readonly>
            </div>

            <!-- Show POST: mobile -->
            <div class="col-md-6 mb-3">
              <label>Mobile Number</label>
              <input type="text" value="<?= htmlspecialchars($mobile) ?>" class="form-control" readonly>
            </div>

            <!-- Show API: refId -->
            <?php if (!empty($response['refId'])) { ?>
              <div class="col-md-6 mb-3">
                <label>Reference No</label>
                <input type="text" value="<?= htmlspecialchars($response['refId']) ?>" class="form-control" readonly>
              </div>
            <?php } ?>

            <!-- Show API: message -->
            <?php if (!empty($response['message'])) { ?>
              <div class="col-md-6 mb-3">
                <label>Message</label>
                <input type="text" value="<?= htmlspecialchars($response['message']) ?>" class="form-control" readonly>
              </div>
            <?php } ?>

          </form>
        <?php } else { ?>
          <p>No details fetched yet. Submit Voter Number to Link Your Mobile Number.</p>
        <?php } ?>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

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

<!-- SHOW MODAL IF DATA EXISTS -->
<script>
  <?php if (!empty($epic_no) && !empty($response['message'])) { ?>
    $(document).ready(function () {
      $('#showDetailsModal').modal('show');
    });
  <?php } ?>
</script>


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