<?php include('includes/header.php'); ?>
<!DOCTYPE html>
<html>

<head>
    <title>Timesheet View</title>
</head>

<body>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>
                        Timesheet Entries
                    </h4>
                    <button id="download-csv" class="btn btn-primary float-end">Download CSV</button>
                </div>
                <div class="card-body">

                    <?php
                    session_start();
                    $userID = $_SESSION['userID'];
                    
                    // Define $selectedMonth with a default value (e.g., the previous month)
                    $selectedMonth = date('Y-m', strtotime('last month'));


                    // Check if a success message exists in the session
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success">' . $_SESSION['success_message'] . '</div>';

                        // Remove the success message from the session to prevent it from displaying again
                        unset($_SESSION['success_message']);
                    }

                    // Get the current date and time
                    $currentDate = date('Y-m-d');

                    // Calculate the start and end dates for the current month
                    $startDate = date('Y-m-01');
                    $endDate = date('Y-m-t');

                    // Check if a month filter has been selected
                    if (isset($_POST['selectedMonth'])) {
                        $selectedMonth = $_POST['selectedMonth'];

                        // Construct the start and end dates for the selected month
                        $startDate = date('Y-m-d', strtotime("first day of $selectedMonth"));
                        $endDate = date('Y-m-d', strtotime("last day of $selectedMonth"));

                        // Fetch timesheet entries for the selected month
                        $query = "SELECT timesheetID,tentryDate, clientName, projectName, milestoneName, hrs, descp, leaveDays
                  FROM timesheet
                  INNER JOIN clients ON timesheet.clientID = clients.clientID
                  INNER JOIN projects ON timesheet.projectID = projects.projectID
                  INNER JOIN milestones ON timesheet.milestoneID = milestones.milestoneID
                  WHERE timesheet.userID = '$userID'
                  AND tentryDate >= '$startDate'
                  AND tentryDate <= '$endDate'";
                    } else {
                        // Fetch timesheet entries for the current month (default)
                        $query = "SELECT timesheetID,tentryDate, clientName, projectName, milestoneName, hrs, descp, leaveDays
                  FROM timesheet
                  INNER JOIN clients ON timesheet.clientID = clients.clientID
                  INNER JOIN projects ON timesheet.projectID = projects.projectID
                  INNER JOIN milestones ON timesheet.milestoneID = milestones.milestoneID
                  WHERE timesheet.userID = '$userID'
                  AND tentryDate >= '$startDate'
                  AND tentryDate <= '$endDate'";
                    }

                    $result = mysqli_query($conn, $query);

                   // Display the month filter dropdown
                    echo "<form method='post' class='form-inline'>";
                    echo "<div class='form-group mr-2'>";
                    echo "<label for='selectedMonth'>Select Month:</label>";
                    echo "<select name='selectedMonth' id='selectedMonth' class='form-control'>";

                    $months = array();
                    $currentYear = date('Y');  // Get current year
                    $currentMonth = date('n'); // Get current month (numeric)
                    
                    // Start from April 2023
                    for ($year = 2023; $year <= $currentYear; $year++) {
                        for ($month = 1; $month <= 12; $month++) {
                            // Ensure it starts from April 2023
                            if ($year == 2023 && $month < 4) {
                                continue; // Skip months before April 2023
                            }
                    
                            // Stop at the current month of the same year
                            if ($year == $currentYear && $month > $currentMonth) {
                                break; // Stop adding months beyond the current month
                            }
                    
                            // Format month correctly
                            $monthDate = date('Y-m', strtotime("$year-$month"));
                            $monthName = date('F Y', strtotime("$year-$month"));
                            $months[$monthDate] = $monthName;
                        }
                    }
                    
                    ksort($months); // Ensure months are in correct order

                    // Populate the dropdown with the months
                    foreach ($months as $value => $monthName) {
                        // Check if this option corresponds to the selected month and set the 'selected' attribute
                        $selectedAttribute = ($value === $selectedMonth) ? 'selected' : '';

                        echo "<option value='$value' $selectedAttribute>$monthName</option>";
                    }

                    echo "</select>";
                    echo "</div>";
                    echo "<button type='submit' class='btn btn-primary mb-3'>Show</button>";
                    echo "</form>";


                    $totalHours = 0;
                    $totalLeaves = 0;

                    if (mysqli_num_rows($result) > 0) {
                        echo "<table class='table table-bordered table-striped'>
              <thead>
                <tr class='align-middle text-center'>
                    <th>Date</th>
                    <th>Client</th>
                    <th>Project</th>
                    <th>Milestone</th>
                    <th>Hrs</th>
                    <th>Description</th>
                    <th>Action</th>
                </tr>
              </thead>
              <tbody>";

                        while ($row = mysqli_fetch_assoc($result)) {
                            echo "<tr class='align-middle text-center'>
                                    <td>{$row['tentryDate']}</td>
                                    <td>{$row['clientName']}</td>
                                    <td>{$row['projectName']}</td>
                                    <td>{$row['milestoneName']}</td>
                                    <td>{$row['hrs']}</td>
                                    <td>{$row['descp']}</td>
                                    <td>
                                        <a href='timesheet-edit.php?timesheetID={$row['timesheetID']}' class='btn btn-success mb-3'>Edit</a>
                                        <a href='timesheet-delete.php?timesheetID={$row['timesheetID']}' class='btn btn-danger delete-link' data-confirm='Are you sure you want to delete this data?'>Delete</a>      
                                    </td>
                                </tr>";

                            // Add the hours to the total
                            $totalHours += (float) $row['hrs'];
                            // Check if the specified criteria are met for calculating leaves
                            if ($row['clientName'] == 'NEW CONCEPT' && $row['projectName'] == 'GENERAL ADMIN' && $row['milestoneName'] == 'LEAVE') {
                                $totalLeaves += (float)$row['hrs'] / 8;
                            }

                        }

                        echo "</tbody></table>";
                        echo "<div class='text-right'><strong>Total Hours for the Month:</strong> $totalHours</div>";
                        echo "<div class='text-right'><strong>Total Leaves for the Month:</strong> $totalLeaves</div>";
                    } else {
                        echo "No timesheet entries found.";
                    }

                    mysqli_close($conn);
                    ?>

                    <br><br>
                    <a href="timesheet-create.php" class="btn btn-success btn-sm">Add Timesheet Entry</a>
                    <!-- <a href="viewAllTimesheet.php" class="btn btn-warning btn-sm">View All Timesheet Entry</a> -->
                </div>
</body>


<!-- JavaScript to handle confirmation dialog -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            // Add a click event listener to all elements with the "delete-link" class
            $('.delete-link').on('click', function (event) {
                // Prevent the default link behavior
                event.preventDefault();
                
                // Show a confirmation dialog
                if (confirm($(this).data('confirm'))) {
                    // If the user confirms, proceed with the link's href
                    window.location.href = $(this).attr('href');
                }
            });
        });
        
                // Function to trigger CSV download
        function downloadCSV() {
            const table = document.querySelector('.table');
            const rows = table.querySelectorAll('tr');
            const csv = [];

            // Generate CSV content
            rows.forEach((row, rowIndex) => {
                const rowData = [];
                row.querySelectorAll('td, th').forEach((cell, cellIndex) => {
                    // Wrap cell data in double quotes and escape existing double quotes
                    const cellData = cell.textContent.replace(/"/g, '""');
                    rowData.push(`"${cellData}"`);
                });

                // Include the header row if it's the first row
                if (rowIndex === 0) {
                    csv.push(rowData.join(','));
                } else {
                    csv.push(rowData.join(','));
                }
            });

            // Create a blob containing the CSV data
            const blob = new Blob([csv.join('\n')], { type: 'text/csv' });

            // Create a download link and trigger the download
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'timesheet_report.csv';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Add click event listener to the download button
        document.getElementById('download-csv').addEventListener('click', downloadCSV);
    </script>
</html>