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

if (!stock_can_view()) {
    header('location: dashboard.php');
    exit;
}

$msg = $err = '';
$role = stock_role();

function render_stock_material_options($conn, $holder_type = '', $holder_id = 0)
{
    $materials = $conn->query(stock_material_select_sql());
    $printed = 0;
    while ($materials && $mat = $materials->fetch_assoc()) {
        if ($holder_type !== '' && $holder_id > 0 && stock_balance($conn, $mat['id'], $holder_type, $holder_id) <= 0) {
            continue;
        }
        echo '<option value="'.$mat['id'].'">'.htmlspecialchars(stock_material_label($mat)).'</option>';
        $printed++;
    }

    if ($printed == 0) {
        echo '<option value="" disabled>No material stock available</option>';
    }
}

function stock_transfer_material_options_html($conn, $holder_type, $holder_id)
{
    $holder_type = mysqli_real_escape_string($conn, $holder_type);
    $holder_id = (int)$holder_id;
    $materials = $conn->query(stock_material_select_sql());
    $html = '<option value="">Select Material</option>';
    $printed = 0;

    while ($materials && $mat = $materials->fetch_assoc()) {
        if ($holder_type !== '' && $holder_id > 0 && stock_balance($conn, $mat['id'], $holder_type, $holder_id) <= 0) {
            continue;
        }
        $html .= '<option value="'.$mat['id'].'">'.htmlspecialchars(stock_material_label($mat)).'</option>';
        $printed++;
    }

    if ($printed == 0) {
        $html .= '<option value="" disabled>No material stock available for selected holder</option>';
    }

    return $html;
}

function stock_transfer_holder_options_html($conn, $holder_type, $division_id)
{
    $holder_type = mysqli_real_escape_string($conn, $holder_type);
    $division_id = (int)$division_id;
    $html = '<option value="">Select '.ucwords($holder_type).'</option>';

    if ($holder_type === 'bso') {
        $where = "WHERE (role='bso' OR type='bso') AND status='1'";
        if ($division_id > 0) {
            $where .= " AND (division_id='$division_id' OR division_id IS NULL OR division_id='0')";
        }
        $holders = $conn->query("
            SELECT id, COALESCE(NULLIF(name, ''), NULLIF(mobile, ''), CONCAT('BSO #', id)) AS display_name
            FROM admin
            $where
            ORDER BY display_name ASC
        ");
    } elseif ($holder_type === 'department') {
        $where = "WHERE status='1'";
        if ($division_id > 0) {
            $where .= " AND division_id='$division_id'";
        }
        $holders = $conn->query("
            SELECT id, COALESCE(NULLIF(name, ''), CONCAT('Department #', id)) AS display_name
            FROM departments
            $where
            ORDER BY display_name ASC
        ");
    } elseif ($holder_type === 'contractor') {
        $where = "WHERE (a.role='contractor' OR a.type='contractor') AND a.status='1'";
        if ($division_id > 0) {
            $where .= " AND (a.division_id='$division_id' OR dep.division_id='$division_id')";
        }
        $holders = $conn->query("
            SELECT a.id, COALESCE(NULLIF(a.name, ''), NULLIF(a.mobile, ''), CONCAT('Contractor #', a.id)) AS display_name
            FROM admin a
            LEFT JOIN departments dep ON dep.id = a.department_id
            $where
            ORDER BY display_name ASC
        ");
    } else {
        return '<option value="">Select Holder Type First</option>';
    }

    if ($holders && $holders->num_rows > 0) {
        while ($holder = $holders->fetch_assoc()) {
            $html .= '<option value="'.$holder['id'].'">'.htmlspecialchars($holder['display_name']).'</option>';
        }
    } else {
        $html .= '<option value="" disabled>No holder found in this division</option>';
    }

    return $html;
}

function stock_transfer_holder_allowed_for_division($conn, $holder_type, $holder_id, $division_id)
{
    $holder_type = mysqli_real_escape_string($conn, $holder_type);
    $holder_id = (int)$holder_id;
    $division_id = (int)$division_id;

    if ($holder_id <= 0) {
        return false;
    }

    if ($holder_type === 'bso') {
        $where = "id='$holder_id' AND (role='bso' OR type='bso') AND status='1'";
        if ($division_id > 0) {
            $where .= " AND division_id='$division_id'";
        }
        $q = $conn->query("SELECT id FROM admin WHERE $where LIMIT 1");
        return $q && $q->num_rows > 0;
    }

    if ($holder_type === 'department') {
        $where = "id='$holder_id' AND status='1'";
        if ($division_id > 0) {
            $where .= " AND division_id='$division_id'";
        }
        $q = $conn->query("SELECT id FROM departments WHERE $where LIMIT 1");
        return $q && $q->num_rows > 0;
    }

    if ($holder_type === 'contractor') {
        $where = "a.id='$holder_id' AND (a.role='contractor' OR a.type='contractor') AND a.status='1'";
        if ($division_id > 0) {
            $where .= " AND (a.division_id='$division_id' OR dep.division_id='$division_id')";
        }
        $q = $conn->query("
            SELECT a.id
            FROM admin a
            LEFT JOIN departments dep ON dep.id = a.department_id
            WHERE $where
            LIMIT 1
        ");
        return $q && $q->num_rows > 0;
    }

    return false;
}

if (isset($_POST['action']) && $_POST['action'] === 'get_holders') {
    $holder_type = $_POST['holder_type'] ?? '';
    $division_id = (int)($_POST['division_id'] ?? 0);

    if (stock_role() === 'ge_admin') {
        $division_id = (int)($_SESSION['division_id'] ?? 0);
    }

    echo stock_transfer_holder_options_html($conn, $holder_type, $division_id);
    exit;
}

if (isset($_POST['action']) && $_POST['action'] === 'get_materials') {
    $holder_type = $_POST['holder_type'] ?? '';
    $holder_id = (int)($_POST['holder_id'] ?? 0);
    echo stock_transfer_material_options_html($conn, $holder_type, $holder_id);
    exit;
}

if (isset($_POST['submit'])) {
    $material_id = (int)$_POST['material_id'];
    $quantity = (float)$_POST['quantity'];
    $reference_no = mysqli_real_escape_string($conn, trim($_POST['reference_no']));
    $remarks = mysqli_real_escape_string($conn, trim($_POST['remarks']));
    $created_by = (int)$_SESSION['admin'];
    $from_type = '';
    $from_id = 0;
    $to_type = '';
    $to_id = 0;
    $transaction_type = 'issue';
    $division_id = (int)($_POST['division_id'] ?? ($_SESSION['division_id'] ?? 0));

    if (stock_is_bso()) {
        $from_type = 'bso';
        $from_id = (int)$_SESSION['admin'];
        $to_type = 'department';
        $to_id = (int)$_POST['department_id'];
        $transaction_type = 'issue';
    } elseif (stock_is_department()) {
        $from_type = 'department';
        $from_id = (int)$_SESSION['department_id'];
        $target = $_POST['target'] ?? '';
        if ($target === 'contractor') {
            $to_type = 'contractor';
            $to_id = (int)$_POST['contractor_id'];
            $transaction_type = 'issue';
        } elseif ($target === 'bso') {
            $to_type = 'bso';
            $to_id = (int)$_POST['bso_id'];
            $transaction_type = 'return';
        } else {
            $to_type = '';
            $to_id = 0;
        }
    } elseif (stock_is_contractor()) {
        $from_type = 'contractor';
        $from_id = (int)$_SESSION['admin'];
        $to_type = 'department';
        $to_id = (int)$_SESSION['department_id'];
        $transaction_type = 'return';
    } elseif (stock_is_admin()) {
        if (stock_role() === 'ge_admin') {
            $division_id = (int)($_SESSION['division_id'] ?? 0);
        }
        $from_type = mysqli_real_escape_string($conn, $_POST['from_type']);
        $from_id = (int)$_POST['from_id'];
        $to_type = mysqli_real_escape_string($conn, $_POST['to_type']);
        $to_id = (int)$_POST['to_id'];
        $transaction_type = $_POST['transaction_type'] === 'return' ? 'return' : 'issue';
    }

    $available = stock_balance($conn, $material_id, $from_type, $from_id);

    if ($material_id <= 0 || $quantity <= 0 || empty($from_type) || empty($to_type) || $from_id <= 0 || $to_id <= 0) {
        $err = 'Please fill all required fields.';
    } elseif (stock_is_admin() && $division_id <= 0) {
        $err = 'Please select division.';
    } elseif (stock_is_admin() && !stock_transfer_holder_allowed_for_division($conn, $from_type, $from_id, $division_id)) {
        $err = 'Please select a valid source holder for selected division.';
    } elseif (stock_is_admin() && !stock_transfer_holder_allowed_for_division($conn, $to_type, $to_id, $division_id)) {
        $err = 'Please select a valid destination holder for selected division.';
    } elseif (!stock_holder_allowed($conn, $from_type, $from_id)) {
        $err = 'Please select a valid source holder.';
    } elseif (!stock_holder_allowed($conn, $to_type, $to_id)) {
        $err = 'Please select a valid destination holder.';
    } elseif (stock_is_department() && $target === 'contractor' && $to_id <= 0) {
        $err = 'Please select contractor.';
    } elseif (stock_is_department() && $target === 'bso' && $to_id <= 0) {
        $err = 'Please select BSO store.';
    } elseif ($from_type === $to_type && $from_id === $to_id) {
        $err = 'Source and destination cannot be same.';
    } elseif ($available < $quantity) {
        $err = 'Insufficient stock. Available quantity is '.rtrim(rtrim(number_format($available, 2, '.', ''), '0'), '.').'.';
    } else {
        $sql = "INSERT INTO stock_transactions
                (material_id, quantity, transaction_type, from_holder_type, from_holder_id, to_holder_type, to_holder_id, reference_no, remarks, created_by)
                VALUES
                ('$material_id', '$quantity', '$transaction_type', '$from_type', '$from_id', '$to_type', '$to_id', '$reference_no', '$remarks', '$created_by')";

        if ($conn->query($sql)) {
            $msg = $transaction_type === 'return' ? 'Stock returned successfully.' : 'Stock transferred successfully.';
        } else {
            $err = $conn->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS ADMIN | Stock Transfer</title>
    <?php include('includes/head.php'); ?>
    <style>
        th,td{text-align:center;vertical-align:middle;}
        .stock-transfer-form .form-group { margin-bottom: 18px; }
        .stock-transfer-form label { font-weight: 600; color: #3b4047; }
        .stock-transfer-form .select2-container,
        .stock-transfer-form .form-control { min-height: 46px; }
        .stock-transfer-form .select2-container--default .select2-selection--single {
            height: 46px;
            border-color: #d4d7dc;
        }
        .stock-transfer-form .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 46px;
            text-align: left;
        }
        .stock-transfer-form .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px;
            top: 0;
        }
        .stock-transfer-form .select2-container { width: 100% !important; }
        .stock-transfer-actions { margin-top: 6px; }
    </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 Transfer / Restock Return</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">
                        <form method="POST" class="stock-transfer-form">
                            <div class="row">
                                <?php if (!stock_is_admin()) { ?>
                                    <div class="col-md-4 form-group">
                                        <label>Material</label>
                                        <select name="material_id" id="material_id" required class="form-control">
                                            <option value="">Select Material</option>
                                            <?php
                                            $material_holder_type = '';
                                            $material_holder_id = 0;
                                            if (stock_is_bso()) {
                                                $material_holder_type = 'bso';
                                                $material_holder_id = (int)$_SESSION['admin'];
                                            } elseif (stock_is_department()) {
                                                $material_holder_type = 'department';
                                                $material_holder_id = (int)$_SESSION['department_id'];
                                            } elseif (stock_is_contractor()) {
                                                $material_holder_type = 'contractor';
                                                $material_holder_id = (int)$_SESSION['admin'];
                                            }
                                            render_stock_material_options($conn, $material_holder_type, $material_holder_id);
                                            ?>
                                        </select>
                                    </div>
                                <?php } ?>

                                <?php if (stock_is_bso()) { ?>
                                    <div class="col-md-4 form-group">
                                        <label>Transfer To Department</label>
                                        <select name="department_id" required class="form-control">
                                            <option value="">Select Department</option>
                                            <?php
                                            $deps = $conn->query("SELECT * FROM departments WHERE status='1' ".stock_department_scope_sql('AND')." ORDER BY name ASC");
                                            while ($dep = $deps->fetch_assoc()) {
                                            ?>
                                                <option value="<?php echo $dep['id']; ?>"><?php echo $dep['name']; ?></option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                <?php } elseif (stock_is_department()) { ?>
                                    <div class="col-md-4 form-group">
                                        <label>Movement Type</label>
                                        <select name="target" id="target" required class="form-control">
                                            <option value="contractor">Issue To Contractor</option>
                                            <option value="bso">Return To BSO</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 form-group target-contractor">
                                        <label>Contractor</label>
                                        <select name="contractor_id" class="form-control">
                                            <option value="">Select Contractor</option>
                                            <?php
                                            $dept_id = (int)$_SESSION['department_id'];
                                            $deptDivision = (int)($_SESSION['division_id'] ?? 0);
                                            $contractorWhere = "(role='contractor' OR type='contractor') AND status='1' AND (department_id='$dept_id'";
                                            if ($deptDivision > 0) {
                                                $contractorWhere .= " OR division_id='$deptDivision'";
                                            }
                                            $contractorWhere .= ")";
                                            $contractors = $conn->query("
                                                SELECT id, COALESCE(NULLIF(name, ''), NULLIF(mobile, ''), CONCAT('Contractor #', id)) AS display_name
                                                FROM admin
                                                WHERE $contractorWhere
                                                ORDER BY display_name ASC
                                            ");
                                            while ($contractor = $contractors->fetch_assoc()) {
                                            ?>
                                                <option value="<?php echo $contractor['id']; ?>"><?php echo htmlspecialchars($contractor['display_name']); ?></option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 form-group target-bso" style="display:none;">
                                        <label>BSO Store</label>
                                        <select name="bso_id" class="form-control">
                                            <option value="">Select BSO</option>
                                            <?php
                                            $deptDivision = (int)($_SESSION['division_id'] ?? 0);
                                            $bsoWhere = "(role='bso' OR type='bso') AND status='1'";
                                            if ($deptDivision > 0) {
                                                $bsoWhere .= " AND (division_id='$deptDivision' OR division_id IS NULL OR division_id='0')";
                                            }
                                            $bsos = $conn->query("
                                                SELECT id, COALESCE(NULLIF(name, ''), NULLIF(mobile, ''), CONCAT('BSO #', id)) AS display_name
                                                FROM admin
                                                WHERE $bsoWhere
                                                ORDER BY display_name ASC
                                            ");
                                            while ($bso = $bsos->fetch_assoc()) {
                                            ?>
                                                <option value="<?php echo $bso['id']; ?>"><?php echo htmlspecialchars($bso['display_name']); ?></option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                <?php } elseif (stock_is_contractor()) { ?>
                                    <div class="col-md-4 form-group">
                                        <label>Return To Department</label>
                                        <?php
                                        $deptName = '';
                                        $dept_id = (int)$_SESSION['department_id'];
                                        $deptQ = $conn->query("SELECT name FROM departments WHERE id='$dept_id' LIMIT 1");
                                        if ($deptQ && $deptQ->num_rows > 0) {
                                            $deptName = $deptQ->fetch_assoc()['name'];
                                        }
                                        ?>
                                        <input type="text" class="form-control" value="<?php echo $deptName; ?>" readonly>
                                    </div>
                                <?php } else { ?>
                                    <div class="col-md-3 form-group">
                                        <label>Division</label>
                                        <?php if (stock_role() === 'ge_admin') {
                                            $loginDivision = (int)($_SESSION['division_id'] ?? 0);
                                            $divisionName = '';
                                            $divisionQ = $conn->query("SELECT name FROM divisions WHERE id='$loginDivision' LIMIT 1");
                                            if ($divisionQ && $divisionQ->num_rows > 0) {
                                                $divisionName = $divisionQ->fetch_assoc()['name'];
                                            }
                                        ?>
                                            <input type="hidden" name="division_id" id="division_id" value="<?php echo $loginDivision; ?>">
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($divisionName); ?>" readonly>
                                        <?php } else { ?>
                                            <select name="division_id" id="division_id" class="form-control" required>
                                                <option value="">Select Division</option>
                                                <?php
                                                $divisions = $conn->query("SELECT id, name FROM divisions WHERE status='1' ORDER BY name ASC");
                                                while ($division = $divisions->fetch_assoc()) {
                                                ?>
                                                    <option value="<?php echo $division['id']; ?>"><?php echo htmlspecialchars($division['name']); ?></option>
                                                <?php } ?>
                                            </select>
                                        <?php } ?>
                                    </div>
                                    <div class="col-md-2 form-group">
                                        <label>Type</label>
                                        <select name="transaction_type" class="form-control">
                                            <option value="issue">Issue</option>
                                            <option value="return">Return</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2 form-group">
                                        <label>From Type</label>
                                        <select name="from_type" id="from_type" class="form-control transfer-holder-type" data-target="from_id">
                                            <option value="">Select Type</option>
                                            <option value="bso">BSO</option>
                                            <option value="department">Department</option>
                                            <option value="contractor">Contractor</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 form-group">
                                        <label>From Holder</label>
                                        <select name="from_id" id="from_id" class="form-control transfer-holder-select" required>
                                            <option value="">Select Division and From Type First</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 form-group">
                                        <label>Material</label>
                                        <select name="material_id" id="material_id" required class="form-control">
                                            <option value="">Select From Holder First</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2 form-group">
                                        <label>To Type</label>
                                        <select name="to_type" id="to_type" class="form-control transfer-holder-type" data-target="to_id">
                                            <option value="">Select Type</option>
                                            <option value="department">Department</option>
                                            <option value="contractor">Contractor</option>
                                            <option value="bso">BSO</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 form-group">
                                        <label>To Holder</label>
                                        <select name="to_id" id="to_id" class="form-control transfer-holder-select" required>
                                            <option value="">Select Division and To Type First</option>
                                        </select>
                                    </div>
                                <?php } ?>

                                <div class="col-md-2 form-group">
                                    <label>Quantity</label>
                                    <input type="number" name="quantity" required min="0.01" step="0.01" class="form-control">
                                </div>
                                <div class="col-md-3 form-group">
                                    <label>Reference No.</label>
                                    <input type="text" name="reference_no" class="form-control">
                                </div>
                                <div class="col-md-5 form-group">
                                    <label>Remarks</label>
                                    <input type="text" name="remarks" class="form-control">
                                </div>
                            </div>
                            <div class="stock-transfer-actions">
                                <button type="submit" name="submit" class="btn btn-primary">Submit Movement</button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card grid-margin">
                    <div class="card-body">
                        <h4 class="card-title">My Current Stock</h4>
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered">
                                <thead><tr><th>Material</th><th>Unit</th><th>Pending Stock</th></tr></thead>
                                <tbody>
                                <?php
                                $holder_type = '';
                                $holder_id = 0;
                                if (stock_is_bso()) {
                                    $holder_type = 'bso';
                                    $holder_id = (int)$_SESSION['admin'];
                                } elseif (stock_is_department()) {
                                    $holder_type = 'department';
                                    $holder_id = (int)$_SESSION['department_id'];
                                } elseif (stock_is_contractor()) {
                                    $holder_type = 'contractor';
                                    $holder_id = (int)$_SESSION['admin'];
                                }

                                if ($holder_type) {
                                    $materials = $conn->query(stock_material_select_sql());
                                    while ($mat = $materials->fetch_assoc()) {
                                        $bal = stock_balance($conn, $mat['id'], $holder_type, $holder_id);
                                ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars(stock_material_label($mat)); ?></td>
                                            <td><?php echo $mat['unit']; ?></td>
                                            <td><?php echo rtrim(rtrim(number_format($bal, 2, '.', ''), '0'), '.'); ?></td>
                                        </tr>
                                <?php }} else { ?>
                                    <tr><td colspan="3">Use Stock Report for full admin stock view.</td></tr>
                                <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include('includes/footer.php'); ?>
        </div>
    </div>
</div>
<?php include('includes/foot.php'); ?>
<script>
function toggleTarget() {
    var target = document.getElementById('target');
    if (!target) return;
    var contractor = document.querySelector('.target-contractor');
    var bso = document.querySelector('.target-bso');
    var contractorSelect = document.querySelector('select[name="contractor_id"]');
    var bsoSelect = document.querySelector('select[name="bso_id"]');
    if (target.value === 'bso') {
        if (contractor) contractor.style.display = 'none';
        if (bso) bso.style.display = 'block';
        if (contractorSelect) {
            contractorSelect.disabled = true;
            contractorSelect.required = false;
            contractorSelect.value = '';
            if (window.jQuery) jQuery(contractorSelect).val('').trigger('change.select2');
        }
        if (bsoSelect) {
            bsoSelect.disabled = false;
            bsoSelect.required = true;
        }
    } else {
        if (contractor) contractor.style.display = 'block';
        if (bso) bso.style.display = 'none';
        if (contractorSelect) {
            contractorSelect.disabled = false;
            contractorSelect.required = true;
        }
        if (bsoSelect) {
            bsoSelect.disabled = true;
            bsoSelect.required = false;
            bsoSelect.value = '';
            if (window.jQuery) jQuery(bsoSelect).val('').trigger('change.select2');
        }
    }
}
var targetSelect = document.getElementById('target');
if (targetSelect) {
    targetSelect.addEventListener('change', toggleTarget);
    if (window.jQuery) {
        jQuery(targetSelect).on('change.select2 change', toggleTarget);
    }
    toggleTarget();
    setTimeout(toggleTarget, 200);
}

function resetSelect2Value(selector, html) {
    if (!window.jQuery) return;
    var $select = jQuery(selector);
    if (!$select.length) return;
    $select.html(html);
    $select.val('');
    $select.trigger('change.select2');
}

function loadTransferHolders(typeSelector) {
    if (!window.jQuery) return;

    var $type = jQuery(typeSelector);
    var targetSelector = '#' + $type.data('target');
    var holderType = $type.val();
    var divisionId = jQuery('#division_id').val();

    if (!divisionId) {
        resetSelect2Value(targetSelector, '<option value="">Select Division First</option>');
        return;
    }

    if (!holderType) {
        resetSelect2Value(targetSelector, '<option value="">Select Holder Type First</option>');
        return;
    }

    resetSelect2Value(targetSelector, '<option value="">Loading...</option>');

    jQuery.ajax({
        url: '',
        type: 'POST',
        data: {
            action: 'get_holders',
            division_id: divisionId,
            holder_type: holderType
        },
        success: function(html) {
            resetSelect2Value(targetSelector, html);
        },
        error: function() {
            resetSelect2Value(targetSelector, '<option value="">Holder loading error</option>');
        }
    });
}

function loadTransferMaterials() {
    if (!window.jQuery) return;

    var holderType = jQuery('#from_type').val();
    var holderId = jQuery('#from_id').val();

    if (!jQuery('#from_type').length || !jQuery('#from_id').length) {
        return;
    }

    if (!holderType || !holderId) {
        resetSelect2Value('#material_id', '<option value="">Select From Holder First</option>');
        return;
    }

    resetSelect2Value('#material_id', '<option value="">Loading...</option>');

    jQuery.ajax({
        url: '',
        type: 'POST',
        data: {
            action: 'get_materials',
            holder_type: holderType,
            holder_id: holderId
        },
        success: function(html) {
            resetSelect2Value('#material_id', html);
        },
        error: function() {
            resetSelect2Value('#material_id', '<option value="">Material loading error</option>');
        }
    });
}

if (window.jQuery) {
    jQuery('#division_id').on('change', function() {
        jQuery('.transfer-holder-select').each(function() {
            resetSelect2Value(this, '<option value="">Select Type First</option>');
        });
        resetSelect2Value('#material_id', '<option value="">Select From Holder First</option>');
        jQuery('.transfer-holder-type').each(function() {
            if (jQuery(this).val()) {
                loadTransferHolders(this);
            }
        });
    });

    jQuery('.transfer-holder-type').on('change', function() {
        loadTransferHolders(this);
        if (jQuery(this).attr('id') === 'from_type') {
            resetSelect2Value('#material_id', '<option value="">Select From Holder First</option>');
        }
    });

    jQuery('#from_id').on('change', function() {
        loadTransferMaterials();
    });

    jQuery('.transfer-holder-type').each(function() {
        if (jQuery(this).val()) {
            loadTransferHolders(this);
        }
    });
}
</script>
</body>
</html>
