<?php
include('../config/function.php'); // Include your database connection file

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Extract data from the edited contract form
    $contractID = validate($_POST['contractID']);
    $contractNo = validate($_POST['contractNo']);
    $clientID = validate($_POST['clientID']);
    $projectCoord = validate($_POST['projectCoord']);
    $teamLead = validate($_POST['teamLead']);
    $contractName = validate($_POST['contractName']);
    $contractAmount = validate($_POST['contractAmount']);
    $taxDetails = validate($_POST['taxDetails']);
    $clientPONumber = validate($_POST['clientPONumber']);
    $startDate = validate($_POST['startDate']);
    $endDate = validate($_POST['endDate']);
    
    $projectName = $contractName;

    // Update contract data in the contracts table
    $updateContractQuery = "UPDATE contracts 
                            SET contractNo = '$contractNo',
                                contractName = '$contractName',
                                contractAmt = '$contractAmount',
                                taxDetails = '$taxDetails',
                                clientPONo = '$clientPONumber',
                                ncstartDate = '$startDate',
                                ncendDate = '$endDate'
                            WHERE contractID = '$contractID'";
    
    $resultContract = mysqli_query($conn, $updateContractQuery);

    if ($resultContract) {
        // Update project data in the projects table
        $updateProjectQuery = "UPDATE projects 
                               SET clientID = '$clientID',
                                   projectCoord = '$projectCoord',
                                   contractValue = '$contractAmount',
                                   projectName = '$contractName',
                                   teamLead = '$teamLead'
                               WHERE contractID = '$contractID'";

        $resultProject = mysqli_query($conn, $updateProjectQuery);

        if ($resultProject) {
            $_SESSION['status'] = 'Contract and Project updated successfully.';
        } else {
            $_SESSION['status'] = 'Error updating Project. Please try again.';
        }
    } else {
        $_SESSION['status'] = 'Error updating Contract. Please try again.';
    }

    header('Location: contracts.php');
    exit();
} else {
    // If the form was not submitted via POST, redirect to the contracts page
    header('Location: contracts.php');
    exit();
}
?>