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

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

// ================= BASE QUERY =================
$query = "
SELECT 
    MIN(im.id) as id,
    im.batch_id,
    im.category_id,
    im.variety_id,
    im.brand,
    im.tray_no,
    im.cavity,
    im.creation_date,
    im.created_at,
    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'){

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

    $query .= " WHERE im.distributor = '$logged_in_id' ";

} else {

    $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)){

        $query .= " WHERE im.distributor IN (
            SELECT id 
            FROM distributor 
            WHERE parent_id = '$parent_id'
        ) OR im.distributor = '$parent_id' ";

    } else {

        $query .= " WHERE im.distributor = '$logged_in_id' ";
    }
}

// ================= GROUP BY =================
$query .= " GROUP BY im.batch_id ";

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

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

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

<style>
.badge {
    padding: 4px 8px;
    border-radius: 5px;
    font-size: 12px;
    font-weight: 600;
}
.badge-green { background: #d1fae5; color: #065f46; }
.badge-orange { background: #fef3c7; color: #92400e; }
.badge-blue { background: #dbeafe; color: #1e3a8a; }
.badge-red { background: #fee2e2; color: #991b1b; }

.main-content-inner,
.main-content-wrap,
.wg-box,
.wg-table,
.wg-table * {
    font-size: 14px !important;
    line-height: 1.5 !important;
}
</style>

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

<div class="flex items-center flex-wrap justify-between gap20 mb-30">
    <h3>Sapling Inventory Details</h3>
</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">Batch ID</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">Trays</div></li>
    <li><div class="body-title">Cavity</div></li>
    <li><div class="body-title">Sowing Date</div></li>
    <li><div class="body-title">Days Passed</div></li>
    <li><div class="body-title">Growth Status</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)){ ?>

<?php
$sowingDate = $row['creation_date'];
$today = new DateTime();
$sowing = new DateTime($sowingDate);
$diff = $today->diff($sowing);
$days = $diff->days;

$category = strtolower(trim($row['category_name']));

// ✅ NEW 3-STAGE LOGIC
if(
    strpos($category, 'chilli') !== false || 
    strpos($category, 'chilly') !== false || 
    strpos($category, 'capsicum') !== false
){
    if($days < 35){
        $growth_status = "Growing";
    } elseif($days <= 70){
        $growth_status = "Ready for Sale";
    } else {
        $growth_status = "Overgrown";
    }
}
else {
    if($days < 22){
        $growth_status = "Growing";
    } elseif($days <= 42){
        $growth_status = "Ready for Sale";
    } else {
        $growth_status = "Overgrown";
    }
}
?>

<li class="wg-product item-row gap20">

    <div><?php echo $row['batch_id']; ?></div>
    <div><?php echo $row['category_name']; ?></div>
    <div><?php echo $row['brand']; ?></div>
    <div><?php echo $row['variety_name']; ?></div>

    <div><?php echo $row['tray_no']; ?></div>
    <div><?php echo $row['cavity']; ?></div>

    <div><?php echo date("d M Y", strtotime($sowingDate)); ?></div>

    <div>
        <span class="badge badge-blue"><?php echo $days . " days"; ?></span>
    </div>

    <div>
        <?php if($growth_status == "Ready for Sale"){ ?>
            <span class="badge badge-green">Ready</span>
        <?php } elseif($growth_status == "Overgrown"){ ?>
            <span class="badge badge-red">Overgrown</span>
        <?php } else { ?>
            <span class="badge badge-orange">Growing</span>
        <?php } ?>
    </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']; ?>">
            <i class="icon-trash-2"></i>
        </button>
    </div>

</li>

<?php } ?>
<?php } else { ?>
<li><div>No inventory records found</div></li>
<?php } ?>

</ul>

</div>
</div>
</div>
</div>

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