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

if (!stock_is_admin() && !stock_is_bso()) {
    header('location: dashboard.php');
    exit;
}

$msg = $err = '';
$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editData = null;

if ($edit_id > 0) {
    $editQ = $conn->query("SELECT * FROM matrial WHERE m_id='$edit_id' LIMIT 1");
    if ($editQ && $editQ->num_rows > 0) {
        $editData = $editQ->fetch_assoc();
    }
}

if (isset($_GET['delete'])) {
    $delete_id = (int)$_GET['delete'];
    $usedStock = $conn->query("SELECT id FROM stock_transactions WHERE material_id='$delete_id' LIMIT 1");
    $usedComplaint = $conn->query("SELECT id FROM complaint_used_material WHERE material_id='$delete_id' LIMIT 1");

    if(($usedStock && $usedStock->num_rows > 0) || ($usedComplaint && $usedComplaint->num_rows > 0)) {
        $err = 'Material cannot be deleted because it is already used in stock or complaint records.';
    } elseif ($conn->query("DELETE FROM matrial WHERE m_id='$delete_id'")) {
        $msg = 'Material deleted successfully.';
    } else {
        $err = $conn->error;
    }
}

if (isset($_POST['submit'])) {
    $material_id = isset($_POST['material_id']) ? (int)$_POST['material_id'] : 0;
    $material_name = mysqli_real_escape_string($conn, trim($_POST['material_name']));
    $material_code = mysqli_real_escape_string($conn, trim($_POST['material_code']));
    $unit = mysqli_real_escape_string($conn, trim($_POST['unit']));

    if ($material_id > 0) {
        $sql = "UPDATE matrial SET material_name='$material_name', serial_number='$material_code', m_unit='$unit' WHERE m_id='$material_id'";
    } else {
        $sql = "INSERT INTO matrial
                (material_name, serial_number, s_code, m_unit, nature_cmp, section, material_rate, min_stock, sihl_page, div_stock_sihl, user_id, update_id, nwdate)
                VALUES
                ('$material_name', '$material_code', '0', '$unit', '0', '', '', '', '', '', '0', '0', NOW())";
    }

    if ($conn->query($sql)) {
        $msg = $material_id > 0 ? 'Material updated successfully.' : 'Material added successfully.';
        $editData = null;
    } else {
        $err = $conn->error;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS ADMIN | Stock Materials</title>
    <?php include('includes/head.php'); ?>
    <style>th,td{text-align:center;vertical-align:middle;}</style>
</head>
<body>
<div class="container-scroller">
    <div class="horizontal-menu"><?php include('includes/header.php'); ?></div>
    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="page-header"><h3 class="page-title">Stock Material Master</h3></div>

                <?php if ($err) { ?><div class="alert alert-danger"><?php echo $err; ?></div><?php } ?>
                <?php if ($msg) { ?><div class="alert alert-success"><?php echo $msg; ?></div><?php } ?>

                <div class="card grid-margin">
                    <div class="card-body">
                        <h4 class="card-title"><?php echo $editData ? 'Edit Material' : 'Add Material'; ?></h4>
                        <form method="POST">
                            <input type="hidden" name="material_id" value="<?php echo $editData['m_id'] ?? ''; ?>">
                            <div class="row">
                                <div class="col-md-4 form-group">
                                    <label>Material Name</label>
                                    <input type="text" name="material_name" required class="form-control" value="<?php echo $editData['material_name'] ?? ''; ?>">
                                </div>
                                <div class="col-md-4 form-group">
                                    <label>Material Code</label>
                                    <input type="text" name="material_code" class="form-control" value="<?php echo $editData['serial_number'] ?? ''; ?>">
                                </div>
                                <div class="col-md-4 form-group">
                                    <label>Unit</label>
                                    <input type="text" name="unit" required class="form-control" value="<?php echo $editData['m_unit'] ?? 'Nos'; ?>">
                                </div>
                            </div>
                            <button type="submit" name="submit" class="btn btn-primary"><?php echo $editData ? 'Update' : 'Submit'; ?></button>
                            <?php if ($editData) { ?><a href="stockMaterials.php" class="btn btn-light">Cancel</a><?php } ?>
                        </form>
                    </div>
                </div>

                <div class="card grid-margin">
                    <div class="card-body">
                        <h4 class="card-title">All Materials</h4>
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered">
                                <thead>
                                <tr>
                                    <th>Sr No.</th>
                                    <th>Material</th>
                                    <th>Code</th>
                                    <th>Unit</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                $materials = $conn->query("SELECT * FROM matrial ORDER BY material_name ASC");
                                $count = 0;
                                if ($materials && $materials->num_rows > 0) {
                                    while ($row = $materials->fetch_assoc()) {
                                        $count++;
                                ?>
                                    <tr>
                                        <td><?php echo $count; ?></td>
                                        <td><?php echo $row['material_name']; ?></td>
                                        <td><?php echo $row['serial_number']; ?></td>
                                        <td><?php echo $row['m_unit']; ?></td>
                                        <td>
                                            <a href="stockMaterials.php?edit=<?php echo $row['m_id']; ?>" class="btn btn-xs btn-outline-primary">Edit</a>
                                            <a href="stockMaterials.php?delete=<?php echo $row['m_id']; ?>" onclick="return confirm('Are you sure?')" class="btn btn-xs btn-outline-danger">Delete</a>
                                        </td>
                                    </tr>
                                <?php }} else { ?>
                                    <tr><td colspan="5">No Records Found!</td></tr>
                                <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include('includes/footer.php'); ?>
        </div>
    </div>
</div>
<?php include('includes/foot.php'); ?>
</body>
</html>
