<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

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

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

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

/* ================= USER DATA ================= */
$udata = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'"));
$wallet = (float)$udata['balance'];
$parent = $udata['parent']; // Parent info

/* ================= SERVICE RATE ================= */
$rateRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='ll'")
);
$fee = (float)($rateRow['rate'] ?? 0);

/* ================= FORM SUBMIT ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $application = trim($_POST['application']);
    $dob = trim($_POST['dob']); // dd-mm-yyyy

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

        $api_key = "TNG-API-1731b6-001c9e-0c12ce-bb1787-8288bf";
        $api_url = "https://secure.thenextgenapi.co.in/api/Lerning-Licence-Pdf/v1/Lerning-license-to-pdf-verification"
            . "?apikey=$api_key&value=$application&type=applnum&dob=$dob";

        $ch = curl_init($api_url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);

        if (!$data) {
            $errorMsg = "Invalid API response.";
        }
        elseif (($data['sampleCode'] ?? '') !== "200") {
            $errorMsg = $data['message'] ?? $data['Message'] ?? "API request failed.";
        }
        elseif (empty($data['pdf'])) {
            $errorMsg = "PDF not received from API.";
        }
        else {

            /* ================= PDF PROCESS ================= */
            $pdf = $data['pdf'];

            if (strpos($pdf, ',') !== false) {
                $pdf = explode(',', $pdf, 2)[1];
            }

            $pdf = html_entity_decode($pdf);
            $pdf = str_replace('\\/', '/', $pdf);
            $pdf = preg_replace('/\s+/', '', $pdf);

            $content = base64_decode($pdf);

            if ($content === false || substr($content, 0, 4) !== "%PDF") {
                $errorMsg = "Invalid PDF data received.";
            } else {

                $dir = "new/ll";
                if (!is_dir($dir)) mkdir($dir, 0755, true);

                $file = "LL_" . $data['applNum'] . "_" . time() . ".pdf";
                $path = "$dir/$file";

                if (!file_put_contents($path, $content)) {
                    $errorMsg = "Unable to save PDF file.";
                } else {

                    /* ================= WALLET UPDATE ================= */
                    $newBal = $wallet - $fee;
                    $order_id = mt_rand(100000000000, 999999999999);

                    $up = $ahk_conn->prepare("UPDATE users SET balance=? WHERE phone=?");
                    $up->bind_param("ds", $newBal, $username);
                    $up->execute();

                    /* ================= HISTORY INSERT ================= */
                    $his = $ahk_conn->prepare("
                        INSERT INTO llhistory (number, tnsid, apiid, type, link, custno)
                        VALUES (?, ?, ?, 'll', ?, ?)
                    ");
                    $his->bind_param(
                        "sssss",
                        $data['applNum'],
                        $order_id,
                        $data['applNum'],
                        $path,
                        $username
                    );
                    $his->execute();

                    /* ================= WALLET HISTORY ================= */
                    $purpose = "Learning Licence PDF";
                    $status = 1;
                    $type = "Debit";

                    $wh = $ahk_conn->prepare("
                        INSERT INTO wallethistory (userid, amount, balance, purpose, status, type)
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $wh->bind_param(
                        "sddsis",
                        $username,
                        $fee,
                        $newBal,
                        $purpose,
                        $status,
                        $type
                    );
                    $wh->execute();

                    /* ================= PARENT COMMISSION 15% ================= */
                    if (!empty($parent) && strtolower($parent) !== 'admin') {
                        $commission = round($fee * 0.15, 2);
                        if ($commission > 0) {
                            $pRes = mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='$parent' LIMIT 1");
                            if (mysqli_num_rows($pRes) > 0) {
                                $pData = mysqli_fetch_assoc($pRes);
                                $parent_balance = (float)$pData['balance'];
                                $parent_newbalance = $parent_balance + $commission;

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

                                mysqli_query($ahk_conn, "
                                    INSERT INTO wallethistory
                                    (userid, amount, balance, purpose, status, type)
                                    VALUES
                                    ('$parent', '$commission', '$parent_newbalance', 'Commission from $username', 1, 'Credit')
                                ");
                            }
                        }
                    }

                    /* ================= SUCCESS ================= */
                    $successMsg = "Learning Licence PDF generated successfully.";
                    $redirectAfterSuccess = true;
                }
            }
        }
    }
}

/* ================= HISTORY ================= */
$hist = $ahk_conn->prepare("SELECT * FROM llhistory WHERE custno=? AND type='ll' ORDER BY id DESC");
$hist->bind_param("s", $username);
$hist->execute();
$history = $hist->get_result();
?>

<!DOCTYPE html>
<html>
<head>
<title>LL PDF Download</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
.card-box{
    background:#fff;
    padding:25px;
    border-radius:15px;
    box-shadow:0 8px 25px rgba(0,0,0,.1)
}
</style>
</head>

<body class="bg-light">

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

<!-- FORM -->
<div class="col-lg-4">
<div class="card-box">
<h5 class="text-primary mb-3">📄 Learning Licence PDF</h5>

<form method="POST" id="llForm">
<input name="application" required class="form-control mb-3" placeholder="Application Number">
<input name="dob" required class="form-control mb-3" placeholder="DD-MM-YYYY">

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

<button type="submit" id="submitBtn" class="btn btn-primary w-100">
Generate PDF
</button>
</form>
</div>
</div>

<!-- HISTORY -->
<div class="col-lg-8">
<div class="card-box">
<table class="table table-bordered text-center align-middle">
<thead class="table-dark">
<tr>
<th>Application No</th>
<th>Txn ID</th>
<th>View</th>
</tr>
</thead>
<tbody>
<?php if ($history->num_rows): ?>
<?php while ($r = $history->fetch_assoc()): ?>
<tr>
<td><?= $r['number'] ?></td>
<td><?= $r['tnsid'] ?></td>
<td>
<a target="_blank" class="btn btn-success btn-sm"
href="down.php?file=<?= urlencode($r['link']) ?>">
Open PDF
</a>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="3" class="text-muted">No records found</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>

</div>
</div>

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

<?php if ($redirectAfterSuccess): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Success',
    text: <?= json_encode($successMsg) ?>
}).then(() => {
    window.location.href = "llpdf.php";
});
</script>
<?php endif; ?>

<script>
document.getElementById("llForm").addEventListener("submit", function () {
    const btn = document.getElementById("submitBtn");
    btn.disabled = true;
    btn.innerHTML = "Processing...";
});
</script>

<?php include('footer.php'); ?>
</body>
</html>
