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

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

// Retrieve the milestone ID from the URL
$milestoneID = $_GET['milestoneID'];

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

// Assuming you have a function to fetch the projectID associated with the milestone
$projectID = getProjectIDForMilestone($milestoneID);

if (!$projectID) {
    // Handle the case when projectID is not found for the milestone
    echo '<h5>Project ID not found for the milestone!</h5>';
    exit(0);
}

// Assuming you have a function to delete the milestone by ID
if (deleteMilestoneById($milestoneID)) {
    // Milestone deleted successfully, set a success message
    $_SESSION['success_message'] = 'Milestone deleted successfully.';
} else {
    // Milestone deletion failed, set an error message
    $_SESSION['error_message'] = 'Failed to delete milestone.';
}

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

// Function to fetch the projectID associated with the milestone
function getProjectIDForMilestone($milestoneID) {
    global $conn;

    // Implement your SQL query to retrieve the projectID for the milestone
    $query = "SELECT projectID FROM milestones WHERE milestoneID = $milestoneID";

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

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['projectID'];
    }

    return null; // Milestone or projectID not found
}

// Function to delete a milestone by ID
function deleteMilestoneById($milestoneID) {
    global $conn;

    // Implement your SQL query to delete the milestone by its ID
    $query = "DELETE FROM milestones WHERE milestoneID = $milestoneID";

    // Execute the query
    if (mysqli_query($conn, $query)) {
        return true; // Deletion was successful
    } else {
        return false; // Deletion failed
    }
}
?>