<?php

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

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

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 ================= */

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

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

/* ================= RC DOWNLOAD ================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $rcno = strtoupper(
        preg_replace('/[^A-Z0-9]/', '', $_POST['rc'] ?? '')
    );

    $cardtype = (int)($_POST['cardtype'] ?? 1);
    $chiptype = (int)($_POST['chiptype'] ?? 1);

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

    if (empty($rcno)) {

        $errorMsg = "Vehicle number required.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } else {

        /* ================= API URL ================= */

        $api_url =
            "https://www.apizone.info/api/rc_pdf/rc.php".
            "?api_key=".$apikey.
            "&rcno=".$rcno.
            "&cardtype=".$cardtype.
            "&chiptype=".$chiptype;

        /* ================= CURL ================= */

        $curl = curl_init();

        curl_setopt_array($curl, [

            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",

            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false

        ]);

        $response = curl_exec($curl);

        /* ================= CURL ERROR ================= */

        if ($response === false) {

            $errorMsg = curl_error($curl);

            curl_close($curl);

        } else {

            curl_close($curl);

            /* ================= API RESPONSE ================= */

            $data = json_decode($response, true);

            if (!$data) {

                $errorMsg = "Invalid API response.";

            } elseif (($data['status'] ?? '') != "200") {

                $errorMsg = $data['message'] ?? "RC verification failed";

            } else {

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

                $vehicle_number = strtoupper(
                    $data['rcno'] ?? $rcno
                );

                $owner_name = strtoupper(
                    $data['name'] ?? ''
                );

                $application_no =
                    $data['application_no'] ?? '';

                /* ================= PDF GET ================= */

                $pdf = '';

                if (!empty($data['pdf'])) {

                    $pdf = $data['pdf'];

                } elseif (!empty($data['pdf_base64'])) {

                    $pdf = $data['pdf_base64'];

                } elseif (!empty($data['base64'])) {

                    $pdf = $data['base64'];
                }

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

                if (empty($pdf)) {

                    $errorMsg = "PDF data missing from API.";

                } else {

                    /* ================= REMOVE PREFIX ================= */

                    $pdf_clean = str_replace(
                        'data:application/pdf;base64,',
                        '',
                        $pdf
                    );

                    /* ================= PDF FOLDER ================= */

                    $folder = "uploads/rc_pdf/";

                    if (!is_dir($folder)) {

                        mkdir($folder, 0777, true);
                    }

                    /* ================= FILE NAME ================= */

                    $file_name =
                        $vehicle_number .
                        "_" .
                        time() .
                        ".pdf";

                    $file_path = $folder . $file_name;

                    /* ================= SAVE PDF ================= */

                    $pdf_binary = base64_decode($pdf_clean);

                    if (!$pdf_binary) {

                        $errorMsg = "Invalid PDF base64 data.";

                    } else {

                        file_put_contents(
                            $file_path,
                            $pdf_binary
                        );

                        /* ================= PDF URL ================= */

                        $pdf_url =
                            "https://" .
                            $_SERVER['HTTP_HOST'] .
                            "/" .
                            $file_path;

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

                        $oldBal = $wallet;

                        $newBal = $wallet - $fee;

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

                        if (!$walletUpdate) {

                            $errorMsg = mysqli_error($ahk_conn);

                        } else {

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

                            $txn_status = 1;

                            $type = "Debit";

                            $purpose = "RC PDF API";

                            $stmt = $ahk_conn->prepare("
                                INSERT INTO wallethistory
                                (
                                    userid,
                                    amount,
                                    balance,
                                    purpose,
                                    status,
                                    type,
                                    oldbalance,
                                    new_balance
                                )
                                VALUES
                                (?, ?, ?, ?, ?, ?, ?, ?)
                            ");

                            $stmt->bind_param(
                                "sddsisdd",
                                $username,
                                $fee,
                                $newBal,
                                $purpose,
                                $txn_status,
                                $type,
                                $oldBal,
                                $newBal
                            );

                            $stmt->execute();

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

                            $order_id = rand(1000000000, 9999999999);

                            mysqli_query(
                                $ahk_conn,
                                "INSERT INTO history
                                (
                                    number,
                                    tnsid,
                                    apiid,
                                    type,
                                    link,
                                    custno
                                )
                                VALUES
                                (
                                    '$vehicle_number',
                                    '$order_id',
                                    '$application_no',
                                    'rc',
                                    '$file_path',
                                    '$username'
                                )"
                            );

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

                            $successMsg = "RC PDF generated successfully.";

                            $redirectAfterSuccess = true;
                        }
                    }
                }
            }
        }
    }
}

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

$hist = $ahk_conn->prepare("
    SELECT * FROM history
    WHERE custno=? AND type='rc'
    ORDER BY id DESC
");

$hist->bind_param("s", $username);

$hist->execute();

$history = $hist->get_result();

?>

<!DOCTYPE html>
<html>
<head>

<title>RC 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">

<!-- LEFT FORM -->

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

<div class="card-box">

<h5 class="text-primary mb-3">🛻 RC PDF Download</h5>

<form method="POST" id="rcForm">

<input
    type="text"
    name="rc"
    required
    class="form-control mb-3 text-uppercase"
    placeholder="PB55W2513"
    maxlength="15"
    oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9]/g,'')"
>

<select name="cardtype" class="form-select mb-3">
    <option value="1">Old Card</option>
    <option value="2" selected>New Card</option>
</select>

<select name="chiptype" class="form-select mb-3">
    <option value="1" selected>Chip</option>
    <option value="2">Non-Chip</option>
</select>

<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 RC
</button>

</form>

</div>

</div>

<!-- RIGHT 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>Vehicle</th>
    <th>Application</th>
    <th>Txn ID</th>
    <th>View</th>
</tr>

</thead>

<tbody>

<?php if ($history->num_rows): ?>

    <?php while ($r = $history->fetch_assoc()): ?>

        <tr>

            <td class="fw-bold">
                <?= htmlspecialchars($r['number']) ?>
            </td>

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

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

            <td>
                <a
                    target="_blank"
                    class="btn btn-success btn-sm"
                    href="download.php?file=<?= urlencode($r['link']) ?>"
                >
                    Open PDF
                </a>
            </td>

        </tr>

    <?php endwhile; ?>

<?php else: ?>

<tr>
    <td colspan="4" class="text-muted">
        No RC downloads
    </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 (!empty($redirectAfterSuccess)): ?>

<script>

Swal.fire({
    icon: 'success',
    title: 'Success',
    text: <?= json_encode($successMsg) ?>,
    confirmButtonText: 'Continue'
}).then(() => {
    window.location.href = "rc_pdf.php";
});

</script>

<?php endif; ?>

<script>

document.getElementById("rcForm").addEventListener("submit", function () {

    const btn = document.getElementById("submitBtn");

    btn.disabled = true;

    btn.innerHTML = "Processing...";

});

</script>

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

</body>
</html>