<?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));

/* =========================================================
   DISTRIBUTOR DROPDOWN LOGIC
========================================================= */
if($role == 'super-admin'){

    $distributors_query = "SELECT * FROM distributor 
                           WHERE status='Active'
                           ORDER BY name ASC";

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

    $parent_id = 0;

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

    if($parent_result && mysqli_num_rows($parent_result) > 0){
        $parent_row = mysqli_fetch_assoc($parent_result);
        $parent_id = $parent_row['parent_id'] ?? 0;
    }

    $distributors_query = "SELECT * FROM distributor 
                           WHERE id='$parent_id' AND status='Active'
                           ORDER BY name ASC";

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

    $distributors_query = "SELECT * FROM distributor 
                           WHERE id='$logged_in_id' AND status='Active'
                           LIMIT 1";

}
else {

    $distributors_query = "SELECT * FROM distributor 
                           WHERE status='Active'
                           ORDER BY name ASC";
}

$distributors = mysqli_query($conn, $distributors_query);

// ================= CATEGORIES =================
$categories_query = "SELECT * FROM category ORDER BY category_name ASC";
$categories = mysqli_query($conn, $categories_query);

/* =========================================================
   INSERT INVENTORY
========================================================= */
if(isset($_POST['submit_inventory'])){

    $distributor = $_POST['distributor']; // ⚠️ change (string because ALL)
    $category   = intval($_POST['category']);
    $variety    = intval($_POST['variety']);
    $brand      = isset($_POST['brand']) ? trim($_POST['brand']) : '';
    $tray_no    = intval($_POST['tray_no']);
    $cavity     = intval($_POST['cavity']);
    $price      = intval($_POST['price']);
    $creation   = trim($_POST['creation_date']);

    if(empty($distributor) || empty($category) || empty($variety) || empty($brand) || empty($tray_no) || empty($cavity) || empty($price) || empty($creation)){
        $error = "All fields are required";
    } else {

        // ================= BATCH ID AUTO =================
        $batch_query = "SELECT MAX(batch_id) AS last_id FROM inventory_management";
        $batch_result = mysqli_query($conn, $batch_query);
        $row = mysqli_fetch_assoc($batch_result);
        $batch_id = ($row['last_id'] ?? 0) + 1;

        // ================= INSERT FUNCTION =================
        function insertInventory($conn, $batch_id, $distributor, $category, $variety, $brand, $tray_no, $cavity, $price, $creation){

            // get parent id
            $parent_id = 0;
            $parent_query = "SELECT parent_id FROM distributor WHERE id='$distributor' LIMIT 1";
            $parent_result = mysqli_query($conn, $parent_query);

            if($parent_result && mysqli_num_rows($parent_result) > 0){
                $parent_row = mysqli_fetch_assoc($parent_result);
                $parent_id = $parent_row['parent_id'] ?? 0;
            }

            $stmt = $conn->prepare("INSERT INTO inventory_management 
            (batch_id, distributor, parent_id, category_id, variety_id, brand, tray_no, cavity, price, creation_date, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");

            $stmt->bind_param(
                "iiiiisiiis",
                $batch_id,
                $distributor,
                $parent_id,
                $category,
                $variety,
                $brand,
                $tray_no,
                $cavity,
                $price,
                $creation
            );

            return $stmt->execute();
        }

        // ================= MAIN LOGIC =================
        if($distributor == 'all' && $role == 'super-admin'){

            // 👉 ALL distributors
            $all_query = mysqli_query($conn, "SELECT id FROM distributor WHERE status='Active' and role='distributor'");

            while($d = mysqli_fetch_assoc($all_query)){
                insertInventory(
                    $conn,
                    $batch_id,
                    $d['id'],
                    $category,
                    $variety,
                    $brand,
                    $tray_no,
                    $cavity,
                    $price,
                    $creation
                );
            }

        } else {

            // 👉 Single distributor
            insertInventory(
                $conn,
                intval($distributor),
                $category,
                $variety,
                $brand,
                $tray_no,
                $cavity,
                $price,
                $creation
            );
        }

        echo "<script>alert('Inventory Added Successfully | Batch ID: $batch_id'); window.location.href='inventory_stat_calc.php';</script>";
        exit;
    }
}
?>

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

        <div class="flex items-center flex-wrap justify-between gap20 mb-30">
            <h3>Add Inventory</h3>
        </div>

        <?php if(isset($error)){ ?>
            <div class="text-red-500 mb-4"><?php echo $error; ?></div>
        <?php } ?>

        <form class="form-add-category" method="POST">

            <div class="wg-box mb-30" style="display:grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap:20px;">

                <!-- Distributor -->
                <fieldset>
                    <div class="body-title mb-10">Nursury <span class="tf-color-1">*</span></div>

                    <select name="distributor" id="distributor" required>
                        <option value="">Select Nursury</option>

                        <?php if($role == 'super-admin'){ ?>
                            <option value="all">All</option>
                        <?php } ?>

                        <?php while($row = mysqli_fetch_assoc($distributors)){ ?>
                            <option value="<?php echo $row['id']; ?>">
                                <?php echo htmlspecialchars($row['name']); ?>
                            </option>
                        <?php } ?>

                    </select>
                </fieldset>
                
                <!-- Date -->
                <fieldset>
                    <div class="body-title mb-10">Date of Sowing <span class="tf-color-1">*</span></div>
                    <input type="date" name="creation_date" required>
                </fieldset>
                
                <!-- Crop -->
                <fieldset>
                    <div class="body-title mb-10">Crop <span class="tf-color-1">*</span></div>
                    <select name="category" id="category" required>
                        <option value="">Select Crop</option>
                        <?php while($row = mysqli_fetch_assoc($categories)){ ?>
                            <option value="<?php echo $row['id']; ?>">
                                <?php echo htmlspecialchars($row['category_name']); ?>
                            </option>
                        <?php } ?>
                    </select>
                </fieldset>
                
                <!-- Variety -->
                <fieldset>
                    <div class="body-title mb-10">Variety <span class="tf-color-1">*</span></div>
                    <select name="variety" id="variety" required>
                        <option value="">Select Variety</option>
                    </select>
                </fieldset>
                
                <!-- Brand -->
                <fieldset>
                    <div class="body-title mb-10">Brand <span class="tf-color-1">*</span></div>
                    <select name="brand" id="brand" required>
                        <option value="">Select Brand</option>
                    </select>
                </fieldset>
                
                <!-- Cavity -->
                <fieldset>
                    <div class="body-title mb-10">Cavity <span class="tf-color-1">*</span></div>
                    <input type="number" name="cavity" required>
                </fieldset>
                
                <!-- Trays -->
                <fieldset>
                    <div class="body-title mb-10">Trays <span class="tf-color-1">*</span></div>
                    <input type="number" name="tray_no" required>
                </fieldset>
                
                <!-- Price -->
                <fieldset>
                    <div class="body-title mb-10">Price <span class="tf-color-1">*</span></div>
                    <input type="number" name="price" required>
                </fieldset>
                
            </div>

            <div class="cols gap10" style="display:flex; gap:20px; flex-wrap:wrap;">
                <button class="tf-button w380" type="submit" name="submit_inventory">Add Inventory</button>
                <a href="inventory_stat_calc.php" class="tf-button style-3 w380">Cancel</a>
            </div>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function(){

    $('#category').on('change', function(){

        var categoryId = $(this).val();

        if(categoryId){

            $.ajax({
                type: 'POST',
                url: 'get_variety.php',
                data: {category_id: categoryId},
                success: function(response){
                    $('#variety').html(response);
                    $('#brand').html('<option value="">Select Brand</option>');
                }
            });

        } else {
            $('#variety').html('<option value="">Select Variety</option>');
            $('#brand').html('<option value="">Select Brand</option>');
        }

    });

    $('#variety').on('change', function(){

        var varietyId = $(this).val();

        if(varietyId){

            $.ajax({
                type: 'POST',
                url: 'get_brands.php',
                data: {variety_id: varietyId},
                success: function(response){
                    $('#brand').html(response);
                }
            });

        } else {
            $('#brand').html('<option value="">Select Brand</option>');
        }

    });

});
</script>

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