<?php
require("../connection.php");
include("../user.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'];
    $action = $_POST['action'];
    $remark = isset($_POST['remark']) ? $_POST['remark'] : '';

    
    if ($action === 'approve') {
        $new_status = 5; // Approved by Purchase Dept
    } elseif ($action === 'reject') {
        $new_status = 6; // Rejected by Purchase Dept
    }

    // Update the status and remark in the database
    $stmt = $con->prepare("UPDATE material_request SET sts = ?, remark = ? WHERE id = ?");
    $stmt->bind_param("isi", $new_status, $remark, $id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        if ($action === 'approve') {
            echo "<script>
                    alert('Material request approved successfully.');
                    window.location.href = 'material_request_details.php';
                  </script>";
        } elseif ($action === 'reject') {
            if (empty($remark)) {
                echo "<script>
                        alert('Please provide a remark for rejection.');
                        window.history.back();
                      </script>";
            } else {
                echo "<script>
                        alert('Material request rejected with remarks: $remark');
                        window.location.href = 'material_request_details.php';
                      </script>";
            }
        }
    } else {
        echo "<script>
                alert('Error: Unable to update the material request status.');
                window.history.back();
              </script>";
    }

    $stmt->close();
    $con->close();
}
?>
