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

function callVoterStatusApi($epic) {
    $apiUrl = "https://" . p4pointsapi('p4points_url') .
                           "/api/v1/voterStatus.php?epic_no=" . rawurlencode($epic);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HTTPHEADER => [
            'accept: application/json',
            'cache-control: no-cache',
            'pragma: no-cache',
            'user-agent: Mozilla/5.0'
        ]
    ]);

    $apiResponse = curl_exec($ch);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        return [
            "status" => "error",
            "message" => "Status API error: " . $curlError
        ];
    }

    $json = json_decode($apiResponse, true);

    if (!is_array($json)) {
        return [
            "status" => "error",
            "message" => "Invalid status API response"
        ];
    }

    return $json;
}

function showField($label, $value, $col = 6) {
    $value = trim((string)$value);

    if ($value === '') {
        return;
    }
    ?>
    <div class="col-md-<?= (int)$col ?> mb-3">
        <label><?= htmlspecialchars($label) ?></label>
        <input type="text" value="<?= htmlspecialchars($value) ?>" class="form-control" readonly>
    </div>
    <?php
}

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

    $epic_no = '';
    $message = '';
    $alertType = '';
    $response = [];

    if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['check_status'])) {

        $epic_no = strtoupper(trim($_POST['epic_no'] ?? ''));

        if ($epic_no === '') {
            awal_alert_msg("Please enter Voter Number!", 'error');
        } else {

            $response = callVoterStatusApi($epic_no);

            if (($response['status'] ?? '') === 'success') {
                $message = $response['message'] ?? 'Status fetched successfully';
                $alertType = 'success';
            } else {
                $message = $response['message'] ?? 'Status check failed';
                $alertType = 'danger';
            }
        }
    }
?>

<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 == 'success') ? 'success' : 'danger' ?> text-center">
                        <?= htmlspecialchars($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 d-flex justify-content-between">
                        <button type="button" class="btn btn-secondary">
                            Free Status
                        </button>

                        <button type="submit" name="check_status" class="btn btn-primary">
                            Check Status
                        </button>

                        <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#showDetailsModal">
                            Show
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<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 <?= ($alertType == 'success') ? 'bg-success' : 'bg-danger' ?> text-white">
        <h5 class="modal-title" id="showDetailsModalLabel">Status Details</h5>
        <button type="button" class="close text-white" data-dismiss="modal">
          <span>&times;</span>
        </button>
      </div>

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

            <?php
            showField("Voter Number", $response['epic'] ?? $epic_no);
            showField("Name", $response['name'] ?? '');
            showField("Database Mobile", $response['database_mobile'] ?? '');
            showField("Main API Mobile", $response['main_api_mobile'] ?? '');
            showField("Reference No", $response['refid'] ?? '');
            showField("State", $response['state'] ?? '');
            showField("State Code", $response['stateCd'] ?? '');
            showField("Payment", $response['payment'] ?? '');
            showField("Message", $response['message'] ?? '', 12);
            showField("Time", $response['time'] ?? '');
            ?>

          </form>
        <?php } else { ?>
          <p>No details fetched yet.</p>
        <?php } ?>
      </div>

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

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

<script>
<?php if (!empty($epic_no) && !empty($response)) { ?>
$(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");
?>