<?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();
    }

    $vendor = "";
    $andSearch = "";
    if(isset($_GET["vendor_id"])){
        $vendor_id = $_GET["vendor_id"];
        $vendor_sql = mysqli_query($con, "SELECT * FROM work_place WHERE wp_id = '$vendor_id' ");
        if($vendor_row = mysqli_fetch_assoc($vendor_sql)){
            $vendor = $vendor_row["wp_name"];
            $andSearch = "AND wl_vendor_id = '$_GET[vendor_id]' ";
        }
    }
?>

<!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 -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_id = $_GET["edit_id"];
                    $edit_run = mysqli_query($con, "SELECT * FROM work_list WHERE wl_id = '$_GET[edit_id]'");
                    
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                        $evendor_id = $edit_row["wl_vendor_id"];
                        $evendor_sql = mysqli_query($con, "SELECT * FROM work_place WHERE wp_id = '$evendor_id' ");
                        if($evendor_row = mysqli_fetch_assoc($evendor_sql)){
                            $evendor = $evendor_row["wp_name"];
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Generated Work For
                        <?php if(!empty($vendor_id)){ echo $vendor; } else {?>Vendor/Hotel <?php }?></h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row mb-2 mt-2">
                                <div class="col-md-4 mb-2">
                                    <label for="work_for">Edit Vendor/Hotel</label>
                                    <select name="work_for" class="form-control" id="">
                                        <option value="<?= $evendor_id; ?>"><?= $evendor; ?></option>
                                        <?php 
                                        $hotel_sql = mysqli_query($con, "SELECT * FROM work_place WHERE wp_recycle != '0' ORDER BY wp_name ASC");
                                        while($hotel_row = mysqli_fetch_assoc($hotel_sql)){
                                        ?>
                                        <option value="<?= $hotel_row["wp_id"]; ?>"><?= $hotel_row["wp_name"]; ?>
                                        </option>
                                        <?php }?>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="wl_title">Work Title</label>
                                    <input type="text" class="form-control" name="wl_title"
                                        value="<?= $edit_row["wl_title"];?>" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="date">Date</label>
                                    <input type="date" class="form-control" name="date"
                                        value="<?= $edit_row["wl_date"];?>" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="time">Time</label>
                                    <input type="time" class="form-control" name="time"
                                        value="<?= $edit_row["wl_time"];?>" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="byHotel">Amount paid by Hotel</label>
                                    <input type="number" class="form-control" name="byHotel"
                                        value="<?= $edit_row["wl_amount_by_hotel"]; ?>" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="toStudent">Amount paid to Student</label>
                                    <input type="number" class="form-control" name="toStudent"
                                        value="<?= $edit_row["wl_amount_to_student"]; ?>" required>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-success" name="edit_users">
                                UPDATE
                            </button>

                            <a href="<?php if(!empty($vendor_id)){ echo "view-work.php?vendor_id=".$vendor_id; } else {?>view-work.php<?php }?>"
                                class="btn btn-warning text-white"> <i class="fa fa-arrow-left"></i>
                                Back
                            </a>
                        </form>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["add_vendor"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Generate Work For
                        <?php if(!empty($vendor_id)){ echo $vendor; } else {?>Vendor/Hotel <?php }?></h5>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="row mb-3">
                                <div class="col-md-4 mb-2">
                                    <label for="work_for"
                                        class=""><?php if(!empty($vendor_id)){ echo $vendor; } else {?>Select
                                        Vendor/Hotel
                                        <?php }?></label>
                                    <?php if(!empty($vendor_id)){ ?>
                                    <select name="work_for" class="form-control" id="">
                                        <option value="<?= $vendor_id;?>"><?= $vendor;?></option>
                                    </select>
                                    <?php } else {?>
                                    <select name="work_for" class="form-control" id="">
                                        <option value="">Select From list</option>
                                        <?php 
                                        $hotel_sql = mysqli_query($con, "SELECT * FROM work_place WHERE wp_recycle != '0' ORDER BY wp_name ASC");
                                        while($hotel_row = mysqli_fetch_assoc($hotel_sql)){
                                        ?>
                                        <option value="<?= $hotel_row["wp_id"]; ?>"><?= $hotel_row["wp_name"]; ?>
                                        </option>
                                        <?php }?>
                                    </select>
                                    <?php }?>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="wl_title">Work Title</label>
                                    <input type="text" class="form-control" name="wl_title"
                                        placeholder="Enter Work Title" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="date">Date</label>
                                    <input type="date" class="form-control" name="date" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="time">Time</label>
                                    <input type="time" class="form-control" name="time" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="byHotel">Amount paid by Hotel</label>
                                    <input type="number" class="form-control" name="byHotel" placeholder="Amount*"
                                        required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="toStudent">Amount paid to Student</label>
                                    <input type="number" class="form-control" name="toStudent" placeholder="Amount*"
                                        required>
                                </div>
                            </div>
                            <div class="">
                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="submit">
                                    <i class="fa fa-gear"></i> Generate Work
                                </button>
                                <a href="<?php if(!empty($vendor_id)){ echo "view-work.php?vendor_id=".$vendor_id; } else {?>view-work.php<?php }?>"
                                    class="btn btn-warning btn-user mt-4 text-white"> <i class="fa fa-arrow-left"></i>
                                    Back </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php } else{?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <div class="d-flex justify-content-between">
                                    <h4 class="text-gray-800 m-0">
                                        <?php if(!empty($vendor_id)){ echo $vendor; } else {?>Vendor/Hotel <?php }?>
                                        Work List</h4>
                                    <a class="btn btn-primary btn-sm"
                                        href="<?php if(!empty($vendor_id)){ echo "view-work.php?vendor_id=". $vendor_id ."&add_vendor"; } else {?>view-work.php?add_vendor<?php }?>"><i
                                            class="fa fa-w"></i> Generate Work</a>
                                </div>
                            </div>
                            <div class="col-md-6 mt-1">
                                <div class="d-flex">
                                    <div class="w-100">
                                        <div class="form-group">
                                            <input type="text" list="First" class="form-control form-control-sm"
                                                id="FirstFilterValue" placeholder="Search By Vendor/Hotel Name">
                                            <datalist id="First">
                                                <?php 
                                                echo "SELECT wl_title FROM work_list WHERE wl_recycle != '0' $andSearch ORDER BY wl_title ASC";
                                                    $sql = "SELECT wl_title FROM work_list WHERE wl_recycle != '0' $andSearch ORDER BY wl_title ASC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['wl_title']; ?>">
                                                    <?php echo $row['wl_title']; ?></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"> Search
                                        </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"; ?>

    <!-- Modal Structure -->
    <div class="modal fade" id="adminDetailsModal" data-bs-backdrop="static" tabindex="-1" role="dialog"
        aria-labelledby="modelTitleId" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 style="color:orange;font-size: 20px"> <i class="fa fa-hotel"></i> <span id="modalName"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><b>Title:</b> <span id="modalTitle"></span></p>
                    <p><b>Date:</b> <span id="modalStartDate"></span></p>
                    <p><b>Time:</b> <span id="modalEndDate"></span></p>
                    <p><b>Amount by Hotel:</b> <span id="modalHotelAmount"></span></p>
                    <p><b>Amount to Student:</b> <span id="modalStudentAmount"></span></p>
                    <p><b>Created Date:</b> <span id="modalDate"></span></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    </script>

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

        var FirstFilterValue = '';
        <?php if(isset($_GET["vendor_id"])){?>
        var SecondFilterValue = '<?= $vendor_id;?>';
        <?php } else {?>
        var SecondFilterValue = '';
        <?php }?>

        // Initial unfiltered data load
        loadMore(load_flag);

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

            load_filter_flag = 0;
            load_flag = 0;

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

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

                        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: 'view-work-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue: FirstFilterValue,
                    SecondFilterValue: SecondFilterValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#filter-table-data').append(result);
                    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: 'view-work-Ajax.php',
                type: 'POST',
                data: {
                    SecondFilterValue: SecondFilterValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    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>

<?php

if (isset($_POST['submit'])) {
    $vendor_id   = intval($_POST['work_for']);
    $wl_title   = mysqli_real_escape_string($con, $_POST['wl_title']);
    $date   = mysqli_real_escape_string($con, $_POST['date']);
    $time     = mysqli_real_escape_string($con, $_POST['time']);
    $byHotel     = floatval($_POST['byHotel']);
    $toStudent   = floatval($_POST['toStudent']);

    // optional validation
    if ($vendor_id <= 0 || empty($date) || empty($time) || $byHotel <= 0 || $toStudent <= 0) {
        echo "<script>alert('Please fill all fields correctly!'); window.history.back();</script>";
        exit;
    }

    // Insert into work_list
    $sql = "INSERT INTO work_list 
            (wl_vendor_id, wl_title, wl_date, wl_time, wl_amount_by_hotel, wl_amount_to_student, wl_recycle, wl_cDate) 
            VALUES 
            ('$vendor_id', '$wl_title', '$date', '$time', '$byHotel', '$toStudent', '1', '$currentTime')";

    if (mysqli_query($con, $sql)) {
        echo "<script>alert('Work Generated Successfully!'); 
              window.location.href='view-work.php?vendor_id=$vendor_id';</script>";
    } else {
        echo "Error: " . mysqli_error($con);
    }
}
?>

<?php
if (isset($_POST['edit_users'])) {
    $wl_id       = intval($_GET['edit_id']);
    $work_for    = mysqli_real_escape_string($con, $_POST['work_for']);
    $wl_title    = mysqli_real_escape_string($con, $_POST['wl_title']);
    $date        = mysqli_real_escape_string($con, $_POST['date']);
    $time        = mysqli_real_escape_string($con, $_POST['time']);
    $byHotel     = mysqli_real_escape_string($con, $_POST['byHotel']);
    $toStudent   = mysqli_real_escape_string($con, $_POST['toStudent']);

    // Fetch old date and time for comparison
    $old_sql = mysqli_query($con, "SELECT wl_date, wl_time FROM work_list WHERE wl_id = '$wl_id'");
    $old_data = mysqli_fetch_assoc($old_sql);
    $old_date = $old_data['wl_date'];
    $old_time = $old_data['wl_time'];

    // Update work_list
    $update_sql = "UPDATE work_list 
                   SET wl_vendor_id = '$work_for',
                       wl_title = '$wl_title',
                       wl_date = '$date',
                       wl_time = '$time',
                       wl_amount_by_hotel = '$byHotel',
                       wl_amount_to_student = '$toStudent'
                   WHERE wl_id = '$wl_id' AND wl_recycle != '0'";

    if (mysqli_query($con, $update_sql)) {
        
        // If date or time has changed → update related tables
        if ($old_date != $date || $old_time != $time) {

            // Update work_student
            mysqli_query($con, "
                UPDATE work_student 
                SET ws_date = '$date', ws_time = '$time'
                WHERE ws_workId = '$wl_id'
            ");

            // Update work_attendance
            mysqli_query($con, "
                UPDATE work_attendance 
                SET wa_date = '$date', wa_time = '$time'
                WHERE wa_workId = '$wl_id'
            ");
        }

        echo "<script>
                alert('Work updated successfully!');
                window.location.href='view-work.php?vendor_id=$work_for';
              </script>";
    } else {
        echo "<script>
                alert('Error updating work: " . mysqli_error($con) . "');
                window.history.back();
              </script>";
    }
}
?>


<?php
if ( isset($_GET["del_id"]) ) {
$disable_sql = "UPDATE work_list SET wl_recycle = '0' WHERE wl_id = '$_GET[del_id]'";

    if ( mysqli_query($con, $disable_sql) ) {
       echo "<script>
              window.location.href='view-work.php?vendor_id=$vendor_id';</script>";
    } else {
        echo "<script>
              window.location.href='view-work.php?vendor_id=$vendor_id';</script>";
    }
}
?>