<?php
session_start();
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');
include('header.php');

if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['phone'];

/* ================= USER DATA ================= */

$udata = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'")
);

$wallet = (float)$udata['balance'];

/* ================= SERVICE RATE ================= */

$feeRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='aadhaar_to_ration'")
);

$fee = (float)($feeRow['rate'] ?? 4);

$errorMsg = "";
$successData = null;

/* ================= VERIFY AADHAAR ================= */

if (isset($_POST['find_ration'])) {

    $uidNumber = preg_replace('/[^0-9]/', '', $_POST['uidNumber']);

    /* ================= VALIDATION ================= */

    if (!preg_match('/^[0-9]{12}$/', $uidNumber)) {

        $errorMsg = "Invalid Aadhaar Number.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } else {

        /* ================= API CALL ================= */

        $api_key = "demooo";

        $api_url = "https://maxxapi.site/aadhar2ration?api_key=".$api_key."&uidNumber=".$uidNumber;

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false
        ]);

        $response = curl_exec($ch);

        curl_close($ch);

        $responseData = json_decode($response, true);

        /* ================= API FAILED ================= */

        if (
            !$responseData ||
            !isset($responseData['status']) ||
            $responseData['status'] != '200'
        ) {

            $errorMsg = $responseData['message'] ?? "No data found";

        } else {

            /* ================= RESPONSE DATA ================= */

            $aadhaar_number = $responseData['aadhaar_number'] ?? '';
            $ration_number  = $responseData['ration_number'] ?? '';
            $tracking_id    = $responseData['tracking_id'] ?? '';
            $response_time  = $responseData['response_time'] ?? '';
            $data_source    = $responseData['data_source'] ?? 'api';

            $date = date("Y-m-d H:i:s");

            /* ================= WALLET DEDUCT ================= */

            $new_balance = $wallet - $fee;

            mysqli_query(
                $ahk_conn,
                "UPDATE users
                 SET balance='$new_balance'
                 WHERE phone='$username'"
            );

            /* ================= SAVE HISTORY ================= */

            mysqli_query(
                $ahk_conn,
                "INSERT INTO ration_history
                (
                    aadhaar_no,
                    ration_no,
                    username,
                    response,
                    date
                )
                VALUES
                (
                    '$aadhaar_number',
                    '$ration_number',
                    '$username',
                    '".mysqli_real_escape_string($ahk_conn, json_encode($responseData))."',
                    '$date'
                )"
            );

            /* ================= WALLET HISTORY ================= */

            mysqli_query(
                $ahk_conn,
                "INSERT INTO wallethistory
                (
                    userid,
                    amount,
                    balance,
                    purpose,
                    status,
                    type
                )
                VALUES
                (
                    '$username',
                    '$fee',
                    '$new_balance',
                    'Aadhaar To Ration',
                    '1',
                    'Debit'
                )"
            );

            /* ================= SUCCESS DATA ================= */

            $successData = [
                "status" => "200",
                "aadhaar_number" => $aadhaar_number,
                "ration_number" => $ration_number,
                "tracking_id" => $tracking_id,
                "response_time" => $response_time,
                "data_source" => $data_source
            ];
        }
    }
}

/* ================= HISTORY ================= */

$history = mysqli_query(
    $ahk_conn,
    "SELECT * FROM ration_history
     WHERE username='$username'
     ORDER BY id DESC"
);
?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Aadhaar To Ration</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>

body{
    background:#f4f7fb;
}

.card-box{
    background:#fff;
    padding:25px;
    border-radius:18px;
    box-shadow:0 8px 25px rgba(0,0,0,.08);
}

.verify-btn{
    height:48px;
    border-radius:10px;
    font-weight:600;
}

.table th{
    white-space:nowrap;
}

</style>

</head>

<body>

<div class="container py-4">

<div class="row g-4">

<!-- ================= FORM ================= -->

<div class="col-lg-4">

<div class="card-box">

<h4 class="text-center text-primary mb-4">
Aadhaar To Ration
</h4>

<form method="POST">

<input
type="text"
name="uidNumber"
maxlength="12"
required
class="form-control text-center mb-3"
placeholder="Enter Aadhaar Number"
oninput="this.value=this.value.replace(/[^0-9]/g,'')"
>

<div class="alert alert-warning text-center">

Verification Fee :
<b>₹<?= number_format($fee,2) ?></b>

</div>

<button
type="submit"
name="find_ration"
class="btn btn-primary w-100 verify-btn"
>

Find Ration Number

</button>

</form>

</div>

</div>

<!-- ================= HISTORY ================= -->

<div class="col-lg-8">

<div class="card-box">

<h5 class="mb-3">
Search History
</h5>

<div class="table-responsive">

<table id="rationTable" class="table table-bordered table-hover text-center align-middle">

<thead class="table-dark">

<tr>
<th>ID</th>
<th>Date</th>
<th>Aadhaar</th>
<th>Ration Number</th>
<th>Slip</th>
</tr>

</thead>

<tbody>

<?php while ($r = mysqli_fetch_assoc($history)) { ?>

<tr>

<td>#<?= $r['id'] ?></td>

<td>
<?= date('d M Y h:i A', strtotime($r['date'])) ?>
</td>

<td><?= htmlspecialchars($r['aadhaar_no']) ?></td>

<td><?= htmlspecialchars($r['ration_no']) ?></td>

<td>

<button
class="btn btn-sm btn-info"
onclick='viewSlip(<?= json_encode($r) ?>)'
>

View

</button>

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>

<!-- ================= ERROR ALERT ================= -->

<?php if ($errorMsg) { ?>

<script>

Swal.fire({
    icon:'error',
    title:'Error',
    text:'<?= $errorMsg ?>'
});

</script>

<?php } ?>

<!-- ================= SUCCESS ALERT ================= -->

<?php if ($successData) { ?>

<script>

Swal.fire({

    icon:'success',

    title:'Ration Number Found',

    html:`

    <div style="text-align:left">

    <p><b>Aadhaar :</b> <?= $successData['aadhaar_number'] ?></p>

    <p><b>Ration Number :</b> <?= $successData['ration_number'] ?></p>


    <p><b>Data Source :</b> <?= $successData['data_source'] ?></p>

    </div>

    `

});

</script>

<?php } ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>

$('#rationTable').DataTable();

function viewSlip(d){

    Swal.fire({

        title:'Aadhaar To Ration Slip',

        html:`

        <div style="text-align:left">

        <p><b>Aadhaar :</b> ${d.aadhaar_no}</p>

        <p><b>Ration Number :</b> ${d.ration_no}</p>

        <p><b>Date :</b> ${d.date}</p>

        </div>

        `,

        showCancelButton:true,
        confirmButtonText:'Print'

    }).then((result)=>{

        if(result.isConfirmed){

            window.print();

        }

    });

}

</script>

</body>
</html>