<?php
session_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'];
$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'];
$parent    = $udata['parent'];

/* ================= SERVICE FEE ================= */
$fee = 0;

$q = mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='dl_gf_instant'");
if ($r = mysqli_fetch_assoc($q)) {
    $fee = (float)$r['rate'];
}

/* ================= FORM SUBMIT ================= */
if (isset($_POST['submit_dl'])) {

    $dlno     = strtoupper(trim($_POST['dlno']));
    $dob      = trim($_POST['dob']);
    $cardtype = (int)$_POST['cardtype'];

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

        /* ================= NEW API CALL ================= */
        $api_url = "https://maxxapi.site/dl_pdf"
            . "?api_key=demo"
            . "&dlno=" . urlencode($dlno)
            . "&dob=" . urlencode($dob)
            . "&cardtype=" . urlencode($cardtype);

        $ch = curl_init();

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

        $res = curl_exec($ch);

        if (curl_errno($ch)) {
            $errorMsg = "Curl Error: " . curl_error($ch);
        }

        curl_close($ch);

        $data = json_decode($res, true);

        /* ================= VALIDATE RESPONSE ================= */
        if (!$data || !isset($data['status'])) {
            $errorMsg = "Invalid API response.";
        }
        elseif ($data['status'] != "200") {
            $errorMsg = $data['message'] ?? "DL Not found.";
        }
        else {

            /* ================= PDF FROM API ================= */
            $api_pdf_link = $data['pdf_link'] ?? '';
            $pdfRaw = $data['pdf'] ?? '';

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

            $mod4 = strlen($pdfRaw) % 4;
            if ($mod4) {
                $pdfRaw .= str_repeat('=', 4 - $mod4);
            }

            $pdfContent = base64_decode($pdfRaw, true);

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

                /* ================= SAVE LOCAL PDF ================= */
                $dir = "uploads/dl";
                if (!is_dir($dir)) {
                    mkdir($dir, 0755, true);
                }

                $file = "DL_" . $dlno . "_" . time() . ".pdf";
                $path = $dir . "/" . $file;

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

                    /* ================= TRANSACTION ================= */
                    mysqli_begin_transaction($ahk_conn);

                    try {

                        $order_id = mt_rand(100000000000, 999999999999);
                        $app_no   = $data['application_no'] ?? '';
                        $date     = date("Y-m-d H:i:s");
                        $newBal   = $wallet - $fee;

                        /* Deduct wallet */
                        mysqli_query($ahk_conn,
                            "UPDATE users SET balance='$newBal' WHERE phone='$username'"
                        );

                        /* Save DL history (store API link OR local link) */
                        mysqli_query($ahk_conn, "
                            INSERT INTO dl_history
                            (number, dob, tnsid, apiid, type, link, custno, amount, date_time)
                            VALUES
                            ('$dlno','$dob','$order_id','$app_no','dl','$api_pdf_link','$username','$fee','$date')
                        ");

                        /* Wallet history */
                        mysqli_query($ahk_conn, "
                            INSERT INTO wallethistory
                            (userid, amount, balance, purpose, status, type)
                            VALUES
                            ('$username','$fee','$newBal','DL Download 2.0',1,'Debit')
                        ");

                        /* ================= 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')
                                    ");
                                }
                            }
                        }

                        mysqli_commit($ahk_conn);

                        $successMsg = "DL PDF generated successfully.";

                    } catch (Exception $e) {
                        mysqli_rollback($ahk_conn);
                        $errorMsg = "Database error occurred.";
                    }
                }
            }
        }
    }
}

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

<!DOCTYPE html>
<html>
<head>
<title>DL 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>
</head>

<body class="bg-light">

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

<!-- FORM -->
<div class="col-md-4">
<div class="card shadow-sm">
<div class="card-body">

<h5 class="mb-3">📄 DL PDF Download</h5>

<form method="POST">

<input class="form-control mb-2" name="dlno" placeholder="DL Number" required>

<input class="form-control mb-2" name="dob" placeholder="DD-MM-YYYY" required>

<select class="form-select mb-3" name="cardtype">
<option value="1">Classic</option>
<option value="2" selected>Smart</option>
</select>

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

<button name="submit_dl" class="btn btn-primary w-100">
Generate DL
</button>

</form>

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

<!-- HISTORY -->
<div class="col-md-8">
<div class="card shadow-sm">
<div class="card-body">

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

<table class="table table-bordered text-center">
<thead class="table-dark">
<tr>
<th>DL</th>
<th>DOB</th>
<th>Application</th>
<th>Txn</th>
<th>PDF</th>
</tr>
</thead>

<tbody>

<?php if (mysqli_num_rows($history)): ?>

<?php while ($r = mysqli_fetch_assoc($history)): ?>
<tr>
<td><?= $r['number'] ?></td>
<td><?= $r['dob'] ?></td>
<td><?= $r['apiid'] ?></td>
<td><?= $r['tnsid'] ?></td>
<td>
<a target="_blank"
   class="btn btn-success btn-sm"
   href="<?= $r['link'] ?>">
   Open PDF
</a>
</td>
</tr>
<?php endwhile; ?>

<?php else: ?>
<tr><td colspan="5">No Records</td></tr>
<?php endif; ?>

</tbody>
</table>

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

</div>
</div>

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

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

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

</body>
</html>