<?php
session_start();

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

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

$username = $_SESSION['phone'];
$errorMsg = null;
$successMsg = null;

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

$wallet    = floatval($udata['balance']);
$user_id   = $udata['id'];
$usertype  = $udata['type'];
$name_user = $udata['name'];

/* ================= SERVICE RATE ================= */
$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='ration_pdf'"));
$fee = $price ? floatval($price['rate']) : 0.00;

/* ================= HANDLE FORM ================= */
if (isset($_POST['A2A']) && $_POST['A2A'] == "Apizone") {

    $rationno = strtoupper(trim(preg_replace('/\s+/', '', $_POST['rc'])));
    $cardtype = (int)$_POST['cardtype'];

    if ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance. Charge is ₹$fee.";
    } else {

        /* ================= NEW API ================= */
        $api_url = "https://maxxapi.site/ration"
            . "?api_key=demo"
            . "&rationno=" . urlencode($rationno)
            . "&card_type=" . urlencode($cardtype);

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        if (!$response) {
            $errorMsg = "API connection failed.";
        } else {

            $data = json_decode($response, true);

            if (!$data || $data['status'] != "200") {
                $errorMsg = $data['message'] ?? "Ration verification failed.";
            } else {

                /* ================= PDF ================= */
                $pdfBase64 = $data['pdf'] ?? '';
                $pdfBase64 = preg_replace('#^data:application/pdf;base64,#', '', $pdfBase64);
                $pdfBase64 = str_replace(["\r", "\n", " "], '', $pdfBase64);

                $pdfContent = base64_decode($pdfBase64, true);

                if ($pdfContent === false) {
                    $errorMsg = "PDF decode failed.";
                } else {

                    /* ================= SAVE FILE ================= */
                    $dir = __DIR__ . "/new/new";
                    if (!is_dir($dir)) mkdir($dir, 0755, true);

                    $filename = "RT_" . preg_replace("/[^A-Za-z0-9]/", "", $rationno) . "_" . time() . ".pdf";
                    $fullPath = $dir . "/" . $filename;
                    $dbPath = "new/new/" . $filename;

                    file_put_contents($fullPath, $pdfContent);

                    /* ================= BALANCE ================= */
                    $new_balance = $wallet - $fee;
                    $date = date("Y-m-d H:i:s");

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

                    /* ================= HISTORY ================= */
                    $order_id = mt_rand(1000000000, 9999999999);
                    $app_no = $data['application_no'] ?? '';

                    mysqli_query($ahk_conn, "
                        INSERT INTO rthistory
                        (number, tnsid, apiid, type, link, custno, date)
                        VALUES
                        ('$rationno','$order_id','$app_no','Ration','$dbPath','$username','$date')
                    ");

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

                    $successMsg = "Ration PDF Generated Successfully.";
                }
            }
        }
    }
}

/* ================= HISTORY ================= */
$historyQuery = mysqli_query($ahk_conn, "SELECT * FROM rthistory WHERE custno='$username' ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ration Card PDF</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
.section-header { font-size: 14px; font-weight: 800; color: #3182ce; text-transform: uppercase; margin-bottom: 20px; display: table; background: #ebf8ff; padding: 8px 20px; border-radius: 50px; }
.card-custom { border-radius: 15px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
</style>

</head>

<body class="bg-light">

<div class="container-fluid py-4">
<div class="row g-4">

<!-- LEFT FORM (OLD DESIGN) -->
<div class="col-lg-4">
<span class="section-header">Ration Services</span>

<div class="card card-custom p-4 bg-white">

<h5 class="text-center mb-4 fw-bold">Download Ration PDF</h5>

<form method="POST">
<input type="hidden" name="A2A" value="Apizone" />

<div class="mb-3">
<label class="form-label small fw-bold text-secondary">Ration Number</label>
<input type="text" name="rc" required class="form-control text-center fw-bold"
placeholder="Enter Ration Number"
oninput="this.value=this.value.replace(/\s/g,'').toUpperCase()">
</div>

<div class="mb-3">
<label class="form-label small fw-bold text-secondary">Design Type</label>
<select name="cardtype" class="form-select">
<option value="1">Photo Design</option>
<option value="2" selected>Simple Design</option>
</select>
</div>

<div class="alert alert-warning py-2 text-center small fw-bold">
Service Fee: ₹<?= number_format($fee,2) ?>
</div>

<button type="submit" class="btn btn-primary w-100 btn-lg shadow-sm">
Generate PDF Now
</button>

</form>

</div>
</div>

<!-- RIGHT HISTORY (OLD DESIGN) -->
<div class="col-lg-8">
<div class="card shadow">
<div class="card-header bg-primary text-white">
<h4 class="mb-0">Your Download History</h4>
</div>

<div class="card-body">

<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>Date</th>
<th>Ration No</th>
<th>Transaction ID</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>

<tbody>
<?php if(mysqli_num_rows($historyQuery)>0): ?>
<?php while($row = mysqli_fetch_assoc($historyQuery)): ?>
<tr>
<td><?= $row['date'] ?></td>
<td><?= htmlspecialchars($row['number']) ?></td>
<td><?= htmlspecialchars($row['tnsid']) ?></td>
<td><?= htmlspecialchars($row['type']) ?></td>
<td>
<a href="<?= $row['link'] ?>" target="_blank" class="btn btn-sm btn-success">
Download PDF
</a>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="5" class="text-center text-muted py-3">No records found</td>
</tr>
<?php endif; ?>
</tbody>

</table>

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

</div>
</div>

<!-- SUCCESS -->
<?php if ($successMsg): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Success',
    text: <?= json_encode($successMsg) ?>
});
</script>
<?php endif; ?>

<!-- ERROR -->
<?php if ($errorMsg): ?>
<script>
Swal.fire({
    icon: 'error',
    title: 'Error',
    text: <?= json_encode($errorMsg) ?>
});
</script>
<?php endif; ?>

<?php include('footer.php'); ?>

</body>
</html>