<?php
// Enable error reporting for debugging purposes (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
include('../config/dbcon.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $projectIDs = $_POST['projectID'];
    $cumulativeDMs = $_POST['cumulative_dm'];

    // Loop through project IDs and corresponding Cumulative DM values
    for ($i = 0; $i < count($projectIDs); $i++) {
        $projectID = $projectIDs[$i];
        $cumulativeDM = $cumulativeDMs[$i];

        // Update the Cumulative DM for Previous Month with the new value
        // You'll need to adjust this query based on your database schema
        if ($cumulativeDM !== '') {
            $updateQuery = "UPDATE projects SET directMaterialcost = '$cumulativeDM' WHERE projectID = '$projectID'";

            // Execute the update query
            $result = mysqli_query($conn, $updateQuery);

            if (!$result) {
                // Handle the database update error
                die("Update failed: " . mysqli_error($conn));
            }
        }
    }

    // Redirect back to DirectMaterial.php
    header("Location: DirectMaterial.php");
    exit();
} else {
    // Handle invalid requests (e.g., direct access to this script)
    header("Location: DirectMaterial.php");
}
?>