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

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

    if ( $_SESSION['utype'] != 'master_admin' && $_SESSION['uref'] != 'fssdf4543frts' ) {
        header("Location: logout.php");
        exit();
    }

    if(isset($_GET["franchisee"])){
        $userId = $_GET["franchisee"];
        $user_sql = mysqli_query($con, "SELECT * FROM users WHERE utype = 'Associate' AND uid = '$userId' ");
        if($user_row = mysqli_fetch_assoc($user_sql)){
            $userName = $user_row["uname"];
            $uref_code = $user_row["uref_code"];
            $usertype = $user_row["utype"];
        }
    }
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_run = mysqli_query($con, "SELECT * FROM data  WHERE data_sl_no = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                    ?>
                <div class="card">
                    <div class="card-header">
                        <h4 class="m-0">Edit Document : <?php echo $edit_row["data_title"];?></h4>
                    </div>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="data_up_for" class="form-label">Document For
                                        <?php echo $user_row["utype"]; ?></label>
                                    <select name="data_up_for" class="form-control">
                                        <option value="<?php echo $userId; ?>"><?php echo $userName; ?></option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="data_title" class="form-label">Document Title</label>
                                    <input type="text" class="form-control" name="data_title"
                                        value="<?php echo $edit_row["data_title"]?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="logo" class="form-label">Upload Document <a
                                            href='<?php echo $edit_row["data_img"];?>' title='Click to open'
                                            target='_blank'>
                                            (<b>View Uploaded - <img src='<?php echo $edit_row["data_img"];?>'
                                                    height='20' data-toggle='modal' data-target='#show-img'
                                                    class='showModal'>
                                            </b></a> )</label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        placeholder="Upload logo">
                                </div>
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-success btn-user m-2" name="edit_blog">
                                        <i class="fa fa-edit"></i> Update
                                    </button>
                                    <a href="subFranchiee.php?franchisee=<?php echo $userId;?>&show_list"
                                        class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                                        Cancel </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["view_id"])){
                    $view_sql = "SELECT * FROM users WHERE uid ='$_GET[view_id]'";
                    $view_data = mysqli_query($con,$view_sql);
                    if($view_rows = mysqli_fetch_array($view_data)){

                        $state_sql = mysqli_query($con, "SELECT * FROM state WHERE id = '$view_rows[state]' ");
                        if($state_row = mysqli_fetch_assoc($state_sql)){
                            $state_name = $state_row["name"];
                        }
                        $dist_sql = mysqli_query($con, "SELECT * FROM dist WHERE id = '$view_rows[dist]' ");
                        if($dist_row = mysqli_fetch_assoc($dist_sql)){
                            $dist_name = $dist_row["distName"];
                        }
                    ?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="m-0">RE Title : <span class="underline"><?php echo $view_rows['uname']; ?></span>
                        </h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <?php
                                if (!empty($view_rows['ulogo']))
                                {
                            ?>
                            <h5 class="underline">RE Logo</h5>
                            <a href='<?php echo $view_rows["ulogo"];?>' title='Click to open' target='_blank'>
                                (<b>Already Uploaded - <img src='<?php echo $view_rows["ulogo"];?>' height='50'
                                        data-toggle='modal' data-target='#show-img' class='showModal'>
                                </b> Click To View</a> )
                            <?php }
                                if (!empty($edit_row['ulogo']))
                                { 
                            ?>
                            <a href='<?php echo $view_rows["ulogo"];?>' title='Click to open' target='_blank'>
                                (<b>Already Uploaded - <img src='<?php echo $view_rows["ulogo"];?>' height='50'
                                        data-toggle='modal' data-target='#show-img' class='showModal'>
                                </b> Click To View</a> )
                            <?php } ?>
                        </div>
                        <p><strong>Contact Number : </strong><?php echo $view_rows['ucontact']; ?></p>
                        <p><strong>User ID : </strong><?php echo $view_rows['referal_code']; ?></p>
                        <p><strong>Address : </strong><?php echo $view_rows['saddress']; ?></p>
                        <p><strong>District : </strong><?php echo $dist_name; ?></p>
                        <p><strong>State : </strong><?php echo $state_name; ?></p>
                        <p><strong>PIN Code : </strong><?php echo $view_rows["pin"]; ?></p>
                        <p class="m-0"><strong>Sub RA About : </strong></p>
                        <div class="mb-2">
                            <?php echo $view_rows["uabout"];?>
                        </div>
                        <hr>
                        <a href="subFranchiee-list.php?franchisee=<?php echo $userId;?>&show_list"
                            class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                            Cancel </a>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["add_new"])){?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="card-title mb-0">Add Document</h4>
                    </div>
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="data_up_for" class="form-label">Document For
                                        <?php echo $user_row["utype"]; ?></label>
                                    <select name="data_up_for" class="form-control">
                                        <option value="<?php echo $userId; ?>"><?php echo $userName; ?></option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="data_title" class="form-label">Document Title</label>
                                    <input type="text" class="form-control" name="data_title"
                                        placeholder="Enter Document Title">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="logo" class="form-label">Upload Document</label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        placeholder="Upload logo">
                                </div>
                                <div class="mb-3">
                                    <button class="btn btn-success text-white me-md-2" name="addsubmit" type="submit">
                                        <i class="fa fa-paper-plane"></i> Submit
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }?>
                <?php if(isset($_GET["show_list"])){?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h4 class="text-gray-800">Sub Associate List of <?php echo $userName;?></h4>
                            </div>
                            <div class="col-md-6 d-flex justify-content-end">
                                <div class="mr-2">
                                    <div class="form-group">
                                        <input type="text" list="First" class="form-control form-control-sm"
                                            id="FirstFilterValue" placeholder="Search By Sub Associate Title">
                                        <datalist id="First">
                                            <?php 
                                                $sql = "SELECT uname FROM users WHERE utype = 'Sub Associate' AND admin_ref = '$uref_code' AND udisplay != 'disable' ORDER BY uname ASC";
                                                $res = mysqli_query($con,$sql);
                                                while ($row = mysqli_fetch_assoc($res)) {
                                            ?>
                                            <option value="<?php echo $row['uname']; ?>">
                                                <?php echo $row['uname']; ?></option>
                                            <?php } ?>
                                        </datalist>
                                    </div>
                                    <input type="hidden" class="form-control" value="" id="FirstFilterValue">
                                </div>
                                <div class="d-flex">
                                    <div style="margin-left:0px">
                                        <div class="form-group">
                                            <input type="text" list="second" class="form-control form-control-sm"
                                                id="SecondFilterValue" placeholder="Search By Unique Id">
                                            <datalist id="second">
                                                <?php 
                                                    $sql2 = "SELECT referal_code FROM users WHERE utype = 'Sub Associate' AND admin_ref = '$uref_code' AND udisplay != 'disable' ORDER BY uname ASC";
                                                    $res2 = mysqli_query($con,$sql2);
                                                    while ($row2 = mysqli_fetch_assoc($res2)) {
                                                ?>
                                                <option value="<?php echo $row2['referal_code']; ?>">
                                                    <?php echo $row2['referal_code']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <input type="hidden" class="form-control" value="" id="SecondFilterValue">
                                    </div>
                                    <div class="#">
                                        <button type="button" id="filter" class="btn btn-primary btn-sm"><i
                                                class="fa fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </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: 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: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="text-center mt-3" id="load-more-container">
                                <button id="loadMoreBtn" class="btn btn-info btn-sm text-white">Load More</button>
                                <div id="endMessage" class="text-muted mt-2" style="display: none;">End of result</div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>

    <script>
    $(document).ready(function() {
        let load_filter_flag = 0;
        let load_flag = 0;

        // Get static values from PHP
        const uref_code = '<?php echo $uref_code; ?>';
        const userId = '<?php echo $userId; ?>';

        let FirstFilterValue = '';
        let SecondFilterValue = '';

        // Initial unfiltered data load
        loadMore(load_flag);

        // Filter Button Click
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();

            load_filter_flag = 0;
            load_flag = 0;

            $('#loadMoreBtn').show();
            $('#endMessage').hide();

            if (FirstFilterValue !== '' || SecondFilterValue !== '') {
                $.ajax({
                    url: 'subFranchiee-list-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue,
                        SecondFilterValue,
                        uref_code,
                        userId,
                        start: load_filter_flag
                    },
                    beforeSend: function() {
                        $("#loader").show();
                        $("#loadMoreBtn").hide();
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);
                        initializeStatusSwitches();

                        const newItems = $('<div>').html(result).find('li');
                        load_filter_flag += newItems.length;

                        if (newItems.length < 10) {
                            $('#loadMoreBtn').hide();
                            $('#endMessage').show();
                        } else {
                            $('#loadMoreBtn').show();
                            $('#endMessage').hide();
                        }
                    },
                    complete: function() {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Please select at least one filter option.');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        // Load More Button Click
        $('#loadMoreBtn').click(function() {
            if ($('#filter-table').is(':visible')) {
                loadMoreFilter(load_filter_flag);
            } else {
                loadMore(load_flag);
            }
        });

        // Load more for filtered data
        function loadMoreFilter(start) {
            $.ajax({
                url: 'subFranchiee-list-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    SecondFilterValue,
                    uref_code,
                    userId,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#filter-table-data').append(result);
                    initializeStatusSwitches();
                    const newItems = $('<div>').html(result).find('li');
                    load_filter_flag += newItems.length;

                    if (newItems.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        // Load more for unfiltered data
        function loadMore(start) {
            $.ajax({
                url: 'subFranchiee-list-Ajax.php',
                type: 'POST',
                data: {
                    uref_code,
                    userId,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    initializeStatusSwitches();
                    const newItems = $('<div>').html(result).find('li');
                    load_flag += newItems.length;

                    if (newItems.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }
    });
    </script>


</body>

</html>