<?php
session_start();
include('../config/dbcon.php');

// Check if timesheetID is provided via GET or POST
if (isset($_GET['timesheetID'])) {
    $timesheetID = $_GET['timesheetID'];
} elseif (isset($_POST['timesheetID'])) {
    $timesheetID = $_POST['timesheetID'];
} else {
    // Handle the case where timesheetID is not provided
    // Redirect or display an error message
    header('Location: timesheet.php');
    exit();
}

// Fetch the timesheet entry based on timesheetID
$query = "SELECT * FROM timesheet WHERE timesheetID = '$timesheetID'";
$result = mysqli_query($conn, $query);

if (!$result) {
    // Handle the case where the query fails
    echo "Error: " . mysqli_error($conn);
    exit();
}

if (mysqli_num_rows($result) != 1) {
    // Handle the case where the timesheet entry is not found
    echo "Timesheet entry not found.";
    exit();
}

$row = mysqli_fetch_assoc($result);
$clientID = $row['clientID'];
$projectID = $row['projectID'];
$milestoneID = $row['milestoneID'];

// Close the initial query result
mysqli_free_result($result);

// Fetch clients, projects, and milestones for populating dropdowns
$queryClients = "SELECT * FROM clients";
$resultClients = mysqli_query($conn, $queryClients);

$queryProjects = "SELECT * FROM projects";
$resultProjects = mysqli_query($conn, $queryProjects);

$queryMilestones = "SELECT * FROM milestones";
$resultMilestones = mysqli_query($conn, $queryMilestones);
?>

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

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>Edit Timesheet Entry</h4>
            </div>
            <div class="card-body">
                <form action="update_timesheet.php" method="POST" id="timesheetForm">
                    <input type="hidden" name="timesheetID" value="<?= $timesheetID ?>">
                    <div class="row">
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label for="tentryDate">Date of Entry</label>
                                <input type="date" name="tentryDate" class="form-control" required value="<?= $row['tentryDate'] ?>">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label for="client">Select Client:</label>
                                <select class="form-control client" name="client" required>
                                    <option value="">Select a Client</option>
                                    <?php
                                    while ($clientRow = mysqli_fetch_assoc($resultClients)) {
                                        $selected = ($clientRow['clientID'] == $clientID) ? 'selected' : '';
                                        echo "<option value='{$clientRow['clientID']}' $selected>{$clientRow['clientName']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label for="project">Select Project:</label>
                                <select class="form-control project" name="project" required>
                                    <option value="">Select a Project</option>
                                    <?php
                                    while ($projectRow = mysqli_fetch_assoc($resultProjects)) {
                                        $selected = ($projectRow['projectID'] == $projectID) ? 'selected' : '';
                                        $clientIDForProject = $projectRow['clientID'];
                                        echo "<option value='{$projectRow['projectID']}' data-client-id='$clientIDForProject' $selected>{$projectRow['projectName']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label for="milestone">Select Milestone:</label>
                                <select class="form-control milestone" name="milestone" required>
                                    <option value="">Select a Milestone</option>
                                    <?php
                                    while ($milestoneRow = mysqli_fetch_assoc($resultMilestones)) {
                                        $selected = ($milestoneRow['milestoneID'] == $milestoneID) ? 'selected' : '';
                                        $projectIDForMilestone = $milestoneRow['projectID'];
                                        echo "<option value='{$milestoneRow['milestoneID']}' data-project-id='$projectIDForMilestone' $selected>{$milestoneRow['milestoneName']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label>Hours Spent</label>
                                <input type="text" name="hrs" class="form-control" value="<?= $row['hrs'] ?>">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label>Description</label>
                                <input type="text" name="descp" class="form-control" value="<?= $row['descp'] ?>">
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="mb-3">
                                <label>Leave Days</label>
                                <input type="text" name="leaveDays" class="form-control" value="<?= $row['leaveDays'] ?>">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <br>
                            <button type="submit" value="Submit" class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Function to populate clients dropdown
    function populateClients() {
        var clientSelect = $('.client'); // Select all client dropdowns

        // Make an AJAX request to get clients
        $.ajax({
            url: "get_clients.php",
            type: "get", // Use GET method for fetching clients
            success: function (response) {
                // Update all client dropdowns with the fetched options
                clientSelect.html('<option value="">Select a Client</option>' + response);
                // Set the selected client based on the value from PHP
                clientSelect.val('<?php echo $clientID; ?>');
                // Trigger the change event to populate projects and milestones
                clientSelect.trigger('change');
            }
        });
    }

    // Call the function to populate clients initially
    populateClients();

    // Function to populate projects dropdown based on the selected client
    function populateProjects(selectElement) {
        var clientID = $(selectElement).val();
        var projectSelect = $(selectElement).closest('.row').find('.project');

        // Make an AJAX request to get projects for the selected client
        $.ajax({
            url: "get_projects.php",
            type: "post",
            data: { clientID: clientID },
            success: function (response) {
                // Update the projects dropdown with the fetched options
                projectSelect.html(response);
                // Set the selected project based on the value from PHP
                projectSelect.val('<?php echo $projectID; ?>');
                // Trigger the change event to populate milestones
                projectSelect.trigger('change');
            }
        });
    }

    // Function to populate milestones dropdown based on the selected project
    function populateMilestones(selectElement) {
        var projectID = $(selectElement).val();
        var milestoneSelect = $(selectElement).closest('.row').find('.milestone');

        // Make an AJAX request to get milestones for the selected project
        $.ajax({
            url: "get_milestones.php",
            type: "post",
            data: { projectID: projectID },
            success: function (response) {
                // Update the milestones dropdown with the fetched options
                milestoneSelect.html(response);
                // Set the selected milestone based on the value from PHP
                milestoneSelect.val('<?php echo $milestoneID; ?>');
            }
        });
    }

    // Event listener for client dropdown change (including dynamically added rows)
    $(document).on('change', '.client', function () {
        populateProjects(this);
    });

    // Event listener for project dropdown change (including dynamically added rows)
    $(document).on('change', '.project', function () {
        populateMilestones(this);
    });
</script>

<?php include('includes/footer.php'); ?>