<?php
extract($_GET);

// print_r($_GET);

if (empty($id)) {

    echo "<script> window.location.href ='" . BASE_URL . "/verifications/-nin_verifications'</script>";

}
$service = Service::find_by_id($id);
if (!$service || $service->status == 0) {

    echo "<script> window.location.href ='" . BASE_URL . "/verifications/-nin_verifications'</script>";
}
$sub_service = SubService::find_by_query("SELECT * FROM sub_service WHERE service_id = $service->id");


function select($subServices)
{
    switch ($subServices->service_code) {
        case 'VVS':
            $img = 'vnin_v_slip.png';
            $link = ROOT_URL . "/print/vnin_verification_slip.php";
            break;
        case 'NIS':
            $img = 'improved.png';
            $link = ROOT_URL . "/print/nin_improved_slip.php";
            break;
        case 'NPS':
            $img = 'premium.png';
            $link = ROOT_URL . "/print/nin_premium_slip.php";

            break;
        case 'BVS':
            $img = 'freepdf.png';
            $link = ROOT_URL . "/print/nin_pdf_slip.php";
            break;
        case 'RNS':
            $img = 'regular_nin_slip.jpg';
            $link = ROOT_URL . "/print/nin_regular_slip.php";

            break;
        case 'BVN':
            $img = 'bvn_slip.png';
            $link = ROOT_URL . "/print/bvn_pdf_slip.php";

            break;
            
        case 'BVN_P':
            $img = 'bvn_premium.jpg';
            $link = ROOT_URL . "/print/bvn_premium_slip.php";
            break;
            
        default:
            $img = 'freepdf.png';
            $link = ROOT_URL . "/print/nin_pdf_slip.php";

            # code...
            break;
    }

    return [
        'img' => ROOT_URL . "/assets/img/$img",
        'link' => $link
    ];
}
?>

<div class="p-2 sm:ml-64 mb-14">
    <nav class="md:max-w-max flex px-5 py-2 mt-20 mx-2 text-gray-700 border border-gray-200 rounded-lg bg-teal-50 bg-teal-800 dark:border-gray-700"
        aria-label="Breadcrumb">
        <ol class="inline-flex items-center space-x-1 md:space-x-3">
            <li class="inline-flex items-center">
                <a href="<?= BASE_URL ?>"
                    class="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-white">
                    <svg class="w-3 h-3 mr-2.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"
                        fill="currentColor" viewBox="0 0 20 20">
                        <path
                            d="m19.707 9.293-2-2-7-7a1 1 0 0 0-1.414 0l-7 7-2 2a1 1 0 0 0 1.414 1.414L2 10.414V18a2 2 0 0 0 2 2h3a1 1 0 0 0 1-1v-4a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v4a1 1 0 0 0 1 1h3a2 2 0 0 0 2-2v-7.586l.293.293a1 1 0 0 0 1.414-1.414Z" />
                    </svg>
                    Home
                </a>
            </li>
            <li>
                <div class="flex items-center">
                    <svg class="w-3 h-3 mx-1 text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"
                        fill="none" viewBox="0 0 6 10">
                        <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="m1 9 4-4-4-4" />
                    </svg>
                    <?php if ($service->category == "NIN"): ?>
                        <a href="<?= BASE_URL ?>/verifications/-nin_verifications"
                            class="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2 dark:text-gray-400 dark:hover:text-white">NIN
                            Verifications</a>
                    <?php else: ?>

                        <a href="<?= BASE_URL ?>/verifications/"
                            class="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2 dark:text-gray-400 dark:hover:text-white">Verifications</a>
                    <?php endif ?>
                </div>
            </li>
            <li>
                <div class="flex items-center">
                    <svg class="w-3 h-3 mx-1 text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"
                        fill="none" viewBox="0 0 6 10">
                        <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="m1 9 4-4-4-4" />
                    </svg>
                    <a href="#"
                        class="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2 dark:text-gray-400 dark:hover:text-white">
                        <?= $service->service_name ?>
                    </a>
                </div>
            </li>

        </ol>
    </nav>
    <div class="p-2 rounded-lg dark:border-gray-700">


        <h3 class="text-gray-600 text-sm">Select Slip type</h3>
        <div class="grid sm:grid-cols-1 md:grid-cols-1 lg:grid-cols-3  gap-4 justify-center rounded py-4 items-stretch">


            <?php foreach ($sub_service as $sub_service):
                ?>

                <button type="button" data-modal-target="<?= $sub_service->service_code ?>"
                    data-modal-toggle="<?= $sub_service->service_code ?>"
                    class="flex flex-col items-center border rounded-lg shadow md:flex-row md:max-w-xl border-teal-700 bg-teal-800 hover:bg-teal-700">
                    <img class="object-cover rounded-t-lg h-36 md:h-36 md:rounded-none md:rounded-l-lg transition-all"
                        src="<?= select($sub_service)['img'] ?>" alt="">
                    <div class="flex flex-col justify-between p-4 leading-normal">
                        <h5 class="mb-2 text-sm md:text-lg font-bold tracking-tight text-gray-900 text-white">
                            <?= $sub_service->service_name ?>
                        </h5>
                        <p class="mb-3 font-normal text-xs md:text-sm text-gray-300">You'll be
                            charge
                            <span class="bg-yellow-600 p-1 text-white font-bold rounded whitespace-nowrap">₦
                                <?= number_format($service->no_record_charge) ?>
                            </span> &nbsp;
                            if No record found.
                        </p>
                        <h5 class="text-right text-xs md:text-sm text-white font-bold">Price: <span
                                class="bg-red-500 p-1 text-white font-bold rounded whitespace-nowrap">₦
                                <?= number_format(intval($sub_service->service_fee) + intval($service->service_fee)) ?>
                            </span>
                        </h5>
                    </div>
                </button>


                <div id="<?= $sub_service->service_code ?>" tabindex="-1" aria-hidden="true"
                    class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full backdrop-blur transition-all">
                    <div class="relative w-full max-w-md max-h-full">
                        <!-- Modal content -->
                        <div class="relative rounded-lg shadow bg-emerald-700">
                            <button type="button" id="<?= $sub_service->id ?>close"
                                class="absolute model top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
                                data-modal-hide="<?= $sub_service->service_code ?>">
                                <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                                    viewBox="0 0 14 14">
                                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                        stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
                                </svg>
                                <span class="sr-only">Close modal</span>
                            </button>
                            <!-- Modal header -->
                            <div class="px-6 py-4 border-b rounded-t dark:border-gray-600">
                                <h3 class="text-base font-semibold text-gray-900 lg:text-lg dark:text-white">
                                    <?= $sub_service->service_name ?> >
                                    <?= $service->service_name ?>
                                </h3>
                            </div>
                            <!-- Modal body -->
                            <div class="p-4">

                                <form data-link="<?= select($sub_service)["link"] ?>"
                                    data-sub_service_id="<?= $sub_service->id ?>"
                                    data-service_fee="<?= $sub_service->service_fee ?>"
                                    class="verification_form space-y-4 md:space-y-6">
                                    <div>
                                        <?php $parameters = json_decode($service->parameters);

                                        foreach ($parameters as $key => $parameter):
                                            // print_r($parameter);
                                            ?>
                                            <label for="<?= $key ?>"
                                                class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                                                <?= $parameter->label ?>
                                            </label>

                                            <input type="<?= $parameter->type ?>" name="<?= $key ?>" id="<?= $key ?>"
                                                class="form-field bg-gray-50 border py-2 border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                                                placeholder="<?= $parameter->placeholder ?>">

                                        <?php endforeach ?>
                                    </div>


                                    <button type="submit"
                                        class="w-full text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium bg-emerald-900 hover:bg-emerald-950 rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800 ">Verify
                                        <span
                                            class="bg-red-500 p-1 text-xs text-white font-bold rounded shadow-2xl  shadow-emerald-950">₦
                                            <?= number_format(intval($sub_service->service_fee) + intval($service->service_fee)) ?>
                                        </span></button>

                                </form>

                                <div class="<?= $sub_service->id ?> transition-all flex flex-col items-center">

                                </div>
                                <div>
                                    <a href="#"
                                        class="inline-flex items-center text-xs font-normal text-gray-500 hover:underline dark:text-gray-400">
                                        <svg class="w-3 h-3 mr-2" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"
                                            fill="none" viewBox="0 0 20 20">
                                            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M7.529 7.988a2.502 2.502 0 0 1 5 .191A2.441 2.441 0 0 1 10 10.582V12m-.01 3.008H10M19 10a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                        </svg>
                                        Help?</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            <?php endforeach; ?>


        </div>

    </div>


    <div
        class="relative flex flex-col m-2 h-full min-w-0 break-words bg-emerald-800 border-0 shadow-soft-xl rounded bg-clip-border">
        <div
            class="relative flex flex-col min-w-0 break-words bg-emerald-800 border-0 shadow-soft-xl rounded bg-clip-border">
            <div class="p-6 px-4 pb-0 mb-0 bg-emerald-800 border-b-0 rounded">
                <h6 class="mb-0 text-sm text-white">All Recent Services Perform</h6>
            </div>
            <div class="flex-auto p-4 pt-6 text-white">
                <hr class="h-px bg-transparent bg-gradient-to-r from-transparent via-black/40 to-transparent" />
                <!-- </div> -->
                <div class="table-responsive " style="font-size: 12px !important;">

                    <table class="table table-flush datatable text-sm text-white overflow-x-scroll" datatable
                        id="datatable-search">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Service type</th>
                                <th>Amount</th>
                                <th>Searching Query</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $my_intransaction = InTransaction::find_by_query("SELECT * FROM in_transaction WHERE user_id=$user->id ORDER BY id DESC");
                            // $my_intransaction = array_reverse($my_intransaction);
                            
                            $i = 1;
                            foreach ($my_intransaction as $intransaction):

                                if ($intransaction->service_id == $service->id):
                                    $sub_servicess = SubService::find_by_query("SELECT * FROM sub_service WHERE service_id=$service->id AND service_name='$intransaction->service'");
                                    $sub_servicess = array_shift($sub_servicess);
                                    // echo "<pre>";
                                    // print_r($sub_servicess);
                                    if ($intransaction->service_id == $service->id) {
                                        // $parent_service=Service::find_by_id($intransaction->service_id);
                                        // $service= Service::find_by_id($intransaction->service_id);
                                        $service_name = $service->service_name . " > " . $intransaction->service;
                                        $amount = intval($service->service_fee) + intval($intransaction->amount);
                                    } else {
                                        $service_name = $intransaction->service;
                                        $amount = intval($intransaction->amount);
                                    }


                                    ?>
                                    <tr class='hover:bg-emerald-400 hover:text-emerald-950'>
                                        <td>
                                            <?= $i ?>
                                        </td>
                                        <td>
                                            <?= $service_name ?>
                                        </td>
                                        <td>₦
                                            <?= $amount ?>
                                        </td>
                                        <td>
                                            <?= $intransaction->search_query ?>
                                        </td>
                                        <td>
                                            <?= $intransaction->status == 1 ? '<span class="badge badge-lg bg-gradient-to-tl from-green-600 to-lime-400">Successful</span>' : '<span
                                        class="badge badge-lg bg-gradient-to-tl from-red-600 to-rose-400">Failed</span>' ?>
                                        </td>
                                        <td>
                                            <?= $intransaction->date ?>
                                        </td>
                                        <td>
                                            <?php if ($intransaction->status == 1): ?>
                                                <button data-link="<?= select($sub_servicess)["link"] ?>"
                                                    data-sub_service_id="<?= $sub_servicess->id ?>"
                                                    data-transaction_id="<?= $intransaction->id ?>"
                                                    data-record_id="<?= $intransaction->record_id ?>"
                                                    class="view_btn rounded bg-blue-500 p-1 text-white text-sm hover:bg-blue-700 hover:text-white">Download</button>
                                            <?php endif; ?>
                                        </td>

                                    </tr>
                                    <?php $i++;
                                endif;
                            endforeach; ?>
                        <tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>


</div>




<script>
    var verification_form = $('.verification_form');
    verification_form.on("submit", function (e) {
        e.preventDefault();

        var sub_service_id = $(this).data("sub_service_id")
        var service_fee = $(this).data("service_fee")
        var link = $(this).data("link");
        $this = $(this)




        var closeButton = $("#" + sub_service_id + "close");



        if (wallet_balance() < parseInt(service_fee)) {
            iziToast.warning({
                title: 'Caution',
                message: "Insufficient Wallet Balance",
                // color: "yellow",
                position: "topRight",
                balloon: true
            });

            return false
        }

        if (validateFormFields()) {

            var form_values = $(this).serialize();
            console.log(form_values);

            form_values += "&service_type=<?= $service->id ?>&sub_service_id=" + sub_service_id;


            $.ajax({
                method: "POST",
                dataType: 'json',
                data: form_values,
                url: "<?= ROOT_URL . $service->verification_url ?>",
                success: function (response) {

                    // console.log(response)

                    if (response.response_code == '00') {

                        iziToast.success({
                            title: 'OK',
                            message: "Verification Successfuly please wait while your slip is downloading!.",
                            // color: "yellow",
                            position: "topRight",
                            balloon: true,
                            onClosing: function () {
                                // location.reload();
                            }
                        });

                        verification_form[0].reset();


                        // close modal  

                        // closeButton.click()



                        // $("#record_id").val(response.record_id)



                        // var a = document.createElement('a')
                        // a.target = 'blank'
                        // a.href = link + "?record=" + response.record_id + "&service_id=" +
                        //     sub_service_id
                        // a.click()

                        download(link + "?record=" + response.record_id + "&service_id=" + sub_service_id, response.search_query)


                        var search_details = $("." + sub_service_id)

                        var visible_param = <?= $service->visible_param ?>


                        var table = $("<table/>").addClass("w-full text-sm text-left text-gray-400")

                        var image = $("<img/>").addClass("h-auto w-48 rounded-lg shadow-xl shadow-gray-800")

                        for (var key in visible_param) {
                            if (visible_param.hasOwnProperty(key)) {
                                var parameter = visible_param[key];
                                // console.log(key);
                                // console.log(parameter);

                                if (parameter == 'text') {

                                    var row = $('<tr/>').addClass("border-b bg-gray-600 border-gray-700")
                                    var keyCell = $('<th/>').addClass("px-4 py-2 font-medium whitespace-nowrap text-white").html(key.toUpperCase())
                                    var parameterCell = $('<td/>').addClass("px-4 py-2").html(

                                        response.nin_data ? response.nin_data[key] : response.data[key]

                                    )

                                    row.append(keyCell)
                                    row.append(parameterCell)
                                    table.append(row)
                                } else {
                                    let photo = response.nin_data ? response.nin_data[key] : response.data[key];
                                    image.prop("src", "data:image/jpg;charset=utf8;base64," + photo)
                                }

                            }
                        }

                        search_details.html(
                            `<h3 class="text-base font-semibold mt text-sm text-gray-900 lg:text-lg dark:text-white">Search Details</h3>`
                        )
                        $this.hide()
                        search_details.append(image)
                        search_details.append(table)

                        // console.log(visible_param)
                        // return false;


                        // wallet_balance()
                    } else {
                        $("#personal_detail").fadeOut("slow");
                        iziToast.error({
                            title: 'Error',
                            message: response.message ?? response.detail,
                            // color: "yellow",
                            position: "topRight",
                            balloon: true
                        });

                    }

                }

            })

        }



    });

    function validateFormFields() {
        let isValid = true;

        // Perform validation for each field
        verification_form.find(".form-field:visible").each(function () {
            const fieldValue = $(this).val();
            const fieldName = $(this).attr("name");

            // Perform validation logic for each field
            if (fieldValue.trim() === "") {
                isValid = false;
                iziToast.warning({
                    title: 'Error',
                    message: fieldName + " Field is required",
                    // color: "yellow",
                    position: "topRight",
                    balloon: true
                });
            }



        });

        return isValid;
    }
</script>












<script>
    $('.view_btn').click(function () {
        var transaction_id = $(this).data("transaction_id")
        var record_id = $(this).data("record_id")

        var link = $(this).data("link")
        // var record_id = $(this).data("record_id")
        var sub_service_id = $(this).data("sub_service_id")

        $.ajax({
            method: "GET",
            dataType: 'json',
            url: "<?= ROOT_URL ?>/main_includes/components/get_saved_record.php?record_id=" + record_id,
            success: function (response) {
                $(".lds-roller").fadeOut();
                // console.log(response)

                if (response.response_code == '00') {


                    // wallet_balance()
                    iziToast.success({
                        title: 'OK',
                        message: "Record Found! Please wait while your slip is downloading.",
                        // color: "yellow",
                        position: "topRight",
                        balloon: true
                    });

                    // var a = document.createElement('a')
                    // a.target = 'blank'
                    // a.href = link + "?record=" + response.record_id + "&service_id=" + sub_service_id + "&redownload=true"
                    // a.click()

                    download(link + "?record=" + response.record_id + "&service_id=" + sub_service_id + "&redownload=true", response.search_query)


                } else {
                    $("#personal_detail").fadeOut("slow");

                    iziToast.error({
                        title: 'Error',
                        message: response.message,
                        // color: "yellow",
                        position: "topRight",
                        balloon: true
                    });
                }

            }

        })

    })
</script>


<script>
    function download(url, filename) {

        // window.open(url)
        // return false
        var link = document.createElement('a');
        link.href = url;
        link.download = filename + ".pdf";
        link.target = "_blank"; // Open the link in a new tab/window
        link.style.display = "none"; // Hide the link
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);



        // $.ajax({
        //     url: url,
        //     method: 'GET',
        //     responseType: 'blob',
        //     success: function (response) {
        //         console.log(response);
        //         var blob = new Blob([response]);
        //         var url = window.URL.createObjectURL(blob);
        //         var link = document.createElement('a');
        //         link.href = url;
        //         link.download = filename+".pdf";
        //         // document.body.appendChild(link);
        //         link.click();
        //         // document.body.removeChild(link);
        //     },
        //     error: function (xhr, status, error) {
        //         console.log(error);
        //     }
        // });

    }
</script>