<?php

session_start();
error_reporting(1);
include_once('includes/db.php');

if (!isset($_SESSION['alogin'])) {
    header('location:login.php');
    die();
}

if (isset($_FILES['pdf'])) {
    if ($_FILES['pdf']['type'] === "application/pdf") {
        // Create PDF name and path
        $pdf = "pdf/" . md5(rand(1111, 9999)) . ".pdf";

        // Move uploaded file to the server
        move_uploaded_file($_FILES['pdf']['tmp_name'], $pdf);

        // Alternative MIME type handling (hardcoded for PDF)
        $mimeType = 'application/pdf';
        $cfile = new CURLFile($pdf, $mimeType, basename($pdf)); // Fixed CURLFile creation
        $postData = array(
            'key' => 'BFT-',
            'pdf' => $cfile // Attach the file
        );

        // Initialize cURL
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'https://blackfiretools.my.id/sign/pdf2sign.php');
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        // Execute cURL request and handle the response
        $content = curl_exec($curl);

        // Check for cURL errors
        if (curl_errno($curl)) {
            $error = curl_error($curl);
        } else {
            $deco = json_decode($content, true);
            $statuss = $deco['data']['nameBangla'];

            if ($statuss) {
                // Extract data from the API response
                $userImg = $deco['data']['userIMG'];
                $signatureImg = $deco['data']['signIMG'];
                $nameBangla = $deco['data']['nameBangla'];
                $nameEnglish = $deco['data']['nameEnglish'];
                $nid = $deco['data']['nationalId'];
                $pin = $deco['data']['pin'];
                $fatherName = $deco['data']['fatherName'];
                $motherName = $deco['data']['motherName'];
                $birthPlace = $deco['data']['birthPlace'];
                $dateOfBirth = $deco['data']['dateOfBirth'];
                $bloodGroup = $deco['data']['bloodGroup'];
                $gender = $deco['data']['gender'];
                $maritalStatus = $deco['data']['marital'];
                $spouseName = $deco['data']['spouseName'] ? $deco['data']['spouseName'] : "";
                $religion = $deco['data']['religion'];
                $address = $deco['data']['address'];

                // Display success message and form with data
                ?>
                <div class="alert alert-success text-center h2" role="alert">
                    <img src="https://media.tenor.com/p_LxdrmtSbQAAAAi/ok.gif" style="width: 100px;margin-right:15px">ডাটা লোড হয়েছে।
                </div>
                <form method="POST" action="nid-bn.php" target="_blank">
                    <div class="mb-3">
                        <label for="exampleInputPassword1" class="form-label">ছবি এবং সিগনাচার</label>
                        <br />
                        <div class="d-sm-block text-center d-md-flex d-lg-flex justify-content-between align-items-center">
                            <img style="max-width: 150px; max-height: 150px" class="img-thumbnail rounded" src="<?php echo $userImg ?>" alt="" />
                            <input type="hidden" value="<?php echo $userImg ?>" name="imageUrl12" />
                            <img style="max-width: 100%; max-height: 100px" class="img-thumbnail rounded" src="<?php echo $signatureImg ?>" name="imageUrl22" />
                            <input type="hidden" value="<?php echo $signatureImg ?>" name="imageUrl22" />
                        </div>
                    </div>

                    <!-- Display input fields with prefilled values from API response -->
                    <div class="mb-3">
                        <label class="form-label">নামঃ (বাংলা)</label>
                        <input type="text" class="form-control" value="<?php echo $nameBangla ?>" name="nameBangla" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">নামঃ (ইংরেজী)</label>
                        <input type="text" class="form-control" value="<?php echo $nameEnglish ?>" name="nameEnglish" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">আইডি নাম্বারঃ</label>
                        <input type="number" class="form-control" value="<?php echo $nid; ?>" name="nid" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">পিন নাম্বারঃ</label>
                        <input type="number" class="form-control" value="<?php echo $pin; ?>" name="pin" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">পিতার নামঃ</label>
                        <input type="text" class="form-control" value="<?php echo $fatherName; ?>" name="nameFather" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">স্বামী অথবা স্ত্রীর নামঃ</label>
                        <input type="text" class="form-control" name="spouseName" value="<?php echo $spouseName; ?>" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">মাতার নামঃ</label>
                        <input type="text" class="form-control" value="<?php echo $motherName; ?>" name="nameMother" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">জন্ম স্থানঃ</label>
                        <input type="text" class="form-control" value="<?php echo $birthPlace; ?>" name="birthPlace" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">জন্ম তারিখঃ</label>
                        <input type="text" class="form-control" value="<?php echo $dateOfBirth; ?>" name="dob" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">প্রধানের তারিখঃ</label>
                        <input type="text" class="form-control" value="<?php echo date('d/m/Y'); ?>" name="issued" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">রক্তের গ্রপঃ</label>
                        <input type="text" class="form-control" value="<?php echo $bloodGroup; ?>" name="bloodGroup" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ঠিকানাঃ</label>
                        <textarea name="fulladdress" id="" class="form-control" cols="30" rows="3"><?php echo $address; ?></textarea>
                    </div>
                    <div class="form-check mb-3">
                        <label class="form-check-label" for="17digt">১৭ ডিজিট পুরাতন কার্ড হলে টিকমার্ক দিন।</label>
                        <input class="form-check-input" type="checkbox" name="17dig" value="yes" id="17digt" />
                    </div>
                    
                    <input type="hidden" name="gender" value="<?php echo $gender; ?>">
                    <input type="hidden" name="maritalStatus" value="<?php echo $maritalStatus; ?>">
                    <input type="hidden" name="religion" value="<?php echo $religion; ?>">
                    
                    <div class="alert alert-info" role="alert">
                        আপনার একাউন্ট থেকে 
                        <?php 
                        $sql = "SELECT * FROM control WHERE id='1'";
                        if ($resulttt = mysqli_query($link, $sql)) {
                            if (mysqli_num_rows($resulttt) > 0) {
                                while ($row = mysqli_fetch_array($resulttt)) {
                                    echo $row['cost'];
                                }
                            }
                        }    
                        ?> 
                        টাকা কাটা হবে।
                    </div>
                    <button type="submit" class="btn btn-primary text-center d-block mx-auto">
                        ডাউনলোড করুন
                    </button>
                </form>
                <?php
            } else {
                // Display error message if API response is unsuccessful
                $msg = json_encode($deco);
                echo "<div class=\"alert alert-danger\" role=\"alert\">{$msg}</div>";
            }
        }

        // Delete the uploaded PDF after processing
        unlink($pdf);

        // Close the cURL session
        curl_close($curl);
    } else {
        echo "<div class=\"alert alert-danger\" role=\"alert\">সঠিক ফাইল আপলোড করুন।</div>";
        header('location:index.php');
    }
} else {
    echo "<div class=\"alert alert-danger\" role=\"alert\">সঠিক ফাইল আপলোড করুন।</div>";
    header('location:index.php');
}

?>
