<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Get rice bag details
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $riceBagId = (int)$_GET['id'];
    
    $query = "SELECT r.*, 
              COALESCE(r.CurrentStock, 0) as CurrentStock,
              COALESCE(r.StockInBags, 0) as StockInBags
              FROM tblricebags r 
              WHERE r.ID = $riceBagId AND r.IsActive = 1";
    
    $result = mysqli_query($con, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $riceBag = mysqli_fetch_assoc($result);
        
        // Get recent stock adjustments for this rice bag
        $adjustmentsQuery = "SELECT sa.*, u.FullName as CreatedByName
                            FROM tblstockadjustments sa
                            LEFT JOIN tblusers u ON sa.CreatedBy = u.ID
                            WHERE sa.RiceBagID = $riceBagId AND sa.IsActive = 1
                            ORDER BY sa.CreatedDate DESC
                            LIMIT 5";
        
        $adjustmentsResult = mysqli_query($con, $adjustmentsQuery);
        $recentAdjustments = [];
        
        if ($adjustmentsResult) {
            while ($row = mysqli_fetch_assoc($adjustmentsResult)) {
                $recentAdjustments[] = $row;
            }
        }
        
        $riceBag['recentAdjustments'] = $recentAdjustments;
        
        header('Content-Type: application/json');
        echo json_encode($riceBag);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Rice bag not found']);
    }
} else {
    // Get all rice bags with current stock
    $query = "SELECT ID, RiceBagName, Brand, BagKg, ManufactureType, 
              COALESCE(CurrentStock, 0) as CurrentStock, 
              COALESCE(StockInBags, 0) as StockInBags, Location
              FROM tblricebags 
              WHERE IsActive = 1 
              ORDER BY RiceBagName";
    
    $result = mysqli_query($con, $query);
    $riceBags = [];
    
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $riceBags[] = $row;
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode($riceBags);
}
?>
