<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('session.php');
include('stock_helpers.php');

$complaintRole = $_SESSION['role'] ?? '';
if(in_array($complaintRole, array('ge_admin', 'department_admin', 'je'), true)) {
    $_SESSION['error'] = 'This login has view and print access only.';
    header('Location: complaints.php');
    exit;
}

if(isset($_POST['submit'])) {

    $ucid = (int)$_POST['id'];
    $remarks = $conn->real_escape_string($_POST['remarks']);
    $c_status = (int)$_POST['c_status'];

    $completiondate = '';
    if($c_status == 2) {
        $completiondate = ", completiondate = NOW()";
    }

    $update = $conn->query("
        UPDATE users_complaint 
        SET 
            remarks = '$remarks',
            c_status = '$c_status'
            $completiondate
        WHERE ucid = '$ucid'
    ");

    if($update) {

        if($c_status == 2) {

            $conn->query("DELETE FROM complaint_used_material WHERE ucid = '$ucid'");
            $materialRows = array();

            if(!empty($_POST['material_id'])) {

                foreach($_POST['material_id'] as $key => $material_id) {

                    $material_id = (int)$material_id;
                    $qty = isset($_POST['qty'][$key]) ? (float)$_POST['qty'][$key] : 0;
                    $unit = $conn->real_escape_string($_POST['unit'][$key] ?? '');

                    if($material_id > 0 && $qty > 0) {

                        $matQ = $conn->query("
                            SELECT material_name, m_unit 
                            FROM matrial 
                            WHERE m_id = '$material_id'
                        ");

                        if($matQ && $matQ->num_rows > 0) {
                            $mat = $matQ->fetch_assoc();

                            $material_name = $conn->real_escape_string($mat['material_name']);
                            $final_unit = !empty($unit) ? $unit : $conn->real_escape_string($mat['m_unit']);

                            $conn->query("
                                INSERT INTO complaint_used_material
                                (
                                    ucid,
                                    material_id,
                                    material_name,
                                    qty,
                                    unit
                                )
                                VALUES
                                (
                                    '$ucid',
                                    '$material_id',
                                    '$material_name',
                                    '$qty',
                                    '$final_unit'
                                )
                            ");

                            $materialRows[] = array(
                                'material_id' => $material_id,
                                'qty' => $qty
                            );
                        }
                    }
                }
            }

            $stockError = stock_record_complaint_material_usage($conn, $ucid, $materialRows, (int)($_SESSION['admin'] ?? 0));
            if($stockError != '') {
                $_SESSION['error'] = $stockError;
                header("Location: ".$_SERVER['HTTP_REFERER']);
                exit;
            }
        } else {
            $reference = $conn->real_escape_string('COMPLAINT-'.$ucid);
            $conn->query("DELETE FROM complaint_used_material WHERE ucid = '$ucid'");
            $conn->query("DELETE FROM stock_transactions WHERE reference_no = '$reference'");
        }

        $_SESSION['success'] = "Complaint updated successfully";
    } else {
        $_SESSION['error'] = "Something went wrong";
    }

    header("Location: ".$_SERVER['HTTP_REFERER']);
    exit;
}
?>
