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

// Fetch all clients
$clientQuery = "SELECT clientID, clientName FROM clients ORDER BY clientName";
$clientResult = mysqli_query($conn, $clientQuery);

if (!$clientResult) {
    die("Query failed: " . mysqli_error($conn));
}
?>

<div class="container mt-4">
    <h1 class="mt-4 mb-4">Costing Report</h1>
    <form id="costing-report-form">
        <div class="form-group mb-3">
            <label for="client">Select Client:</label>
            <select class="form-control" id="client" name="clientID" required>
                <option value="">-- Select Client --</option>
                <?php
                while ($row = mysqli_fetch_assoc($clientResult)) {
                    echo "<option value='{$row['clientID']}'>{$row['clientName']}</option>";
                }
                ?>
            </select>
        </div>
        <div class="form-group mb-3">
            <label for="project">Select Project:</label>
            <select class="form-control" id="project" name="projectID" required>
                <option value="">-- Select Project --</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">Generate Report</button>
    </form>
    
    <div id="report-container" class="mt-4">
        <!-- Report table will be populated here -->
    </div>
</div>

<script>
document.getElementById('client').addEventListener('change', function() {
    const clientID = this.value;
    const projectDropdown = document.getElementById('project');

    // Clear the projects dropdown
    projectDropdown.innerHTML = '<option value="">-- Select Project --</option>';

    if (clientID) {
        // Fetch projects for the selected client
        fetch(`fetch-projects.php?clientID=${clientID}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    data.projects.forEach(project => {
                        projectDropdown.innerHTML += `<option value="${project.projectID}">${project.projectName}</option>`;
                    });
                }
            })
            .catch(error => console.error('Error fetching projects:', error));
    }
});

document.getElementById('costing-report-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const clientID = document.getElementById('client').value;
    const projectID = document.getElementById('project').value;

    // Fetch and display the report
    fetch(`generate-report.php?clientID=${clientID}&projectID=${projectID}`)
        .then(response => response.text())
        .then(data => {
            document.getElementById('report-container').innerHTML = data;
        })
        .catch(error => console.error('Error generating report:', error));
});


</script>

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