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

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

    // Fetch current billing details from the database
    $query = "SELECT * FROM ncbilldetails WHERE billID = '$billID'";
    $result = mysqli_query($conn, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $billingData = mysqli_fetch_assoc($result);

        // Get the contractID from the associated milestone
        $contractIDQuery = "SELECT contractID FROM ncmilestones WHERE ncmilestoneID = " . $billingData['ncmilestoneID'];
        $contractIDResult = mysqli_query($conn, $contractIDQuery);
        $contractIDRow = mysqli_fetch_assoc($contractIDResult);
        $contractID = $contractIDRow['contractID'];
    } else {
        echo '<div class="alert alert-danger">Billing details not found.</div>';
        include('includes/footer.php');
        exit();
    }

    // Handle form submission
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Retrieve updated billing details from the form
        $milestoneID = validate($_POST['milestoneID']);
        $billNo = validate($_POST['billNo']);
        $billAmount = validate($_POST['billAmount']);
        $billDate = validate($_POST['billDate']);
        $expRecDate = validate($_POST['expRecDate']);

        // Update billing details in the database
        $update_query = "UPDATE ncbilldetails SET ncmilestoneID = '$milestoneID', billNo = '$billNo', billAmount = '$billAmount', billDate = '$billDate', expRecDate = '$expRecDate' WHERE billID = '$billID'";
        $update_result = mysqli_query($conn, $update_query);

        if ($update_result) {
            // Redirect to the contracts view page with success message
            $_SESSION['success_message'] = "Billing details updated successfully.";
            // JavaScript redirection
            echo '<script>window.location.href = "contracts-view.php?contractID=' . $contractID . '";</script>';
            exit();
        } else {
            echo '<div class="alert alert-danger">Failed to update billing details.</div>';
        }
    }
} else {
    // If billID is not provided in the URL, redirect to contracts.php
    header('Location: contracts.php');
    exit();
}
?>

<!-- HTML Form for editing billing details -->
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h3>Edit Billing Details</h3>
                </div>
                <div class="card-body">
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . '?billID=' . $billID; ?>">
                        <!-- Here, you can include a dropdown/select option to choose the milestone -->
                        <div class="mb-3">
                            <label for="milestoneID" class="form-label">Milestone</label>
                            <select class="form-select" id="milestoneID" name="milestoneID" required>
                                <option value="">Select a milestone</option>
                                <!-- Populate milestone options dynamically -->
                                <?php
                                $milestone_query = "SELECT ncmilestoneID, milestone FROM ncmilestones WHERE contractID = $contractID";
                                $milestone_result = mysqli_query($conn, $milestone_query);

                                if ($milestone_result && mysqli_num_rows($milestone_result) > 0) {
                                    while ($milestone_row = mysqli_fetch_assoc($milestone_result)) {
                                        $selected = ($milestone_row['ncmilestoneID'] == $billingData['ncmilestoneID']) ? 'selected' : '';
                                        echo '<option value="' . $milestone_row['ncmilestoneID'] . '" ' . $selected . '>' . $milestone_row['milestone'] . '</option>';
                                    }
                                } else {
                                    echo '<option value="">No milestones found</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="billNo" class="form-label">Bill Number</label>
                            <input type="text" class="form-control" id="billNo" name="billNo" value="<?php echo $billingData['billNo']; ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="billAmount" class="form-label">Billing Amount</label>
                            <input type="text" class="form-control" id="billAmount" name="billAmount" value="<?php echo $billingData['billAmount']; ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="billDate" class="form-label">Billing Date</label>
                            <input type="date" class="form-control" id="billDate" name="billDate" value="<?php echo $billingData['billDate']; ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="expRecDate" class="form-label">Expected Receive Date</label>
                            <input type="date" class="form-control" id="expRecDate" name="expRecDate" value="<?php echo $billingData['expRecDate']; ?>" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Update Billing Details</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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