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

$api_key = p4pointsapi("p4points_apikey");

if (
    isset($user_data['voter_Pdf_Service'], $user_data['usertype']) &&
    $user_data['voter_Pdf_Service'] === "YES" &&
    in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])
) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    $message = "";
    $pdf_base64 = "";
    $price = $user_data['voter_pdf_fee'] ?? 0;
    $otp_sent = false;
    $otp_verified = false;
    $show_modal = false;
    $epic = $_POST['epic'] ?? "";
    $response = [];

    function call_api($url) {
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);
        $response = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);
        return [$response, $error];
    }

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        if (isset($_POST['find']) && !empty($_POST['epic'])) {
            $epic = strtoupper(trim($_POST['epic']));
            if ($user_data['balance'] < $price) {
                awal_alert_msg("Insufficient wallet balance!", 'error');
            } else {
                $url = "https://" . p4pointsapi("p4points_url") . "/panel/serviceapi/voter/Voterpdf_otp.php?apikey=" . urlencode($api_key) . "&epic=" . urlencode($epic);
                list($result, $curl_error) = call_api($url);

                if ($result === false || !empty($curl_error)) {
                    awal_alert_msg("Connection error.", 'error');
                } else {
                    $response = json_decode($result, true);
                    if (isset($response['status']) && $response['status'] === 'success') {
    if (strpos(strtolower($response['message']), 'please wait') !== false) {
        // OTP already sent recently, show message but do NOT enable OTP form
        $message = $response['message'];
        $otp_sent = false;
        $show_modal = false;
    } else {
        $otp_sent = true;
        $message = $response['message'] ?? "OTP sent.";
        $show_modal = true;
    }
} else {
    awal_alert_msg($response['message'] ?? "Failed to send OTP.", 'error');
}

                }
            }
        }

        if (isset($_POST['verify_otp'], $_POST['otp'], $_POST['epic']) && !empty($_POST['otp']) && !empty($_POST['epic'])) {
            $epic = trim($_POST['epic']);
            $otp = trim($_POST['otp']);
            $order_id = order_txn_id();
            $verify_url = "https://" . p4pointsapi("p4points_url") . "/panel/serviceapi/voter/voterpdf_otp_verify.php?apikey=" . urlencode($api_key) . "&epic=" . urlencode($epic) . "&otp=" . urlencode($otp);

            list($result, $curl_error) = call_api($verify_url);

            if (!$result || !empty($curl_error)) {
                awal_alert_msg("OTP verification error.", 'error');
            } else {
                $data = json_decode($result, true);
                if (isset($data['status']) && $data['status'] === 'success' && !empty($data['file'])) {
                    $otp_verified = true;
                    $pdf_base64 = $data['file'];
                    $response = $data;
                    $message = "OTP verified. PDF ready.";
                    $show_modal = false;

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

                    if ($old_balance >= $amount) {
                        $update_result = db_update("members", ["balance" => $new_balance], "user_id='" . $user_data['user_id'] . "'");
                        if ($update_result) {
                            $txn_id = uniqid("TXN");

                            $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' => "VOTERPDFORIGINAL",
                                'type' => "Debit",
                                'account_number'=> $epic,
                                'amount' => $amount,
                                'main_amount'=> $amount,
                                'old_balance'=> $old_balance,
                                'new_balance'=> $new_balance,
                                'txn_id'=> $txn_id,
                                'ref_id'=> $epic,
                                'description'=> "Rs.{$amount} Has Been Debited For Voter PDF",
                                'date_time'=> date('Y-m-d H:i:s'),
                                'status'=> "Success"
                            ];

                            $insertId = db_insert("reports", $insData);

                            if ($insertId) {
                                $fields = [
                                    'epicNo' => 'Voter No',
                                    'refrenceNo' => 'Sr NO',
                                ];

                                $voterNumber = $epic;

                                $whamessage = "Dear {$user_data['name']},\nYour Request for Voter Number *{$voterNumber}* PDF 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);
                            } else {
                                awal_alert_msg("Insert Server Error!", 'error');
                            }
                        } else {
                            awal_alert_msg("Balance debited but not updated. Contact support!", 'error');
                        }
                    } else {
                        awal_alert_msg("Insufficient Wallet Balance!", 'error');
                    }
                } else {
                    awal_alert_msg($data['message'] ?? "Invalid OTP.", 'error');
                }
            }
        }
    }
?>

<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 d-flex justify-content-between">
                <span>Voter PDF Service</span>
                <button class="btn btn-dark btn-sm" onclick="history.back()"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="p-3 text-dark">
                <?php
if (!empty($message)) {
    $isError = stripos($message, 'please wait') !== false || stripos($message, 'error') !== false || stripos($message, 'failed') !== false;
    $alertClass = $isError ? 'alert-danger' : 'alert-info';
    echo "<div class='alert $alertClass'>$message</div>";
}
?>


                <form method="POST" class="row">
                    <?php if (!$otp_sent || $otp_verified): ?>
                        <div class="col-md-12 mb-3">
                            <label>Voter Number</label>
                            <input type="text" name="epic" placeholder="Enter Voter Number" maxlength="45" value="<?= htmlspecialchars($epic) ?>" 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['voter_pdf_fee']; ?></button>
                            <button type="submit" name="find" class="btn btn-primary" onclick="return confirm('Are you sure?');">Send OTP</button>
                            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#showDetailsModal">Show</button>
                        </div>
                    <?php else: ?>
                        <input type="hidden" name="epic" value="<?= htmlspecialchars($epic) ?>">
                        <div class="col-md-12 mb-3">
                            <label>Enter OTP</label>
                            <input type="text" name="otp"
                                   placeholder="Enter OTP"
                                   maxlength="6"
                                   minlength="6"
                                   pattern="\d{6}"
                                   class="form-control"
                                   required
                                   inputmode="numeric"
                                   title="Please enter a 6-digit OTP">
                        </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_pdf_fee']; ?></button>
                            <button type="submit" name="verify_otp" class="btn btn-primary" onclick="return confirm('Are you sure?');">Verify & Download</button>
                            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#showDetailsModal">Show</button>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <?php if (!empty($pdf_base64)) { ?>
        <div class="col-md-8 mb-2">
            <div class="card text-danger">
                <div class="card-header bg-primary text-white py-2 d-flex justify-content-between">
                    <span>PDF Ready</span>
                    <a href="data:application/pdf;base64,<?= urlencode($pdf_base64); ?>" download="voter_details.pdf" class="btn btn-warning">
                        <i class="fas fa-download"></i> Download
                    </a>
                </div>
                <iframe src="data:application/pdf;base64,<?= htmlspecialchars($pdf_base64); ?>"
                        style="width: 100%; height: 800px; border: 1px solid #ccc;" frameborder="0">
                </iframe>
            </div>
        </div>
    <?php } ?>
</div>

<!-- Modal to show fetched details -->
<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($response['name']) || !empty($response['voter_name'])) { ?>
          <form class="row">
            <div class="col-md-6 mb-3">
              <label>Voter Number</label>
              <input type="text" value="<?= htmlspecialchars($epic) ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 mb-3">
              <label>Name</label>
              <input type="text" value="<?= htmlspecialchars($response['voter_name'] ?? $response['name']) ?>" class="form-control" readonly>
            </div>
          </form>
        <?php } else { ?>
          <p>No details fetched yet. Submit Voter Number to Download PDF.</p>
        <?php } ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<?php if ($otp_sent && !$otp_verified && $show_modal): ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    $('#showDetailsModal').modal('show');
});
</script>
<?php endif; ?>

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