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

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

        $api_key = p4pointsapi("p4points_apikey");

        $showOtpForm = false;
        $epic_no = '';
        $mobile = '';
        $message = '';
        $alertType = '';
        $response = [];

        /* ============================================================
           FUNCTION: cURL Request
        ============================================================ */
        function curlGet($url) {
            $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);
            $result = curl_exec($ch);
            $error  = curl_error($ch);
            curl_close($ch);

            return ($error) ? false : $result;
        }

        /* ============================================================
           GET CAPTCHA (using cURL)
        ============================================================ */
        $captchaUrl = "https://" . p4pointsapi("p4points_url") . "/serviceApi/V1/voterCaptcha.php";
        $captchaResponse = curlGet($captchaUrl);
        $captchaData = json_decode($captchaResponse, true);

        $captcha_img = $captchaData['captcha'] ?? '';
        $captchaTxnId = $captchaData['id'] ?? '';

        /* ============================================================
           POST HANDLER
        ============================================================ */
        if ($_SERVER["REQUEST_METHOD"] == "POST") {

            /* ============================================================
               OTP SEND REQUEST
            ============================================================ */
            if (isset($_POST['find'])) {

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

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

                    $price = $user_data['voter_mobile_link_fee'] ?? 0;
                    $old_balance = $user_data['balance'] ?? 0;

                    if ($old_balance >= $price) {

                        $url = "https://" . p4pointsapi("p4points_url") .
                            "/panel/serviceapi/voter/voter_mob_link.php?apikey=$api_key&epic=$epic_no&mobile=$mobile&type=otp";

                        $apiResponse = curlGet($url);

                        if ($apiResponse !== false) {

                            $response = json_decode($apiResponse, true);
                            $status = strtolower($response['status'] ?? '');

                            if ($status == "success") {
                                $showOtpForm = true;
                                $message = $response['message'] ?? "OTP Sent Successfully";
                                $alertType = 'success';

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

                        } else {
                            awal_alert_msg("API Error: No response received.", 'error');
                        }

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

                } else {
                    awal_alert_msg("Please fill all fields!", 'error');
                }
            }


            /* ============================================================
               OTP VERIFICATION SECTION
            ============================================================ */
            if (isset($_POST['submit_mobile'])) {

                $newMobileNumber = trim($_POST['new_mobile']);
                $epic = trim($_POST['epic']);
                $otp = trim($_POST['otp']);
                $order_id = order_txn_id();

                $price = $user_data['voter_mobile_link_fee'] ?? 0;
                $old_balance = $user_data['balance'] ?? 0;
                $new_balance = $old_balance - $price;

                if ($old_balance >= $price) {

                    $verifyUrl = "https://" . p4pointsapi("p4points_url") .
                        "/panel/serviceapi/voter/voter_mob_link.php?apikey=$api_key&epic=$epic&mobile=$newMobileNumber&type=otpv&otp=$otp&cid=123";

                    $verifyResponse = curlGet($verifyUrl);

                    if ($verifyResponse !== false) {

                        $response = json_decode($verifyResponse, true);

                        $status = strtolower($response['status'] ?? '');
                        $statusCode = $response['statusCode'] ?? 0;

                        // SUCCESS CONDITION
                        if ($status == "success" || $statusCode == 200) {

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

                            $message = "OTP Verified Successfully! Ref No: $refId";
                            $alertType = 'success';

                            /* ============================================================
                               UPDATE WALLET BALANCE
                            ============================================================ */
                            $updateSuccess = db_update("members",
                                ["balance" => $new_balance],
                                " user_id='" . $user_data['user_id'] . "' "
                            );

                            if ($updateSuccess) {

                                $description = "Rs.{$price} Debited For Mobile Link. Ref No: $refId";

                                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' => "VOTERMOBILELINK",
                                    'type' => "Debit",
                                    'account_number' => $epic,
                                    'app_type' => "VOTERMOBILELINK",
                                    'amount' => $price,
                                    'main_amount' => $price,
                                    'old_balance' => $old_balance,
                                    'new_balance' => $new_balance,
                                    'txn_id' => $order_id,
                                    'ref_id' => $refId,
                                    'description' => $description,
                                    'date_time' => date('Y-m-d H:i:s'),
                                    'status' => "Success"
                                ]);

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

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

                            } else {
                                awal_alert_msg("Wallet updated failed! Contact support.", 'error');
                            }

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

                    } else {
                        awal_alert_msg("API Error: No response received.", 'error');
                        $showOtpForm = true;
                    }

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


<!-- HTML Starts -->
<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 } ?>

                <!-- Single Form Handling Both Stages -->
                <form method="POST" class="row">
                    <!-- EPIC and Mobile Inputs (Only Show if OTP Form is Not Active) -->
                    <div class="col-md-12 mb-3" <?= $showOtpForm ? 'style="display:none;"' : '' ?>>
                        <label>Voter Number & New Mobile 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>

                        <label class="mt-2"></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>

                    <!-- OTP Section -->
                    <?php if ($showOtpForm): ?>
                        <!-- Hidden Fields -->
                        <input type="hidden" name="epic" value="<?= htmlspecialchars($epic_no) ?>">
                        <input type="hidden" name="new_mobile" value="<?= htmlspecialchars($mobile) ?>">

                        <div class="col-md-12 mb-3">
                            <label>Full Name</label>
                            <input type="text" name="name" class="form-control" readonly
                                   value="<?= htmlspecialchars($response['name'] ?? '') ?>">
                        </div>

                        <div class="col-md-12 mb-3">
                            <label>Enter OTP</label>
                            <input type="text" name="otp" maxlength="6"
       pattern="\d{6}"
       class="form-control border border-success rounded"
       placeholder="Enter 6 Digit OTP"
       oninput="this.value=this.value.replace(/\D/g,'');"
       required
       title="Please enter exactly 6 digits.">

                        </div>
                    <?php endif; ?>

                    <!-- Submit Buttons -->
                    <div class="col-md-12 mb-3 d-flex justify-content-between">
                        <?php if (!$showOtpForm): ?>
                        
              <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo $user_data['voter_mobile_link_fee'];?></button>
                            <button type="submit" name="find" class="btn btn-primary" onclick="return confirm('Are you sure you want to Send OTP?');">Send OTP</button>
                        <?php else: ?>
                        <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo $user_data['voter_mobile_link_fee'];?></button>
                            <button type="submit" name="submit_mobile" class="btn btn-primary"
                                    onclick="return confirm('Are you sure you want to verify this OTP?');">
                                Verify OTP
                            </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php
} else {
    require_once("404.php");
}
} else {
      awal_alert_msg('You Do Not Have Any Voter Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
