<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle form submissions
if ($_POST) {
    $action = $_POST['action'];
    $riceBagName = mysqli_real_escape_string($con, $_POST['riceBagName']);
    $bagKg = (float)$_POST['bagKg'];
    $manufactureType = mysqli_real_escape_string($con, $_POST['manufactureType']);
    $shopRate = (float)$_POST['shopRate'];
    $retailRate = (float)$_POST['retailRate'];
    $mrp = (float)$_POST['mrp'];
    $brand = mysqli_real_escape_string($con, $_POST['brand']);
    $location = mysqli_real_escape_string($con, $_POST['location']);
    
    // Handle image upload
    $imagePath = '';
    if (isset($_FILES['productImage']) && $_FILES['productImage']['error'] == 0) {
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        $maxFileSize = 5 * 1024 * 1024; // 5MB
        
        if (in_array($_FILES['productImage']['type'], $allowedTypes)) {
            if ($_FILES['productImage']['size'] <= $maxFileSize) {
                $fileExtension = pathinfo($_FILES['productImage']['name'], PATHINFO_EXTENSION);
                $fileName = 'ricebag_' . time() . '_' . rand(1000, 9999) . '.' . $fileExtension;
                $uploadDir = 'uploads/rice-bags/';
                $uploadPath = $uploadDir . $fileName;
                
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                if (move_uploaded_file($_FILES['productImage']['tmp_name'], $uploadPath)) {
                    $imagePath = $uploadPath;
                } else {
                    $error = "Error uploading image file.";
                }
            } else {
                $error = "Image file size should not exceed 5MB.";
            }
        } else {
            $error = "Only JPG, JPEG, PNG & GIF image files are allowed.";
        }
    }
    
    if ($action == 'create') {
        // Check if rice bag name already exists
        $checkQuery = "SELECT ID FROM tblricebags WHERE RiceBagName = '$riceBagName' AND Brand = '$brand' AND BagKg = $bagKg AND IsActive = 1";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (mysqli_num_rows($checkResult) > 0) {
            $error = "Rice bag with same name, brand and weight already exists!";
        } else {
            $insertQuery = "INSERT INTO tblricebags (RiceBagName, BagKg, ManufactureType, ShopRate, RetailRate, MRP, Brand, Location, ProductImage, CreatedBy) 
                           VALUES ('$riceBagName', $bagKg, '$manufactureType', $shopRate, $retailRate, $mrp, '$brand', '$location', '$imagePath', '$userId')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Rice bag product added successfully!";
            } else {
                $error = "Error adding rice bag product: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $riceBagId = (int)$_POST['riceBagId'];
        
        // Get current image path for update
        $currentImageQuery = "SELECT ProductImage FROM tblricebags WHERE ID = $riceBagId";
        $currentImageResult = mysqli_query($con, $currentImageQuery);
        $currentImage = mysqli_fetch_assoc($currentImageResult)['ProductImage'];
        
        // Use new image if uploaded, otherwise keep current image
        $finalImagePath = !empty($imagePath) ? $imagePath : $currentImage;
        
        // Check if rice bag name already exists for other products
        $checkQuery = "SELECT ID FROM tblricebags WHERE RiceBagName = '$riceBagName' AND Brand = '$brand' AND BagKg = $bagKg AND ID != $riceBagId AND IsActive = 1";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (mysqli_num_rows($checkResult) > 0) {
            $error = "Rice bag with same name, brand and weight already exists!";
        } else {
            $updateQuery = "UPDATE tblricebags SET 
                           RiceBagName = '$riceBagName',
                           BagKg = $bagKg,
                           ManufactureType = '$manufactureType',
                           ShopRate = $shopRate,
                           RetailRate = $retailRate,
                           MRP = $mrp,
                           Brand = '$brand',
                           Location = '$location',
                           ProductImage = '$finalImagePath',
                           UpdatedBy = '$userId',
                           UpdatedDate = NOW()
                           WHERE ID = $riceBagId";
            
            if (mysqli_query($con, $updateQuery)) {
                // Delete old image if new image was uploaded
                if (!empty($imagePath) && !empty($currentImage) && file_exists($currentImage)) {
                    unlink($currentImage);
                }
                $success = "Rice bag product updated successfully!";
            } else {
                $error = "Error updating rice bag product: " . mysqli_error($con);
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $riceBagId = (int)$_GET['delete'];
    $deleteQuery = "UPDATE tblricebags SET IsActive = 0, UpdatedBy = '$userId', UpdatedDate = NOW() WHERE ID = $riceBagId";
    
    if (mysqli_query($con, $deleteQuery)) {
        $success = "Rice bag product deleted successfully!";
    } else {
        $error = "Error deleting rice bag product: " . mysqli_error($con);
    }
}

// Get rice bag for editing
$editRiceBag = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $riceBagId = (int)$_GET['edit'];
    $editQuery = "SELECT * FROM tblricebags WHERE ID = $riceBagId AND IsActive = 1";
    $editResult = mysqli_query($con, $editQuery);
    $editRiceBag = mysqli_fetch_assoc($editResult);
}

// Fetch all rice bags with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$recordsPerPage = 10;
$offset = ($page - 1) * $recordsPerPage;

$searchTerm = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';
$filterBrand = isset($_GET['brand']) ? mysqli_real_escape_string($con, $_GET['brand']) : '';
$filterType = isset($_GET['type']) ? mysqli_real_escape_string($con, $_GET['type']) : '';

$whereClause = "WHERE IsActive = 1";
if (!empty($searchTerm)) {
    $whereClause .= " AND (RiceBagName LIKE '%$searchTerm%' OR Brand LIKE '%$searchTerm%' OR Location LIKE '%$searchTerm%')";
}
if (!empty($filterBrand)) {
    $whereClause .= " AND Brand = '$filterBrand'";
}
if (!empty($filterType)) {
    $whereClause .= " AND ManufactureType = '$filterType'";
}

// Count total records
$countQuery = "SELECT COUNT(*) as total FROM tblricebags $whereClause";
$countResult = mysqli_query($con, $countQuery);
$totalRecords = mysqli_fetch_assoc($countResult)['total'];
$totalPages = ceil($totalRecords / $recordsPerPage);

// Fetch rice bags
$riceBagsQuery = "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 
                  $whereClause 
                  ORDER BY r.CreatedDate DESC 
                  LIMIT $offset, $recordsPerPage";
$riceBagsResult = mysqli_query($con, $riceBagsQuery);

// Get statistics
$statsQuery = "SELECT 
    COUNT(*) as TotalProducts,
    COUNT(CASE WHEN ManufactureType = 'Premium' THEN 1 END) as PremiumProducts,
    COUNT(CASE WHEN ManufactureType = 'Standard' THEN 1 END) as StandardProducts,
    COUNT(CASE WHEN ManufactureType = 'Organic' THEN 1 END) as OrganicProducts,
    COUNT(DISTINCT Brand) as TotalBrands,
    AVG(MRP) as AvgMRP
    FROM tblricebags WHERE IsActive = 1";
$statsResult = mysqli_query($con, $statsQuery);
$stats = mysqli_fetch_assoc($statsResult);

// Get distinct brands for filter
$brandsQuery = "SELECT DISTINCT Brand FROM tblricebags WHERE IsActive = 1 ORDER BY Brand";
$brandsResult = mysqli_query($con, $brandsQuery);

// Get distinct manufacture types for filter
$typesQuery = "SELECT DISTINCT ManufactureType FROM tblricebags WHERE IsActive = 1 ORDER BY ManufactureType";
$typesResult = mysqli_query($con, $typesQuery);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Rice Bag Management | Mariyappa Nadar Ricemill</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
    <style>
        .product-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .product-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .type-premium { border-left: 4px solid #f6c23e; }
        .type-standard { border-left: 4px solid #1cc88a; }
        .type-organic { border-left: 4px solid #36b9cc; }
        .modal-header { background: linear-gradient(45deg, #4e73df, #36b9cc); color: white; }
        .required { color: red; }
        
        /* Compact design for mobile */
        .form-group { margin-bottom: 0.75rem; }
        .card-body { padding: 1rem; }
        .table td, .table th { padding: 0.5rem; }
        .btn { padding: 0.375rem 0.75rem; }
        .alert { padding: 0.5rem 1rem; margin-bottom: 0.75rem; }
        
        /* Product Grid Layout */
        .product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .product-grid-item {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            overflow: hidden;
            border: 1px solid #e3e6f0;
        }
        
        .product-grid-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .product-header {
            padding: 1rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            position: relative;
        }
        
        .product-header.premium {
            background: linear-gradient(135deg, #f6c23e 0%, #f4b619 100%);
        }
        
        .product-header.standard {
            background: linear-gradient(135deg, #1cc88a 0%, #17a673 100%);
        }
        
        .product-header.organic {
            background: linear-gradient(135deg, #36b9cc 0%, #2c9faf 100%);
        }
        
        .product-type-badge {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            font-size: 0.7rem;
            padding: 0.25rem 0.5rem;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
        }
        
        .product-name {
            font-size: 1.1rem;
            font-weight: 600;
            margin: 0;
            line-height: 1.2;
        }
        
        .product-brand {
            font-size: 0.9rem;
            opacity: 0.9;
            margin: 0.25rem 0 0 0;
        }
        
        .product-body {
            padding: 1rem;
        }
        
        .product-info {
            margin-bottom: 0.75rem;
        }
        
        .product-info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        
        .product-info-label {
            color: #5a5c69;
            font-weight: 500;
        }
        
        .product-info-value {
            font-weight: 600;
        }
        
        .rate-shop { color: #1cc88a; }
        .rate-retail { color: #36b9cc; }
        .rate-mrp { color: #e74a3b; }
        
        .product-actions {
            border-top: 1px solid #e3e6f0;
            padding: 0.75rem 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .product-date {
            font-size: 0.8rem;
            color: #858796;
        }
        
        .view-toggle {
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .product-grid {
                grid-template-columns: 1fr;
                gap: 0.75rem;
            }
            .product-header, .product-body, .product-actions {
                padding: 0.75rem;
            }
            .product-info-item {
                font-size: 0.85rem;
            }
            .form-group { margin-bottom: 0.5rem; }
            .modal-body { padding: 1rem; }
        }
        
        /* Statistics cards hover effect */
        .stats-card {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .stats-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.2) !important;
        }
        
        .weight-badge {
            background: #e9ecef;
            color: #495057;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        /* Image upload styles */
        .image-upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 2rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f8f9fa;
        }
        
        .image-upload-area:hover {
            border-color: #4e73df;
            background: #f0f2ff;
        }
        
        .image-upload-area.dragover {
            border-color: #4e73df;
            background: #e3f2fd;
        }
        
        .image-preview {
            max-width: 200px;
            max-height: 200px;
            border-radius: 8px;
            margin: 1rem auto;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #e3e6f0;
        }
        
        .product-image-large {
            width: 100%;
            max-width: 300px;
            height: auto;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .image-placeholder {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #e9ecef, #dee2e6);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            font-size: 1.5rem;
        }
        
        .remove-image-btn {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="fas fa-box text-primary mr-2"></i>
                            Rice Bag Management
                        </h1>
                        <div>
                            <button class="btn btn-success mr-2" onclick="exportProducts()">
                                <i class="fas fa-file-export mr-2"></i>Export Products
                            </button>
                            <button class="btn btn-primary" data-toggle="modal" data-target="#riceBagModal" onclick="clearForm()">
                                <i class="fas fa-plus mr-2"></i>Add New Product
                            </button>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-primary shadow h-100 py-2 stats-card">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                Total Products</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['TotalProducts']; ?></div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-box fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-success shadow h-100 py-2 stats-card">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                Premium Products</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['PremiumProducts']; ?></div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-star fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-info shadow h-100 py-2 stats-card">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                                Total Brands</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['TotalBrands']; ?></div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-tags fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-warning shadow h-100 py-2 stats-card">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                                Avg MRP</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">₹<?php echo number_format($stats['AvgMRP'], 0); ?></div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-rupee-sign fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="card shadow mb-3">
                        <div class="card-body py-2">
                            <form method="GET" class="row align-items-end">
                                <div class="col-md-3 mb-2">
                                    <label for="search" class="form-label">Search Products</label>
                                    <input type="text" class="form-control form-control-sm" id="search" name="search" 
                                           value="<?php echo htmlspecialchars($searchTerm); ?>" 
                                           placeholder="Search by name, brand, location...">
                                </div>
                                <div class="col-md-2 mb-2">
                                    <label for="brand" class="form-label">Brand</label>
                                    <select class="form-control form-control-sm" id="brand" name="brand">
                                        <option value="">All Brands</option>
                                        <?php while($brand = mysqli_fetch_assoc($brandsResult)): ?>
                                        <option value="<?php echo $brand['Brand']; ?>" <?php echo $filterBrand == $brand['Brand'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($brand['Brand']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-2">
                                    <label for="type" class="form-label">Type</label>
                                    <select class="form-control form-control-sm" id="type" name="type">
                                        <option value="">All Types</option>
                                        <?php 
                                        mysqli_data_seek($typesResult, 0);
                                        while($type = mysqli_fetch_assoc($typesResult)): 
                                        ?>
                                        <option value="<?php echo $type['ManufactureType']; ?>" <?php echo $filterType == $type['ManufactureType'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($type['ManufactureType']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-2">
                                    <button type="submit" class="btn btn-primary btn-sm mr-2">
                                        <i class="fas fa-search mr-1"></i>Search
                                    </button>
                                    <a href="rice-bag-management.php" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-times mr-1"></i>Clear
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <div class="view-toggle btn-group btn-group-sm" role="group">
                                        <button type="button" class="btn btn-outline-primary active" id="gridViewBtn" onclick="toggleView('grid')">
                                            <i class="fas fa-th-large mr-1"></i>Grid
                                        </button>
                                        <button type="button" class="btn btn-outline-primary" id="tableViewBtn" onclick="toggleView('table')">
                                            <i class="fas fa-list mr-1"></i>Table
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Product Grid View -->
                    <div id="gridView" class="product-grid">
                        <?php 
                        mysqli_data_seek($riceBagsResult, 0);
                        while($product = mysqli_fetch_assoc($riceBagsResult)): 
                        ?>
                        <div class="product-grid-item">
                            <div class="product-header <?php echo strtolower($product['ManufactureType']); ?>">
                                <div class="product-type-badge">
                                    <?php echo $product['ManufactureType']; ?>
                                </div>
                                <h6 class="product-name"><?php echo htmlspecialchars($product['RiceBagName']); ?></h6>
                                <p class="product-brand"><?php echo htmlspecialchars($product['Brand']); ?></p>
                            </div>
                            <div class="product-body">
                                <div class="row mb-3">
                                    <div class="col-4">
                                        <?php if (!empty($product['ProductImage']) && file_exists($product['ProductImage'])): ?>
                                            <img src="<?php echo $product['ProductImage']; ?>" alt="<?php echo htmlspecialchars($product['RiceBagName']); ?>" class="product-image">
                                        <?php else: ?>
                                            <div class="image-placeholder">
                                                <i class="fas fa-image"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-8">
                                        <div class="product-info-item">
                                            <span class="product-info-label">Weight:</span>
                                            <span class="weight-badge"><?php echo $product['BagKg']; ?> Kg</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="product-info">
                                    <div class="product-info-item">
                                        <span class="product-info-label">Shop Rate:</span>
                                        <span class="product-info-value rate-shop">₹<?php echo number_format($product['ShopRate'], 2); ?></span>
                                    </div>
                                    <div class="product-info-item">
                                        <span class="product-info-label">Retail Rate:</span>
                                        <span class="product-info-value rate-retail">₹<?php echo number_format($product['RetailRate'], 2); ?></span>
                                    </div>
                                    <div class="product-info-item">
                                        <span class="product-info-label">MRP:</span>
                                        <span class="product-info-value rate-mrp">₹<?php echo number_format($product['MRP'], 2); ?></span>
                                    </div>
                                    <?php if($product['Location']): ?>
                                    <div class="product-info-item">
                                        <span class="product-info-label">Location:</span>
                                        <span class="product-info-value"><?php echo htmlspecialchars($product['Location']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="product-actions">
                                <div class="product-date">
                                    <?php echo date('M d, Y', strtotime($product['CreatedDate'])); ?>
                                </div>
                                <div class="btn-group btn-group-sm" role="group">
                                    <button class="btn btn-info" onclick="viewProduct(<?php echo $product['ID']; ?>)" title="View Product">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn btn-warning" onclick="editProduct(<?php echo $product['ID']; ?>)" title="Edit Product">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger" onclick="deleteProduct(<?php echo $product['ID']; ?>, '<?php echo htmlspecialchars($product['RiceBagName']); ?>')" title="Delete Product">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>

                    <!-- Products Table -->
                    <div class="card shadow mb-4" id="tableView" style="display: none;">
                        <div class="card-header py-2">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-list mr-2"></i>Product List
                                <span class="text-muted">(<?php echo $totalRecords; ?> total)</span>
                            </h6>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped table-sm mb-0" width="100%" cellspacing="0">
                                    <thead class="thead-dark">
                                        <tr>
                                            <th>#</th>
                                            <th>Image</th>
                                            <th>Product Name</th>
                                            <th>Brand</th>
                                            <th>Weight (Kg)</th>
                                            <th>Type</th>
                                            <th>Shop Rate</th>
                                            <th>Retail Rate</th>
                                            <th>MRP</th>
                                            <th>Location</th>
                                            <th>Created Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $serialNo = $offset + 1;
                                        mysqli_data_seek($riceBagsResult, 0);
                                        while($product = mysqli_fetch_assoc($riceBagsResult)): 
                                        ?>
                                        <tr>
                                            <td><?php echo $serialNo++; ?></td>
                                            <td>
                                                <?php if (!empty($product['ProductImage']) && file_exists($product['ProductImage'])): ?>
                                                    <img src="<?php echo $product['ProductImage']; ?>" alt="<?php echo htmlspecialchars($product['RiceBagName']); ?>" class="product-image" onclick="showImageModal('<?php echo $product['ProductImage']; ?>', '<?php echo htmlspecialchars($product['RiceBagName']); ?>')">
                                                <?php else: ?>
                                                    <div class="image-placeholder">
                                                        <i class="fas fa-image"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td class="font-weight-bold"><?php echo htmlspecialchars($product['RiceBagName']); ?></td>
                                            <td><?php echo htmlspecialchars($product['Brand']); ?></td>
                                            <td><?php echo $product['BagKg']; ?> Kg</td>
                                            <td>
                                                <span class="badge badge-<?php echo $product['ManufactureType'] == 'Premium' ? 'warning' : ($product['ManufactureType'] == 'Standard' ? 'success' : 'info'); ?>">
                                                    <?php echo $product['ManufactureType']; ?>
                                                </span>
                                            </td>
                                            <td class="text-success font-weight-bold">₹<?php echo number_format($product['ShopRate'], 2); ?></td>
                                            <td class="text-info font-weight-bold">₹<?php echo number_format($product['RetailRate'], 2); ?></td>
                                            <td class="text-danger font-weight-bold">₹<?php echo number_format($product['MRP'], 2); ?></td>
                                            <td><?php echo htmlspecialchars($product['Location']); ?></td>
                                            <td><?php echo date('M d, Y', strtotime($product['CreatedDate'])); ?></td>
                                            <td>
                                                <div class="btn-group btn-group-sm" role="group">
                                                    <button class="btn btn-info" onclick="viewProduct(<?php echo $product['ID']; ?>)" title="View Product">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <button class="btn btn-warning" onclick="editProduct(<?php echo $product['ID']; ?>)" title="Edit Product">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-danger" onclick="deleteProduct(<?php echo $product['ID']; ?>, '<?php echo htmlspecialchars($product['RiceBagName']); ?>')" title="Delete Product">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <nav aria-label="Product pagination">
                        <ul class="pagination justify-content-center pagination-sm">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($searchTerm); ?>&brand=<?php echo urlencode($filterBrand); ?>&type=<?php echo urlencode($filterType); ?>">Previous</a>
                            </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>&brand=<?php echo urlencode($filterBrand); ?>&type=<?php echo urlencode($filterType); ?>"><?php echo $i; ?></a>
                            </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($searchTerm); ?>&brand=<?php echo urlencode($filterBrand); ?>&type=<?php echo urlencode($filterType); ?>">Next</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Rice Bag Modal -->
    <div class="modal fade" id="riceBagModal" tabindex="-1" role="dialog" aria-labelledby="riceBagModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="riceBagModalLabel">
                        <i class="fas fa-box mr-2"></i>Add New Rice Bag Product
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" id="riceBagForm" enctype="multipart/form-data">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="riceBagId" id="riceBagId">
                        
                        <!-- Product Image Upload -->
                        <div class="form-group">
                            <label>Product Image <small class="text-muted">(Optional - JPG, PNG, GIF - Max 5MB)</small></label>
                            <div class="image-upload-area" onclick="document.getElementById('productImageFile').click();" id="imageUploadArea">
                                <div id="uploadPrompt">
                                    <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                    <p class="text-muted mb-0">Click to upload or drag and drop</p>
                                    <small class="text-muted">JPG, PNG, GIF up to 5MB</small>
                                </div>
                                <div id="imagePreviewContainer" style="display: none;">
                                    <div class="position-relative d-inline-block">
                                        <img id="imagePreview" class="image-preview" alt="Preview">
                                        <button type="button" class="remove-image-btn" onclick="removeImage(event)">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <input type="file" name="productImage" id="productImageFile" accept="image/*" style="display: none;" onchange="previewImage(this)">
                        </div>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group">
                                    <label for="riceBagName">Rice Bag Name <span class="required">*</span></label>
                                    <input type="text" class="form-control" id="riceBagName" name="riceBagName" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="bagKg">Bag Weight (Kg) <span class="required">*</span></label>
                                    <input type="number" class="form-control" id="bagKg" name="bagKg" step="0.01" min="0.1" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="brand">Brand <span class="required">*</span></label>
                                    <input type="text" class="form-control" id="brand" name="brand" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="manufactureType">Manufacture Type <span class="required">*</span></label>
                                    <select class="form-control" id="manufactureType" name="manufactureType" required>
                                        <option value="">Select Type</option>
                                        <option value="Premium">Premium</option>
                                        <option value="Standard">Standard</option>
                                        <option value="Organic">Organic</option>
                                        <option value="Economy">Economy</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="shopRate">Shop Rate (₹) <span class="required">*</span></label>
                                    <input type="number" class="form-control" id="shopRate" name="shopRate" step="0.01" min="0" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="retailRate">Retail Rate (₹) <span class="required">*</span></label>
                                    <input type="number" class="form-control" id="retailRate" name="retailRate" step="0.01" min="0" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="mrp">MRP (₹) <span class="required">*</span></label>
                                    <input type="number" class="form-control" id="mrp" name="mrp" step="0.01" min="0" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="location">Location <small class="text-muted">(Optional)</small></label>
                            <input type="text" class="form-control" id="location" name="location" 
                                   placeholder="e.g., Warehouse A, Store Room 1">
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle mr-2"></i>
                            <strong>Rate Guidelines:</strong> Shop Rate should be lowest, followed by Retail Rate, and MRP should be highest.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times mr-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fas fa-save mr-1"></i>Save Product
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Product Modal -->
    <div class="modal fade" id="viewProductModal" tabindex="-1" role="dialog" aria-labelledby="viewProductModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title" id="viewProductModalLabel">
                        <i class="fas fa-eye mr-2"></i>Product Details
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="productDetailsContent">
                    <!-- Product details will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Image View Modal -->
    <div class="modal fade" id="imageViewModal" tabindex="-1" role="dialog" aria-labelledby="imageViewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-dark text-white">
                    <h5 class="modal-title" id="imageViewModalLabel">
                        <i class="fas fa-image mr-2"></i>Product Image
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <img id="fullSizeImage" class="img-fluid" alt="Product Image">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <?php include_once('includes/footer2.php');?>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/quick-filters.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <script>
        let currentView = 'grid';
        
        function toggleView(view) {
            const gridView = document.getElementById('gridView');
            const tableView = document.getElementById('tableView');
            const gridBtn = document.getElementById('gridViewBtn');
            const tableBtn = document.getElementById('tableViewBtn');
            
            if (view === 'grid') {
                gridView.style.display = 'grid';
                tableView.style.display = 'none';
                gridBtn.classList.add('active');
                tableBtn.classList.remove('active');
                currentView = 'grid';
            } else {
                gridView.style.display = 'none';
                tableView.style.display = 'block';
                tableBtn.classList.add('active');
                gridBtn.classList.remove('active');
                currentView = 'table';
            }
            
            // Store preference in localStorage
            localStorage.setItem('productViewPreference', view);
        }
        
        // Load view preference on page load
        document.addEventListener('DOMContentLoaded', function() {
            const savedView = localStorage.getItem('productViewPreference') || 'grid';
            toggleView(savedView);
        });

        function clearForm() {
            document.getElementById('riceBagForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('riceBagId').value = '';
            document.getElementById('riceBagModalLabel').innerHTML = '<i class="fas fa-box mr-2"></i>Add New Rice Bag Product';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Save Product';
            
            // Clear image preview
            clearImagePreview();
        }

        // Image handling functions
        function previewImage(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                
                // Validate file size (5MB)
                if (file.size > 5 * 1024 * 1024) {
                    alert('File size should not exceed 5MB');
                    input.value = '';
                    return;
                }
                
                // Validate file type
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
                if (!allowedTypes.includes(file.type)) {
                    alert('Only JPG, PNG, and GIF files are allowed');
                    input.value = '';
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('imagePreview').src = e.target.result;
                    document.getElementById('uploadPrompt').style.display = 'none';
                    document.getElementById('imagePreviewContainer').style.display = 'block';
                }
                reader.readAsDataURL(file);
            }
        }

        function removeImage(event) {
            event.stopPropagation();
            event.preventDefault();
            
            document.getElementById('productImageFile').value = '';
            clearImagePreview();
        }

        function clearImagePreview() {
            document.getElementById('uploadPrompt').style.display = 'block';
            document.getElementById('imagePreviewContainer').style.display = 'none';
            document.getElementById('imagePreview').src = '';
        }

        function showImageModal(imageSrc, productName) {
            document.getElementById('fullSizeImage').src = imageSrc;
            document.getElementById('imageViewModalLabel').innerHTML = '<i class="fas fa-image mr-2"></i>' + productName;
            $('#imageViewModal').modal('show');
        }

        // Drag and drop functionality
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('imageUploadArea');
            
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                uploadArea.addEventListener(eventName, preventDefaults, false);
                document.body.addEventListener(eventName, preventDefaults, false);
            });

            ['dragenter', 'dragover'].forEach(eventName => {
                uploadArea.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                uploadArea.addEventListener(eventName, unhighlight, false);
            });

            uploadArea.addEventListener('drop', handleDrop, false);

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            function highlight(e) {
                uploadArea.classList.add('dragover');
            }

            function unhighlight(e) {
                uploadArea.classList.remove('dragover');
            }

            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    document.getElementById('productImageFile').files = files;
                    previewImage(document.getElementById('productImageFile'));
                }
            }
        });

        function editProduct(productId) {
            // Fetch product data via AJAX
            fetch('api/get-rice-bag.php?id=' + productId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('formAction').value = 'update';
                        document.getElementById('riceBagId').value = data.product.ID;
                        document.getElementById('riceBagName').value = data.product.RiceBagName;
                        document.getElementById('bagKg').value = data.product.BagKg;
                        document.getElementById('brand').value = data.product.Brand;
                        document.getElementById('manufactureType').value = data.product.ManufactureType;
                        document.getElementById('shopRate').value = data.product.ShopRate;
                        document.getElementById('retailRate').value = data.product.RetailRate;
                        document.getElementById('mrp').value = data.product.MRP;
                        document.getElementById('location').value = data.product.Location || '';
                        
                        // Handle existing image
                        if (data.product.ProductImage && data.product.ProductImage !== '') {
                            document.getElementById('imagePreview').src = data.product.ProductImage;
                            document.getElementById('uploadPrompt').style.display = 'none';
                            document.getElementById('imagePreviewContainer').style.display = 'block';
                        } else {
                            clearImagePreview();
                        }
                        
                        document.getElementById('riceBagModalLabel').innerHTML = '<i class="fas fa-edit mr-2"></i>Edit Rice Bag Product';
                        document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Update Product';
                        
                        $('#riceBagModal').modal('show');
                    } else {
                        alert('Error fetching product data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching product data');
                });
        }

        function viewProduct(productId) {
            // Fetch product data via AJAX
            fetch('api/get-rice-bag.php?id=' + productId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const product = data.product;
                        const content = `
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-header bg-dark text-white">
                                            <h6 class="mb-0"><i class="fas fa-image mr-2"></i>Product Image</h6>
                                        </div>
                                        <div class="card-body text-center">
                                            ${product.ProductImage && product.ProductImage !== '' ? 
                                                `<img src="${product.ProductImage}" alt="${product.RiceBagName}" class="product-image-large" onclick="showImageModal('${product.ProductImage}', '${product.RiceBagName}')" style="cursor: pointer;">` : 
                                                `<div class="image-placeholder" style="width: 100%; height: 200px; font-size: 3rem;">
                                                    <i class="fas fa-image"></i>
                                                </div>
                                                <p class="text-muted mt-2">No image available</p>`
                                            }
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-8">
                                    <div class="card">
                                        <div class="card-header bg-primary text-white">
                                            <h6 class="mb-0"><i class="fas fa-info-circle mr-2"></i>Basic Information</h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-2"><strong>Product Name:</strong> ${product.RiceBagName}</div>
                                            <div class="mb-2"><strong>Brand:</strong> ${product.Brand}</div>
                                            <div class="mb-2"><strong>Weight:</strong> ${product.BagKg} Kg</div>
                                            <div class="mb-2"><strong>Type:</strong> 
                                                <span class="badge badge-${product.ManufactureType === 'Premium' ? 'warning' : (product.ManufactureType === 'Standard' ? 'success' : 'info')}">${product.ManufactureType}</span>
                                            </div>
                                            ${product.Location ? `<div class="mb-2"><strong>Location:</strong> ${product.Location}</div>` : ''}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header bg-success text-white">
                                            <h6 class="mb-0"><i class="fas fa-rupee-sign mr-2"></i>Pricing Information</h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-2"><strong>Shop Rate:</strong> <span class="text-success font-weight-bold">₹${parseFloat(product.ShopRate).toLocaleString()}</span></div>
                                            <div class="mb-2"><strong>Retail Rate:</strong> <span class="text-info font-weight-bold">₹${parseFloat(product.RetailRate).toLocaleString()}</span></div>
                                            <div class="mb-2"><strong>MRP:</strong> <span class="text-danger font-weight-bold">₹${parseFloat(product.MRP).toLocaleString()}</span></div>
                                            <hr>
                                            <div class="mb-2"><strong>Profit Margin (Retail):</strong> <span class="text-primary">₹${(parseFloat(product.RetailRate) - parseFloat(product.ShopRate)).toFixed(2)}</span></div>
                                            <div class="mb-2"><strong>Profit Margin (MRP):</strong> <span class="text-warning">₹${(parseFloat(product.MRP) - parseFloat(product.ShopRate)).toFixed(2)}</span></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header bg-info text-white">
                                            <h6 class="mb-0"><i class="fas fa-clock mr-2"></i>Record Information</h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-2"><strong>Created By:</strong> ${product.CreatedByName || 'N/A'}</div>
                                            <div class="mb-2"><strong>Created Date:</strong> ${new Date(product.CreatedDate).toLocaleString()}</div>
                                            ${product.UpdatedByName ? `<div class="mb-2"><strong>Updated By:</strong> ${product.UpdatedByName}</div>` : ''}
                                            ${product.UpdatedDate ? `<div class="mb-2"><strong>Updated Date:</strong> ${new Date(product.UpdatedDate).toLocaleString()}</div>` : ''}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                        
                        document.getElementById('productDetailsContent').innerHTML = content;
                        $('#viewProductModal').modal('show');
                    } else {
                        alert('Error fetching product data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching product data');
                });
        }

        function deleteProduct(productId, productName) {
            if (confirm(`Are you sure you want to delete product "${productName}"? This action cannot be undone.`)) {
                window.location.href = 'rice-bag-management.php?delete=' + productId;
            }
        }

        function exportProducts() {
            // Create workbook
            const wb = XLSX.utils.book_new();
            
            // Get table data (use table view data)
            const table = document.querySelector('#tableView .table');
            const ws = XLSX.utils.table_to_sheet(table);
            
            // Set column widths
            ws['!cols'] = [
                { width: 5 },   // #
                { width: 25 },  // Product Name
                { width: 15 },  // Brand
                { width: 10 },  // Weight
                { width: 12 },  // Type
                { width: 12 },  // Shop Rate
                { width: 12 },  // Retail Rate
                { width: 12 },  // MRP
                { width: 15 },  // Location
                { width: 15 },  // Created Date
                { width: 12 }   // Actions (will be empty in export)
            ];
            
            XLSX.utils.book_append_sheet(wb, ws, 'Rice Bag Products');
            
            // Save file
            const fileName = 'Rice_Bag_Products_Export_' + new Date().toISOString().slice(0, 10) + '.xlsx';
            XLSX.writeFile(wb, fileName);
        }

        // Rate validation - ensure shop rate <= retail rate <= MRP
        function validateRates() {
            const shopRate = parseFloat(document.getElementById('shopRate').value) || 0;
            const retailRate = parseFloat(document.getElementById('retailRate').value) || 0;
            const mrp = parseFloat(document.getElementById('mrp').value) || 0;
            
            if (shopRate > retailRate && retailRate > 0) {
                alert('Shop rate cannot be higher than retail rate!');
                return false;
            }
            
            if (retailRate > mrp && mrp > 0) {
                alert('Retail rate cannot be higher than MRP!');
                return false;
            }
            
            if (shopRate > mrp && mrp > 0) {
                alert('Shop rate cannot be higher than MRP!');
                return false;
            }
            
            return true;
        }

        // Add rate validation on form submit
        document.getElementById('riceBagForm').addEventListener('submit', function(e) {
            if (!validateRates()) {
                e.preventDefault();
                return false;
            }
        });

        // Number input validation
        document.getElementById('bagKg').addEventListener('input', function(e) {
            if (this.value < 0.1 && this.value !== '') {
                this.value = 0.1;
            }
        });

        ['shopRate', 'retailRate', 'mrp'].forEach(id => {
            document.getElementById(id).addEventListener('input', function(e) {
                if (this.value < 0 && this.value !== '') {
                    this.value = 0;
                }
            });
        });

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);

        // Initialize tooltips for better UX
        $(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>

    <?php if ($editRiceBag): ?>
    <script>
        // Auto-populate form for editing
        $(document).ready(function() {
            editProduct(<?php echo $editRiceBag['ID']; ?>);
        });
    </script>
    <?php endif; ?>
</body>
</html>
