<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='aadhar_pvc_pdf_fee' "));
$fee = $price['price'];
$resdata = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'];
    $password = $_POST['password'];
    $phone = $_POST['phone'];
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;
    $balance = $udata['balance'];

    if (!empty($_FILES['file']['name'])) {
        $allowedMime = ['application/pdf'];
        $fileMime = mime_content_type($_FILES['file']['tmp_name']);

        if (!in_array($fileMime, $allowedMime)) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({ icon: 'error', title: 'Invalid File', text: 'Please upload a valid PDF file.', timer: 3000 });
            </script>";
            exit;
        }

        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileName = uniqid() . '_' . basename($_FILES['file']['name']);
        $uploadPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
            $file = "https://" . $_SERVER['HTTP_HOST'] . "/admin/uploads/" . $fileName;

            if ($balance >= $fee) {
                $url = "$tng_apiurl/aadhar_pvc_card_pdf_verification?file=$file&type=$type&phone=$phone&password=$password&apikey=$tng_apikey";

                $curl = curl_init();
                curl_setopt_array($curl, [
                    CURLOPT_URL => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_TIMEOUT => 30,
                ]);
                $response = curl_exec($curl);
                curl_close($curl);

                $resdata = json_decode($response, true);

                if ($resdata['Message'] === 'Failed') {
                    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                    <script>
                        Swal.fire({ icon: 'error', title: 'Error', text: '{$resdata['error']}', timer: 5000 });
                        setTimeout(() => { window.location = ''; }, 5000);
                    </script>";
                } elseif ($resdata['sampleCode'] === "200") {
                     date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
                $parentPhone = $udata['parent'] ?? null;
        addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Aadhar Pvc Pdf Verification");
           $debit = mysqli_query($ahk_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
           $database = mysqli_query($ahk_conn, "INSERT INTO `aadhar_pvc_pdf`(`name`, `username`, `aadhar`, `pdf`, `date`) VALUES ('{$resdata['name']}','{$udata['phone']}','{$resdata['aadhar']}','{$resdata['pdf']}','$timestamp')");
            $updatehistory = mysqli_query($ahk_conn, "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('$appliedby','$fee','$debit_fee','Aadhar PVC  pDF','1','Debit')");
     echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'success', title: 'Success!', text: 'Pdf Generate Sucessfull Redirecting To List!', timer: 2000 });
            setTimeout(() => { window.location = 'aadhar_pvc_pdf_list.php'; }, 1200);
        </script>";
                    }
            } else {
                echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                <script>
                    Swal.fire({ icon: 'error', title: 'Wallet Balance is Low!', text: 'Please Recharge Now!', timer: 2000 });
                    setTimeout(() => { window.location = 'wallet.php'; }, 1200);
                </script>";
            }
        } else {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({ icon: 'error', title: 'Upload Failed', text: 'File could not be uploaded. Check folder permissions.', timer: 4000 });
            </script>";
        }
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'error', title: 'Invalid File', text: 'Please upload a valid PDF file.', timer: 3000 });
        </script>";
    }
}
?>

<div class="content-wrap">
 <div class="main">
<div class="page-wrapper">
    <div class="page-content">
        <div class="mobile-menu-overlay"></div>
        <div class="main-container">
            <div class="col-lg-12">
                <div class="card" style="margin-left: 10px; padding-left: 30px; padding-top: 12px; box-shadow: 1px 5px 5px 5px;">
                    <div class="stat-widget-two">
                        <div class="stat-content">
                            <div class="stat-text">
                                <div class="container-fluid">
                                    <div class="row">
                                        <div class="col-lg-4 col-md-6 col-sm-6">
                                            <div class="card">
                                                <div class="card-body">
                                                    <div class="alert alert-info" role="alert">
                                                         Aadhar Pvc Card PDF Verification
                                                    </div>
                                                    <form action="" method="POST" enctype="multipart/form-data" class="row g-3">
                                                        <div class="card-body">
                                                            <div class="col-md-12">
                                                                <div class="form-group">
                                                                    <label for="password">Enter Password </label>
                                                                    <input name="password" type="text" id="password" placeholder="Enter Password " class="form-control" required>
                                                                </div>
                                                                <div class="form-group mt-2">
                                                                    <label>Upload UIDAI PDF</label>
                                                                    <input type="file" name="file" class="form-control" accept=".pdf" required>
                                                                </div>
                                                                <div class="form-group mt-2">
                                                                    <label for="type">Select PVC Option</label>
                                                                    <select name="type" class="form-control" required>
                                                                        <option value="true">NEW PVC</option>
                                                                        <option value="false">OLD PVC</option>
                                                                    </select>
                                                                </div>
                                                                <div class="form-group mt-2">
                                                                    <label for="phone">Select Phone Number</label>
                                                                    <select name="phone" class="form-control" required>
                                                                        <option value="true">Yes</option>
                                                                        <option value="false">No</option>
                                                                    </select>
                                                                </div>
                                                                <hr>
                                                                <div class="row mt-3">
                                                                  <div class="col-md-6">
                                                                       <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                                                                   </div>
                                                                   <div class="col-md-6 text-end">
                                                                       <button class="btn btn-primary" name="submit" id="submit"><i class="fa fa-check-circle"></i> Submit</button>
                                                                   </div>
                                                               </div>
                                                            </div>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>

                                        <?php if (isset($resdata['sampleCode']) && $resdata['sampleCode'] === "200") { ?>
                                            <div class="col-lg-8 col-md-6 col-sm-6">
                                                <div class="card" style="background-color: #E8F6F3;">
                                                    <div class="card-body">
                                                        <h5 class="mb-3">Aadhar Pvc Card Pdf  </h5>
                                                        <table class="table table-bordered table-striped">
                                                            <tbody>
                                                                <tr><th>Name </th><td><?php echo htmlspecialchars($resdata['name']); ?></td></tr>
                                                                <tr><th>Year</th><td><?php echo htmlspecialchars($resdata['year']); ?></td></tr>
                                                                <tr><th>Message</th><td><?php echo htmlspecialchars($resdata['message']); ?></td></tr>
                                                                <tr><th>Front Image</th><td><a href="<?php echo $resdata['front']; ?>" download="<?php echo htmlspecialchars($resdata['name']); ?>.jpeg" target="_blank" class="btn btn-success">Download Front Image</a></td></tr>
                                                                <tr><th>Back Image</th><td><a href="<?php echo $resdata['back']; ?>" download="<?php echo htmlspecialchars($resdata['name']); ?>.jpeg" target="_blank" class="btn btn-success">Download Back Image</a></td></tr>
                                                                <tr><th>PDF</th><td><a href="<?php echo $resdata['pdf']; ?>" download="<?php echo htmlspecialchars($resdata['name']); ?>.pdf" target="_blank" class="btn btn-success">Download PDF</a></td></tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                         <?php } ?>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <br><br><br><br>
            </div>
        </div>
    </div>
</div>
<?php include('../template/ahkweb/footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
