<?php 
session_start();
include 'includes/header.php'; 
include 'includes/sidebar.php'; 
include 'includes/connect.php';

// ================= USER =================
$logged_in_role = $_SESSION['role'] ?? '';
$logged_in_id   = $_SESSION['distributor_id'] ?? 0;

$role = strtolower(trim($logged_in_role));

// ================= BASE QUERY =================
$query = "
SELECT 
    im.*, 
    d.name as distributor_name, 
    c.category_name,
    lc.label_name as variety_name
FROM inventory_management im
LEFT JOIN distributor d ON im.distributor = d.id
LEFT JOIN category c ON im.category_id = c.id
LEFT JOIN lifeline_configuration lc ON im.variety_id = lc.id
";

// ================= ROLE FILTER =================
if($role == 'super-admin'){

    // ✅ No filter → all data

} elseif($role == 'distributor'){

    // ✅ Distributor → ONLY OWN DATA
    $query .= " WHERE im.distributor = '$logged_in_id' ";

} else {

    // ✅ For nursery or other roles

    // Get parent_id
    $parent_query = "SELECT parent_id FROM distributor WHERE id='$logged_in_id' LIMIT 1";
    $parent_result = mysqli_query($conn, $parent_query);
    $parent_row = mysqli_fetch_assoc($parent_result);

    $parent_id = $parent_row['parent_id'] ?? 0;

    if(!empty($parent_id)){

        // ✅ Get all distributors under same parent
        $query .= " WHERE im.distributor IN (
            SELECT id 
            FROM distributor 
            WHERE parent_id = '$parent_id'
        ) OR im.distributor = '$parent_id' ";

    } else {

        // fallback → own data
        $query .= " WHERE im.distributor = '$logged_in_id' ";
    }
}

// ================= ORDER =================
$query .= " ORDER BY im.created_at DESC ";

// ================= DEBUG (optional) =================
/*
echo "<pre style='background:#000;color:#0f0;padding:10px;'>";
echo $query;
echo "</pre>";
*/

// ================= EXECUTE =================
$result = mysqli_query($conn, $query);

// ================= ERROR =================
if(!$result){
    echo "<pre style='color:red;'>";
    echo "SQL ERROR: " . mysqli_error($conn);
    echo "</pre>";
}
?>

<div class="main-content-inner">
    <div class="main-content-wrap">

        <div class="flex items-center flex-wrap justify-between gap20 mb-30">
            <h3>Inventory List</h3>
            <a class="tf-button px-40" href="add_inventory.php">
                <i class="icon-plus"></i>Add New
            </a>
        </div>

        <div class="wg-box">

            <div class="wg-table table-all-category">

                <ul class="table-title flex gap20 mb-14">
                    <li><div class="body-title">Nursury</div></li>
                    <li><div class="body-title">Crop</div></li>
                    <li><div class="body-title">Brand</div></li>
                    <li><div class="body-title">Variety</div></li>
                    <li><div class="body-title">Tray No</div></li>
                    <li><div class="body-title">Cavity</div></li>
                    <li><div class="body-title">Price</div></li>
                    <li><div class="body-title">Creation Date</div></li>
                    <li><div class="body-title">Added At</div></li>
                    <li><div class="body-title">Action</div></li>
                </ul>

                <ul class="flex flex-column">
                    <?php if(mysqli_num_rows($result) > 0){ ?>
                        <?php while($row = mysqli_fetch_assoc($result)){ ?>
                            <li class="wg-product item-row gap20">

                                <div class="body-text mt-4">
                                    <?php echo htmlspecialchars($row['distributor_name']); ?>
                                </div>

                                <div class="body-text mt-4">
                                    <?php echo htmlspecialchars($row['category_name']); ?>
                                </div>

                                <div class="body-text mt-4">
                                    <?php echo htmlspecialchars($row['brand']); ?>
                                </div>

                                <div class="body-text mt-4">
                                    <?php echo htmlspecialchars($row['variety_name']); ?>
                                </div>

                                <div class="body-text mt-4"><?php echo $row['tray_no']; ?></div>
                                <div class="body-text mt-4"><?php echo $row['cavity']; ?></div>
                                <div class="body-text mt-4"><?php echo $row['price']; ?></div>
                                <div class="body-text mt-4"><?php echo $row['creation_date']; ?></div>
                                <div class="body-text mt-4">
                                    <?php echo date("d M Y H:i", strtotime($row['created_at'])); ?>
                                </div>

                                <div class="list-icon-function">
                                    <a href="edit_inventory.php?id=<?php echo $row['id']; ?>" class="item edit">
                                        <i class="icon-edit-3"></i>
                                    </a>

                                    <button class="item trash delete-btn" data-id="<?php echo $row['id']; ?>" style="background:none;border:none;padding:0;">
                                        <i class="icon-trash-2"></i>
                                    </button>
                                </div>

                            </li>
                        <?php } ?>
                    <?php } else { ?>
                        <li><div class="body-text">No inventory records found</div></li>
                    <?php } ?>
                </ul>

            </div>

        </div>

    </div>
</div>

<?php include 'includes/footer.php'; ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('.delete-btn').click(function(){
        var id = $(this).data('id');
        if(confirm('Are you sure you want to delete this inventory record?')){
            $.ajax({
                url: 'delete_inventory.php',
                type: 'POST',
                data: {id: id},
                success: function(response){
                    alert(response);
                    location.reload();
                },
                error: function(){
                    alert('Error deleting record');
                }
            });
        }
    });
});
</script>