<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Sub Associate']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['uref_code']) && !isset($_SESSION['uname']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    $admin_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$_SESSION["uid"]}' ");
    if($admin_row = mysqli_fetch_assoc($admin_sql)){
        $admin_ref = $admin_row["admin_ref"];
    }
    $fran_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '$admin_ref' ");
    if($fran_row = mysqli_fetch_assoc($fran_sql)){
        $_SESSION["fran_id"] = $fran_id = $fran_row["uid"];
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->
    <?php if(isset($_GET["product_id"])){
        $product_id = $_GET["product_id"];
        $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pid = '$product_id' ");
        if($product_row = mysqli_fetch_assoc($product_sql)) {

            $client_id = $product_row["pClient"];
            $client_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$client_id' ");
            if($client_row = mysqli_fetch_assoc($client_sql)){
                $client_name = $client_row["uname"];
            }

            $service_id = $product_row["product"];
            $service_sql = mysqli_query($con, "SELECT * FROM data WHERE data_sl_no = '$service_id' ");
            if($service_row = mysqli_fetch_assoc($service_sql)){
                $service_name = $service_row["data_title"];
                $service_charges = $service_row["data_seo_tag"];
            }

            // Get total payments for the current query
            $total_sql = "SELECT SUM(payment) AS total_payment FROM payment WHERE p_forProduct = '$product_id' ";
            $total_res = mysqli_query($con, $total_sql);
            $total_payment = 0;
            if ($total_row = mysqli_fetch_assoc($total_res)) {
                $total_payment = $total_row['total_payment'];
            }

            $remaining_balence = $service_charges - $total_payment;
        ?>

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Payment For
                        <span style="color:orange;"><?php echo $service_name;?></span>
                        <span style="font-size:12px;"> ( Total Payable : <?php echo $service_charges;?> / </span>
                        <span style="font-size:12px;">Total Paid : <?php echo $total_payment;?> / </span>
                        <span style="font-size:12px;">Remaining Balence : <?php echo $remaining_balence;?> )</span>
                    </h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="amount">Enter amount</label>
                                        <input type="text" class="form-control" name="amount"
                                            placeholder="Enter Payment Amount" required>
                                    </div>
                                </div>
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label for="description">Enter Description</label>
                                        <input type="text" class="form-control" name="description"
                                            placeholder="Enter Payment Description">
                                    </div>
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user btn-sm m-2" name="submit"><i
                                        class="fa fa-plus"></i> Pay Now
                                </button>
                                <a href="view-product.php?client_id=<?php echo $client_id;?>"
                                    class="btn btn-warning btn-user btn-sm text-white m-2"> <i class="fa fa-ban"></i>
                                    Cancel </a>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-12 col-12 mt-2 mb-2">
                                <div class="row justify-content-between align-items-center">
                                    <div class="col-md-8 col-12 mb-2">
                                        <h4 class="text-gray-800 m-0">Payment List For <span
                                                style="color:orange;"><?php echo $service_name;?></span></h4>
                                    </div>
                                    <div class="col-md-4 col-12 text-end">
                                        <a href="view-product.php?client_id=<?php echo $client_id;?>"
                                            class="btn btn-warning text-white btn-sm"><i class="fa fa-arrow-left"></i>
                                            Back</a>
                                    </div>
                                </div>
                            </div>
                            <?php if(isset($_GET["kallol"])){?>
                            <div class="col-md-3 col-12 mt-2 mb-2 d-flex justify-content-center">
                                <div class="form-group w-100">
                                    <input type="text" list="First" class="form-control form-control-sm"
                                        id="FirstFilterValue" placeholder="Search By Name">
                                    <datalist id="First">
                                        <?php 
                                            $sql = "SELECT DISTINCT product FROM product WHERE pClient = '{$_GET["client_id"]}' AND pSubFranchiee = '{$_SESSION["uid"]}' ORDER BY pid DESC";
                                            $res = mysqli_query($con,$sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                                // Fetching product details
                                                $service2_sql = mysqli_query($con, "SELECT * FROM data WHERE data_sl_no = '{$row["product"]}'");
                                                if($service2_row = mysqli_fetch_assoc($service2_sql)){
                                                    $productId = $service2_row["data_sl_no"];
                                                    $productName = $service2_row["data_title"];
                                                }
                                        ?>
                                        <!-- Add data-id attribute to the option -->
                                        <option value="<?php echo $productName; ?>" data-id="<?php echo $productId; ?>">
                                            <?php echo $productName; ?>
                                        </option>
                                        <?php } ?>
                                    </datalist>
                                </div>

                                <div class="#">
                                    <button type="button" id="filter" class="btn btn-primary btn-sm">Search</button>
                                </div>

                            </div>
                            <?php }?>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding-left: 0;">
                                    <?php 
                                        for ($count = 0; $count < 4; $count++) {
                                            echo '<li>
                                            <div class="ph-item">
                                            <div cl ass="ph-test">
                                            <div class="ph-row">
                                            <div class="ph-col-12 big"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            </div></div>
                                            </div>
                                            </li>';
                                        }
                                    ?>
                                </ul>
                            </div>
                            <!-- loader -->

                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding-left: 0;">
                                    </>
                                </ul>
                            </div>
                            <div class="col-12" id="filter-table" style="display: none;">
                                <ul class="timeline" id="filter-table-data" style="list-style: none; padding-left: 0;">
                                    </>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <?php } }?>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>
    <script>
    $(document).ready(function() {
        var load_filter_flag = 0;
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var ThirdFilterValue = '';
        var client_id = '<?php echo $client_id; ?>'; // PHP variable passed correctly
        var product_id = '<?php echo $product_id; ?>';

        // Trigger filtering when the filter button is clicked
        $("#filter").click(function() {
            // Get the selected option's value from datalist and fetch its data-id
            var selectedOption = $('#FirstFilterValue').val();
            var selectedDataId = $("#First option[value='" + selectedOption + "']").attr('data-id');

            FirstFilterValue = selectedDataId ? selectedDataId : selectedOption;
            SecondFilterValue = $('#SecondFilterValue').val();
            ThirdFilterValue = $('#ThirdFilterValue').val();

            load_filter_flag = 0; // Reset the filter load flag for new filter

            if (FirstFilterValue !== '' || SecondFilterValue !== '' || ThirdFilterValue !== '') {
                $.ajax({
                    url: 'view-pay-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue, // Using data-id if available
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        start: load_filter_flag,
                        client_id: client_id,
                        product_id: product_id
                    },
                    beforeSend: function() {
                        $("#loader").show(); // Show loader before request
                    },
                    success: function(result) {
                        $('#full-table').hide(); // Hide full table
                        $('#filter-table').show(); // Show filtered table
                        $('#filter-table-data').html(result); // Load the result
                        load_filter_flag +=
                            10; // Increment load flag for future scroll loading
                    },
                    complete: function() {
                        $("#loader").hide(); // Hide loader after completion
                    }
                });
            } else {
                alert('Please select an option');
                $('#full-table').show(); // Show full table when no filter is applied
                $('#filter-table').hide(); // Hide filtered table
            }
        });

        // Function to load more filtered data on scroll
        function loadMoreFilter(start) {
            if (load_filter_flag > 0) {
                $.ajax({
                    url: 'view-pay-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        start: start,
                        client_id: client_id,
                        product_id: product_id
                    },
                    success: function(result) {
                        $('#filter-table-data').append(result);
                        load_filter_flag += 10; // Increment flag for subsequent loads
                    }
                });
            }
        }

        // Function to load more full data on scroll
        var load_flag = 0;
        loadMore(load_flag);

        function loadMore(start) {
            $.ajax({
                url: 'view-pay-Ajax.php',
                type: 'post',
                data: {
                    start: start,
                    client_id: client_id,
                    product_id: product_id
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10; // Increment flag for subsequent loads
                },
                complete: function() {
                    $("#loader").hide(); // Hide loader after completion
                }
            });
        }

        // Infinite scroll event on inner-body element
        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() + $('#inner-body').height() >= $('#inner-body')[0]
                .scrollHeight) {
                // Check if the filter is active or not, and load the respective data
                if (load_filter_flag > 0) {
                    loadMoreFilter(load_filter_flag); // Load more filtered data
                } else {
                    loadMore(load_flag); // Load more full data
                }
            }
        });
    });
    </script>



</body>

</html>

<?php
if (isset($_POST['submit'])) {
    $_SESSION["amount"] = $amount = $_POST["amount"];
    $_SESSION["description"] = $_POST["description"];

    date_default_timezone_set('Asia/Kolkata');
    $_SESSION["client_id"] = $client_id;
    $_SESSION["product_id"] = $product_id;
    $_SESSION["service_name"] = $service_name;

    $_SESSION["rechargeBy"] = $rechargeBy = $_SESSION["uid"];
    $_SESSION["fran_id"] = $fran_id = $_SESSION["fran_id"];
    $_SESSION["rByType"] = $rByType = $_SESSION["utype"];
    $_SESSION["recycle"] = $recycle = 0;
    $_SESSION["uniqueCode"] = $uniqueCode = generateUniqueCode();

    if(!empty($amount)){
        echo "<script>
        window.location.href = 'pay.php';
        </script>";
    } else {
        echo "<script>
            window.location.href = 'view-pay.php?product_id=$product_id';
        </script>";
    }
}

    // Unique Code generation Script
    function generateUniqueCode() {
        // Get the current timestamp in microseconds
        $timestamp = microtime(true);
        // Create a 9-digit code by taking a part of the timestamp and converting it to a string
        $uniqueCode = substr(str_replace('.', '', $timestamp), -9);
        // Generate a random position to insert 'p'
        $randomPosition = rand(0, 9);
        // Insert 'W' into the random position
        $uniqueCodeWithW = substr_replace($uniqueCode, 'p', $randomPosition, 0);
    
        return $uniqueCodeWithW;
    }
    $uniqueCode = generateUniqueCode();
    // Check if the generated code already exists in the payment table
    $query = "SELECT * FROM payment WHERE p_ref = '$uniqueCode'";
    $result = mysqli_query($con, $query);

    // Regenerate the code if it already exists in the table
    while(mysqli_num_rows($result) > 0) {
        $uniqueCode = generateUniqueCode();
        $result = mysqli_query($con, "SELECT * FROM payment WHERE p_ref = '$uniqueCode'");
    }
?>