<?php
// Include necessary PHP functions and configuration here, such as the database connection and session start.
include('includes/header.php'); // Include the header

// Check if the projectID is present in the URL
if (!isset($_GET['projectID'])) {
    // Handle the case when projectID is missing in the URL
    echo '<h5>No project ID found!</h5>';
    exit(0);
}

// Retrieve the project ID from the URL
$projectID = validate($_GET['projectID']);

// Include any necessary validation or data retrieval functions
// For example: include('validation_functions.php');

// Query the project name based on the projectID
$projectQuery = "SELECT projectName FROM projects WHERE projectID = $projectID";
$projectResult = mysqli_query($conn, $projectQuery);

// Check if the project name is fetched successfully
if ($projectResult && mysqli_num_rows($projectResult) > 0) {
    $projectData = mysqli_fetch_assoc($projectResult);
    $projectName = $projectData['projectName'];
} else {
    // Handle the case when project name is not found
    $projectName = "Project Name Not Found";
}

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize input data
    $milestoneID = validate($_POST['milestoneID']);
    $userIDs = $_POST['userIDs']; // Array of user IDs
    $daysBudgeted = $_POST['daysBudgeted']; // Array of budgeted days

    // Perform any additional validation as needed

    // Insert resource plan data into the database for each user
    for ($i = 0; $i < count($userIDs); $i++) {
        $userID = validate($userIDs[$i]);
        $budgetedDays = validate($daysBudgeted[$i]);

        // Insert resource plan data into the database
        $insertQuery = "INSERT INTO resourcePlan (userID, milestoneID, daysBudgeted)
                        VALUES ('$userID', '$milestoneID', '$budgetedDays')";

        if (!mysqli_query($conn, $insertQuery)) {
            // Error inserting resource plan
            $_SESSION['status'] = "Error: " . mysqli_error($conn);
            break; // Exit the loop if an error occurs
        }
    }

    // Check if all resource plans were added successfully
    if ($i == count($userIDs)) {
        // All resource plans added successfully
        $_SESSION['status'] = "Resource plans added successfully.";
    }

    // Redirect back to the resource plan view page
    echo '<script>window.location.href = "resource-plan-view.php?projectID=' . $projectID . '";</script>';
    exit();
}

// Include any necessary validation or data retrieval functions
// For example: include('validation_functions.php');
?>

<div class="row">
    <div class="col-md-8 offset-md-2">
        <div class="card">
            <div class="card-header">
                <h3 class="mb-4">Add Resource Plan</h3>
                <a href="resource-plan-view.php?projectID=<?php echo $projectID; ?>" class="btn btn-danger float-end">Back</a>
                <h5><strong>Project Name:</strong> <?php echo $projectName; ?></h5>
            </div>
            <div class="card-body">
                <form method="post" action="add-resource-plan.php?projectID=<?php echo $projectID; ?>">
                    <div class="mb-3">
                        <label for="milestoneSelect" class="form-label">Select Milestone</label>
                        <select class="form-select" id="milestoneSelect" name="milestoneID">
                            <option value="" selected disabled>Select Milestone</option>
                            <?php
                            // Fetch milestones associated with the project from the database
                            $milestoneQuery = "SELECT milestoneID, milestoneName FROM milestones WHERE projectID = $projectID";
                            $milestoneResult = mysqli_query($conn, $milestoneQuery);

                            if ($milestoneResult && mysqli_num_rows($milestoneResult) > 0) {
                                while ($row = mysqli_fetch_assoc($milestoneResult)) {
                                    echo '<option value="' . $row['milestoneID'] . '">' . $row['milestoneName'] . '</option>';
                                }
                            } else {
                                echo '<option value="">No milestones found</option>';
                            }
                            ?>
                        </select>
                    </div>

                    <div id="userInputs">
                        <!-- Initial set of user inputs -->
                        <div class="user-input mb-3 row align-items-center">
                            <div class="col-md-5">
                                <label for="userSelect1" class="form-label">Select User</label>
                                <select class="form-select" id="userSelect1" name="userIDs[]">
                                    <option value="" selected disabled>Select User</option>
                                    <?php
                                    // Fetch all users from the database
                                    $userQuery = "SELECT userID, CONCAT(fname, ' ', lname) AS fullName FROM users";
                                    $userResult = mysqli_query($conn, $userQuery);

                                    if ($userResult && mysqli_num_rows($userResult) > 0) {
                                        while ($row = mysqli_fetch_assoc($userResult)) {
                                            echo '<option value="' . $row['userID'] . '">' . $row['fullName'] . '</option>';
                                        }
                                    } else {
                                        echo '<option value="">No users found</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-5">
                                <label for="daysBudgeted1" class="form-label">Budgeted Days</label>
                                <input type="text" class="form-control" id="daysBudgeted1" name="daysBudgeted[]">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Remove</label>
                                <button type="button" class="btn btn-danger remove-btn" onclick="removeUserInput(this)">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <button type="button" class="btn btn-primary" onclick="addUserInput()">Add User</button>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Function to add more user inputs dynamically
    function addUserInput() {
        var userInputs = document.getElementById('userInputs');
        var lastUserInput = userInputs.lastElementChild.cloneNode(true);

        // Update IDs and names of cloned elements
        var count = userInputs.childElementCount + 1;
        lastUserInput.querySelector('label[for="userSelect1"]').innerHTML = 'Select User ' + count;
        lastUserInput.querySelector('select').id = 'userSelect' + count;
        lastUserInput.querySelector('select').name = 'userIDs[]';
        lastUserInput.querySelector('input').id = 'daysBudgeted' + count;
        lastUserInput.querySelector('input').name = 'daysBudgeted[]';
        lastUserInput.querySelector('input').value = ''; // Clear the value for new input

        userInputs.appendChild(lastUserInput);
    }

    // Function to remove user inputs dynamically
    function removeUserInput(btn) {
        var userInputs = document.getElementById('userInputs');
        var parentDiv = btn.closest('.user-input');
        
        // Check if only one row is present, then do not remove it
        if (userInputs.childElementCount > 1) {
            userInputs.removeChild(parentDiv);
        }
    }
</script>

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