<?php
include('includes/header.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if contractID is provided in the URL
if (isset($_GET['contractID'])) {
    $contractID = validate($_GET['contractID']);

    // Handle form submission
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Retrieve milestone details from the form
        $milestone = validate($_POST['milestone']);
        $expectedAmt = validate($_POST['expectedAmt']);
        $expectedDateBilling = validate($_POST['expectedDateBilling']);

        // Retrieve the current total of ncmilestones.expectedAmt for the given contractID
        $totalQuery = "SELECT SUM(expectedAmt) AS totalExpectedAmt FROM ncmilestones WHERE contractID = '$contractID'";
        $totalResult = mysqli_query($conn, $totalQuery);
        if (!$totalResult) {
            die("Query failed: " . mysqli_error($conn));
        }
        $totalRow = mysqli_fetch_assoc($totalResult);
        $currentTotal = $totalRow['totalExpectedAmt'];

        // Retrieve the contract amount for the specified contractID
        $contractQuery = "SELECT contractAmt FROM contracts WHERE contractID = '$contractID'";
        $contractResult = mysqli_query($conn, $contractQuery);
        if (!$contractResult) {
            die("Query failed: " . mysqli_error($conn));
        }
        $contractRow = mysqli_fetch_assoc($contractResult);
        $contractAmt = $contractRow['contractAmt'];

        // Calculate the new total expected amount including the new milestone
        $newTotal = $currentTotal + $expectedAmt;

        if ($newTotal > $contractAmt) {
            // Output an error message if the total exceeds the contract amount
            echo '<div class="alert alert-danger">Total milestone amount exceeds the contract amount.</div>';
        } else {
            // Insert milestone details into the database
            $insert_query = "INSERT INTO ncmilestones (contractID, milestone, expectedAmt, expectedDateBilling) VALUES ('$contractID', '$milestone', '$expectedAmt', '$expectedDateBilling')";
            $insert_result = mysqli_query($conn, $insert_query);
            if ($insert_result) {
                // Set session message and perform JavaScript redirection
                $_SESSION['success_message'] = "Milestone added successfully.";
                echo '<script>window.location.href = "contracts-view.php?contractID=' . $contractID . '";</script>';
                exit(); // Ensure that you exit after sending the JavaScript redirection
            } else {
                // Output an error message without redirecting
                echo '<div class="alert alert-danger">Failed to add milestone.</div>';
            }
        }
    }
} else {
    // If contractID is not provided in the URL, redirect to contracts.php
    header('Location: contracts.php');
    exit();
}
?>

<!-- HTML Form for adding a milestone -->
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3>Add Milestone</h3>
                </div>
                <div class="card-body">
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . '?contractID=' . $contractID; ?>">
                        <div class="mb-3">
                            <label for="milestone" class="form-label">Milestone</label>
                            <input type="text" class="form-control" id="milestone" name="milestone" required>
                        </div>
                        <div class="mb-3">
                            <label for="expectedAmt" class="form-label">Expected Amount</label>
                            <input type="number" step="0.01" class="form-control" id="expectedAmt" name="expectedAmt" required>
                        </div>
                        <div class="mb-3">
                            <label for="expectedDateBilling" class="form-label">Expected Date of Billing</label>
                            <input type="date" class="form-control" id="expectedDateBilling" name="expectedDateBilling" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Add Milestone</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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