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

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

$msg = $err = '';

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'];
    $bso_id = stock_is_bso() ? $created_by : 0;

    if (stock_is_admin() && !empty($_POST['bso_id'])) {
        $bso_id = (int)$_POST['bso_id'];
    }

    if ($material_id <= 0 || $quantity <= 0 || $bso_id <= 0) {
        $err = 'Please select material, BSO holder and enter valid quantity.';
    } 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', 'receive', 'external', '0', 'bso', '$bso_id', '$reference_no', '$remarks', '$created_by')";

        if ($conn->query($sql)) {
            $msg = 'Stock received successfully.';
        } else {
            $err = $conn->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS ADMIN | Receive Stock</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">Receive Stock in BSO Store</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">
                            <div class="row">
                                <div class="col-md-3 form-group">
                                    <label>Material</label>
                                    <select name="material_id" required class="form-control">
                                        <option value="">Select Material</option>
                                        <?php
                                        $materials = $conn->query(stock_material_select_sql());
                                        while ($mat = $materials->fetch_assoc()) {
                                        ?>
                                            <option value="<?php echo $mat['id']; ?>"><?php echo htmlspecialchars(stock_material_label($mat)); ?></option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <?php if (stock_is_admin()) { ?>
                                <div class="col-md-3 form-group">
                                    <label>BSO Store Holder</label>
                                    <select name="bso_id" class="form-control" required>
                                        <option value="">Select BSO</option>
                                        <?php
                                        $bsos = stock_holder_options($conn, 'bso');
                                        while ($bso = $bsos->fetch_assoc()) {
                                        ?>
                                            <option value="<?php echo $bso['id']; ?>"><?php echo $bso['name']; ?></option>
                                        <?php } ?>
                                    </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-2 form-group">
                                    <label>Reference No.</label>
                                    <input type="text" name="reference_no" class="form-control">
                                </div>
                                <div class="col-md-4 form-group">
                                    <label>Remarks</label>
                                    <input type="text" name="remarks" class="form-control">
                                </div>
                            </div>
                            <button type="submit" name="submit" class="btn btn-primary">Receive Stock</button>
                        </form>
                    </div>
                </div>

                <div class="card grid-margin">
                    <div class="card-body">
                        <h4 class="card-title">Recent Received Stock</h4>
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered">
                                <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Material</th>
                                    <th>Quantity</th>
                                    <th>BSO</th>
                                    <th>Reference</th>
                                    <th>Remarks</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                $where = stock_is_bso() ? "AND st.to_holder_id='".(int)$_SESSION['admin']."'" : '';
                                $rows = $conn->query("
                                    SELECT st.*, sm.material_name, sm.serial_number AS material_code, sm.s_code, sm.m_unit AS unit
                                    FROM stock_transactions st
                                    INNER JOIN matrial sm ON sm.m_id = st.material_id
                                    WHERE st.transaction_type='receive' $where
                                    ORDER BY st.id DESC
                                    LIMIT 50
                                ");
                                if ($rows && $rows->num_rows > 0) {
                                    while ($row = $rows->fetch_assoc()) {
                                ?>
                                    <tr>
                                        <td><?php echo date('d/m/Y H:i', strtotime($row['created_at'])); ?></td>
                                        <td><?php echo htmlspecialchars(stock_material_label($row, false)); ?></td>
                                        <td><?php echo rtrim(rtrim($row['quantity'], '0'), '.').' '.$row['unit']; ?></td>
                                        <td><?php echo stock_holder_label($conn, 'bso', $row['to_holder_id']); ?></td>
                                        <td><?php echo $row['reference_no']; ?></td>
                                        <td><?php echo $row['remarks']; ?></td>
                                    </tr>
                                <?php }} else { ?>
                                    <tr><td colspan="6">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>
