<?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(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

header('Content-Type: application/json');

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    // Get single rice bag
    $riceBagId = (int)$_GET['id'];
    
    $query = "SELECT r.*, u.FullName as CreatedByName, u2.FullName as UpdatedByName 
              FROM tblricebags r 
              LEFT JOIN tblusers u ON r.CreatedBy = u.ID 
              LEFT JOIN tblusers u2 ON r.UpdatedBy = u2.ID 
              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);
        // Ensure StockInBags is included
        if (!isset($riceBag['StockInBags'])) {
            $riceBag['StockInBags'] = 0;
        }
        echo json_encode([
            'success' => true,
            'product' => $riceBag
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Rice bag product not found'
        ]);
    }
} else {
    // Get all rice bags
    $query = "SELECT r.*, u.FullName as CreatedByName, u2.FullName as UpdatedByName 
              FROM tblricebags r 
              LEFT JOIN tblusers u ON r.CreatedBy = u.ID 
              LEFT JOIN tblusers u2 ON r.UpdatedBy = u2.ID 
              WHERE r.IsActive = 1 
              ORDER BY r.RiceBagName ASC";
    
    $result = mysqli_query($con, $query);
    
    if ($result) {
        $riceBags = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $riceBags[] = [
                'ID' => (int)$row['ID'],
                'RiceBagName' => $row['RiceBagName'],
                'BagKg' => (float)$row['BagKg'],
                'ManufactureType' => $row['ManufactureType'],
                'ShopRate' => (float)$row['ShopRate'],
                'RetailRate' => (float)$row['RetailRate'],
                'MRP' => (float)$row['MRP'],
                'Brand' => $row['Brand'],
                'Location' => $row['Location'],
                'ProductImage' => $row['ProductImage'],
                'CurrentStock' => (float)$row['CurrentStock'],
                'StockInBags' => isset($row['StockInBags']) ? (int)$row['StockInBags'] : 0,
                'IsActive' => (int)$row['IsActive'],
                'CreatedBy' => (int)$row['CreatedBy'],
                'CreatedByName' => $row['CreatedByName'],
                'CreatedDate' => $row['CreatedDate'],
                'UpdatedBy' => $row['UpdatedBy'] ? (int)$row['UpdatedBy'] : null,
                'UpdatedByName' => $row['UpdatedByName'],
                'UpdatedDate' => $row['UpdatedDate']
            ];
        }
        
        echo json_encode([
            'success' => true,
            'data' => $riceBags,
            'count' => count($riceBags)
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . mysqli_error($con)
        ]);
    }
}
?>
