<?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 receipt details from the database
    $query = "SELECT * FROM ncbilldetails WHERE billID = '$billID'";
    $result = mysqli_query($conn, $query);

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

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

    // Handle form submission
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Retrieve updated receipt details from the form
        $milestoneID = validate($_POST['milestoneID']);
        $receivedAmt = validate($_POST['receivedAmt']);
        $chequeNo = validate($_POST['chequeNo']);
        $receivedDate = validate($_POST['receivedDate']);

        // Update receipt details in the database
        $update_query = "UPDATE ncbilldetails SET ncmilestoneID = '$milestoneID', receivedAmt = '$receivedAmt', chequeNo = '$chequeNo', receivedDate = '$receivedDate' 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'] = "Receipt details updated successfully.";
            echo '<script>window.location.href = "contracts-view.php?contractID=' . $contractID . '";</script>';
            exit();
        } else {
            echo '<div class="alert alert-danger">Failed to update receipt details.</div>';
        }
    }
} else {
    // If billID is not provided in the URL, redirect to contracts.php
    header('Location: contracts.php');
    exit();
}
?>

<!-- HTML Form for editing receipt 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 Receipt Details</h3>
                </div>
                <div class="card-body">
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . '?billID=' . $billID; ?>">
                        <div class="mb-3">
                            <label for="milestoneID" class="form-label">Select 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'] == $receiptData['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="receivedAmt" class="form-label">Received Amount</label>
                            <input type="text" class="form-control" id="receivedAmt" name="receivedAmt" value="<?php echo $receiptData['receivedAmt']; ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="chequeNo" class="form-label">Cheque Number</label>
                            <input type="text" class="form-control" id="chequeNo" name="chequeNo" value="<?php echo $receiptData['chequeNo']; ?>">
                        </div>
                        <div class="mb-3">
                            <label for="receivedDate" class="form-label">Received Date</label>
                            <input type="date" class="form-control" id="receivedDate" name="receivedDate" value="<?php echo $receiptData['receivedDate']; ?>" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Update Receipt Details</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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