<?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'];
    
    if ($action == 'adjust_stock') {
        $riceBagId = (int)$_POST['riceBagId'];
        $adjustmentType = mysqli_real_escape_string($con, $_POST['adjustmentType']);
        $quantity = (float)$_POST['quantity'];
        $reason = mysqli_real_escape_string($con, $_POST['reason']);
        $referenceNumber = mysqli_real_escape_string($con, $_POST['referenceNumber']);
        $adjustmentDate = mysqli_real_escape_string($con, $_POST['adjustmentDate']);
        $location = mysqli_real_escape_string($con, $_POST['location']);
        $notes = mysqli_real_escape_string($con, $_POST['notes']);
        
        // Get current stock (both kg and bags)
        $currentStockQuery = "SELECT CurrentStock, StockInBags, BagKg FROM tblricebags WHERE ID = $riceBagId";
        $currentStockResult = mysqli_query($con, $currentStockQuery);
        $currentStock = 0;
        $currentBags = 0;
        $bagKg = 0;
        
        if ($currentStockResult && mysqli_num_rows($currentStockResult) > 0) {
            $stockData = mysqli_fetch_assoc($currentStockResult);
            $currentStock = (float)$stockData['CurrentStock'];
            $currentBags = (int)$stockData['StockInBags'];
            $bagKg = (float)$stockData['BagKg'];
        }
        
        $previousStock = $currentStock;
        $previousBags = $currentBags;
        
        // Calculate new stock based on adjustment type (quantity is now in bags)
        $quantityInBags = (int)$quantity;
        $quantityInKg = $quantityInBags * $bagKg;
        
        switch ($adjustmentType) {
            case 'Add':
                $newBags = $currentBags + $quantityInBags;
                $newStock = $currentStock + $quantityInKg;
                break;
            case 'Remove':
            case 'Damage':
            case 'Loss':
                $newBags = $currentBags - $quantityInBags;
                $newStock = $currentStock - $quantityInKg;
                break;
            case 'Transfer':
                $newBags = $currentBags - $quantityInBags;
                $newStock = $currentStock - $quantityInKg;
                break;
            case 'Correction':
                $newBags = $quantityInBags; // Direct correction to specific bag count
                $newStock = $quantityInBags * $bagKg; // Calculate kg from bags
                break;
            default:
                $newBags = $currentBags;
                $newStock = $currentStock;
        }
        
        // Ensure stock doesn't go negative
        if ($newBags < 0) {
            $error = "Stock cannot be negative. Current stock: $currentBags bags";
        } else {
            // Insert stock adjustment record (quantity stored as bags)
            $insertQuery = "INSERT INTO tblstockadjustments 
                           (RiceBagID, AdjustmentType, Quantity, PreviousStock, NewStock, Reason, ReferenceNumber, AdjustmentDate, Location, Notes, CreatedBy) 
                           VALUES ($riceBagId, '$adjustmentType', $quantityInBags, $previousBags, $newBags, '$reason', '$referenceNumber', '$adjustmentDate', '$location', '$notes', $userId)";
            
            if (mysqli_query($con, $insertQuery)) {
                // Update both kg and bag stock in rice bags table
                $updateStockQuery = "UPDATE tblricebags SET CurrentStock = $newStock, StockInBags = $newBags, UpdatedBy = $userId, UpdatedDate = NOW() WHERE ID = $riceBagId";
                
                if (mysqli_query($con, $updateStockQuery)) {
                    $success = "Stock adjustment completed successfully! New stock: $newBags bags ($newStock kg)";
                } else {
                    $error = "Error updating stock: " . mysqli_error($con);
                }
            } else {
                $error = "Error recording stock adjustment: " . mysqli_error($con);
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $adjustmentId = (int)$_GET['delete'];
    
    // Get adjustment details before deleting
    $adjustmentQuery = "SELECT * FROM tblstockadjustments WHERE ID = $adjustmentId";
    $adjustmentResult = mysqli_query($con, $adjustmentQuery);
    
    if ($adjustmentResult && mysqli_num_rows($adjustmentResult) > 0) {
        $adjustment = mysqli_fetch_assoc($adjustmentResult);
        
        // Reverse the stock adjustment (restore both kg and bags)
        $riceBagId = $adjustment['RiceBagID'];
        
        // Get bag weight to calculate kg from previous bag stock
        $bagDataQuery = "SELECT BagKg FROM tblricebags WHERE ID = $riceBagId";
        $bagDataResult = mysqli_query($con, $bagDataQuery);
        $bagKg = 25.0; // default
        if ($bagDataResult && mysqli_num_rows($bagDataResult) > 0) {
            $bagKg = (float)mysqli_fetch_assoc($bagDataResult)['BagKg'];
        }
        
        $previousBags = (int)$adjustment['PreviousStock']; // Previous stock is stored as bags
        $previousStockKg = $previousBags * $bagKg;
        
        $reverseStockQuery = "UPDATE tblricebags SET CurrentStock = $previousStockKg, StockInBags = $previousBags, UpdatedBy = $userId, UpdatedDate = NOW() WHERE ID = $riceBagId";
        
        if (mysqli_query($con, $reverseStockQuery)) {
            // Mark adjustment as inactive
            $deleteQuery = "UPDATE tblstockadjustments SET IsActive = 0, UpdatedBy = $userId, UpdatedDate = NOW() WHERE ID = $adjustmentId";
            
            if (mysqli_query($con, $deleteQuery)) {
                $success = "Stock adjustment reversed successfully!";
            } else {
                $error = "Error deleting adjustment record: " . mysqli_error($con);
            }
        } else {
            $error = "Error reversing stock adjustment: " . mysqli_error($con);
        }
    }
}

// Fetch stock adjustments with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$recordsPerPage = 15;
$offset = ($page - 1) * $recordsPerPage;

$searchTerm = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';
$filterType = isset($_GET['type']) ? mysqli_real_escape_string($con, $_GET['type']) : '';
$filterRiceBag = isset($_GET['ricebag']) ? (int)$_GET['ricebag'] : 0;
$filterDateFrom = isset($_GET['date_from']) ? mysqli_real_escape_string($con, $_GET['date_from']) : '';
$filterDateTo = isset($_GET['date_to']) ? mysqli_real_escape_string($con, $_GET['date_to']) : '';

$whereClause = "WHERE sa.IsActive = 1";
if (!empty($searchTerm)) {
    $whereClause .= " AND (r.RiceBagName LIKE '%$searchTerm%' OR sa.Reason LIKE '%$searchTerm%' OR sa.ReferenceNumber LIKE '%$searchTerm%')";
}
if (!empty($filterType)) {
    $whereClause .= " AND sa.AdjustmentType = '$filterType'";
}
if ($filterRiceBag > 0) {
    $whereClause .= " AND sa.RiceBagID = $filterRiceBag";
}
if (!empty($filterDateFrom)) {
    $whereClause .= " AND sa.AdjustmentDate >= '$filterDateFrom'";
}
if (!empty($filterDateTo)) {
    $whereClause .= " AND sa.AdjustmentDate <= '$filterDateTo'";
}

// Count total records
$countQuery = "SELECT COUNT(*) as total FROM tblstockadjustments sa 
               LEFT JOIN tblricebags r ON sa.RiceBagID = r.ID 
               $whereClause";
$countResult = mysqli_query($con, $countQuery);
$totalRecords = mysqli_fetch_assoc($countResult)['total'];
$totalPages = ceil($totalRecords / $recordsPerPage);

// Fetch stock adjustments
$adjustmentsQuery = "SELECT sa.*, r.RiceBagName, r.Brand, r.BagKg, r.ManufactureType, 
                     u.FullName as CreatedByName, u2.FullName as UpdatedByName 
                     FROM tblstockadjustments sa 
                     LEFT JOIN tblricebags r ON sa.RiceBagID = r.ID 
                     LEFT JOIN tblusers u ON sa.CreatedBy = u.ID 
                     LEFT JOIN tblusers u2 ON sa.UpdatedBy = u2.ID 
                     $whereClause 
                     ORDER BY sa.CreatedDate DESC 
                     LIMIT $offset, $recordsPerPage";
$adjustmentsResult = mysqli_query($con, $adjustmentsQuery);

// Get statistics
$statsQuery = "SELECT 
    COUNT(*) as TotalAdjustments,
    COUNT(CASE WHEN AdjustmentType = 'Add' THEN 1 END) as AddAdjustments,
    COUNT(CASE WHEN AdjustmentType IN ('Remove', 'Damage', 'Loss') THEN 1 END) as ReduceAdjustments,
    COUNT(CASE WHEN AdjustmentType = 'Transfer' THEN 1 END) as TransferAdjustments,
    SUM(CASE WHEN AdjustmentType = 'Add' THEN Quantity ELSE 0 END) as TotalAdded,
    SUM(CASE WHEN AdjustmentType IN ('Remove', 'Damage', 'Loss', 'Transfer') THEN Quantity ELSE 0 END) as TotalReduced
    FROM tblstockadjustments WHERE IsActive = 1";
$statsResult = mysqli_query($con, $statsQuery);
$stats = mysqli_fetch_assoc($statsResult);

// Get current total stock value
$stockValueQuery = "SELECT 
    SUM(CurrentStock) as TotalStock,
    COUNT(*) as TotalProducts,
    SUM(CurrentStock * ShopRate) as TotalValue
    FROM tblricebags WHERE IsActive = 1";
$stockValueResult = mysqli_query($con, $stockValueQuery);
$stockValue = mysqli_fetch_assoc($stockValueResult);

// Get rice bags for filter dropdown
$riceBagsQuery = "SELECT ID, RiceBagName, Brand FROM tblricebags WHERE IsActive = 1 ORDER BY RiceBagName";
$riceBagsResult = mysqli_query($con, $riceBagsQuery);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Stock Adjustment | 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>
        .adjustment-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .adjustment-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .type-add { border-left: 4px solid #1cc88a; }
        .type-remove { border-left: 4px solid #e74a3b; }
        .type-damage { border-left: 4px solid #f6c23e; }
        .type-loss { border-left: 4px solid #36b9cc; }
        .type-transfer { border-left: 4px solid #6f42c1; }
        .type-correction { border-left: 4px solid #6c757d; }
        
        .modal-header { background: linear-gradient(45deg, #4e73df, #36b9cc); color: white; }
        .required { color: red; }
        
        .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; }
        
        .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;
        }
        
        .adjustment-type-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-weight: 500;
        }
        
        .badge-add { background: #d4edda; color: #155724; }
        .badge-remove { background: #f8d7da; color: #721c24; }
        .badge-damage { background: #fff3cd; color: #856404; }
        .badge-loss { background: #d1ecf1; color: #0c5460; }
        .badge-transfer { background: #e2e3f1; color: #383d41; }
        .badge-correction { background: #e9ecef; color: #495057; }
        
        .stock-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .current-stock {
            font-size: 1.5rem;
            font-weight: 600;
            text-align: center;
        }
        
        .stock-details {
            display: flex;
            justify-content: space-between;
            margin-top: 0.5rem;
            font-size: 0.9rem;
        }
        
        .quantity-input {
            font-size: 1.1rem;
            font-weight: 600;
            text-align: center;
        }
        
        .bags-input {
            font-size: 1.0rem;
            font-weight: 500;
            text-align: center;
            background-color: #f8f9fa !important;
            border: 2px dashed #dee2e6 !important;
        }
        
        .bag-calculation-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 6px;
            padding: 0.5rem;
            margin-top: 0.25rem;
            font-size: 0.85rem;
        }
        
        .adjustment-preview {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .preview-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }
        
        .preview-new-stock {
            font-size: 1.2rem;
            font-weight: 600;
            color: #1cc88a;
        }
        
        @media (max-width: 768px) {
            .form-group { margin-bottom: 0.5rem; }
            .modal-body { padding: 1rem; }
            .stats-card { margin-bottom: 1rem; }
        }
    </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-boxes mr-2"></i>Stock Adjustment
                        </h1>
                        <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#stockAdjustmentModal" onclick="clearForm()">
                            <i class="fas fa-plus-circle mr-1"></i>New Adjustment
                        </button>
                    </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-triangle 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-success shadow h-100 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">Total Stock</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php 
                                                // Calculate total bags from database
                                                $totalBagsQuery = "SELECT SUM(StockInBags) as TotalBags FROM tblricebags WHERE IsActive = 1";
                                                $totalBagsResult = mysqli_query($con, $totalBagsQuery);
                                                $totalBags = mysqli_fetch_assoc($totalBagsResult)['TotalBags'] ?? 0;
                                                echo number_format($totalBags); 
                                                ?> bags
                                            </div>
                                            <div class="text-xs text-muted">
                                                (<?php echo number_format($stockValue['TotalStock'], 0); ?> kg)
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-boxes 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 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">Stock Value</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                ₹<?php echo number_format($stockValue['TotalValue'], 2); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-rupee-sign 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-primary shadow h-100 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 Adjustments</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['TotalAdjustments']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-edit 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 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">Products</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stockValue['TotalProducts']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-box 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">
                            <form method="GET" class="row">
                                <div class="col-md-3 mb-2">
                                    <input type="text" class="form-control form-control-sm" name="search" 
                                           placeholder="Search adjustments..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                </div>
                                <div class="col-md-2 mb-2">
                                    <select class="form-control form-control-sm" name="type">
                                        <option value="">All Types</option>
                                        <option value="Add" <?php echo $filterType == 'Add' ? 'selected' : ''; ?>>Add</option>
                                        <option value="Remove" <?php echo $filterType == 'Remove' ? 'selected' : ''; ?>>Remove</option>
                                        <option value="Damage" <?php echo $filterType == 'Damage' ? 'selected' : ''; ?>>Damage</option>
                                        <option value="Loss" <?php echo $filterType == 'Loss' ? 'selected' : ''; ?>>Loss</option>
                                        <option value="Transfer" <?php echo $filterType == 'Transfer' ? 'selected' : ''; ?>>Transfer</option>
                                        <option value="Correction" <?php echo $filterType == 'Correction' ? 'selected' : ''; ?>>Correction</option>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-2">
                                    <select class="form-control form-control-sm" name="ricebag">
                                        <option value="">All Products</option>
                                        <?php while ($riceBag = mysqli_fetch_assoc($riceBagsResult)): ?>
                                        <option value="<?php echo $riceBag['ID']; ?>" <?php echo $filterRiceBag == $riceBag['ID'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($riceBag['RiceBagName'] . ' - ' . $riceBag['Brand']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-2">
                                    <input type="date" class="form-control form-control-sm" name="date_from" 
                                           placeholder="From Date" value="<?php echo $filterDateFrom; ?>">
                                </div>
                                <div class="col-md-2 mb-2">
                                    <input type="date" class="form-control form-control-sm" name="date_to" 
                                           placeholder="To Date" value="<?php echo $filterDateTo; ?>">
                                </div>
                                <div class="col-md-1 mb-2">
                                    <button type="submit" class="btn btn-primary btn-sm">
                                        <i class="fas fa-search"></i>
                                    </button>
                                    <a href="stock-adjustment.php" class="btn btn-secondary btn-sm ml-1">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Stock Adjustments Table -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-history mr-2"></i>Stock Adjustment History
                            </h6>
                            <div>
                                <button class="btn btn-success btn-sm" onclick="exportAdjustments()">
                                    <i class="fas fa-file-excel mr-1"></i>Export
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>#</th>
                                            <th>Date</th>
                                            <th>Product</th>
                                            <th>Type</th>
                                            <th>Quantity</th>
                                            <th>Previous Stock</th>
                                            <th>New Stock</th>
                                            <th>Reason</th>
                                            <th>Reference</th>
                                            <th>Created By</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $serialNumber = $offset + 1;
                                        if ($adjustmentsResult && mysqli_num_rows($adjustmentsResult) > 0):
                                            while ($adjustment = mysqli_fetch_assoc($adjustmentsResult)): 
                                        ?>
                                        <tr>
                                            <td><?php echo $serialNumber++; ?></td>
                                            <td><?php echo date('d/m/Y', strtotime($adjustment['AdjustmentDate'])); ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($adjustment['RiceBagName']); ?></strong><br>
                                                <small class="text-muted">
                                                    <?php echo htmlspecialchars($adjustment['Brand']); ?> - <?php echo $adjustment['BagKg']; ?>kg
                                                </small>
                                            </td>
                                            <td>
                                                <span class="adjustment-type-badge badge-<?php echo strtolower($adjustment['AdjustmentType']); ?>">
                                                    <?php echo $adjustment['AdjustmentType']; ?>
                                                </span>
                                            </td>
                                            <td class="text-right font-weight-bold">
                                                <?php 
                                                $sign = in_array($adjustment['AdjustmentType'], ['Add']) ? '+' : 
                                                       (in_array($adjustment['AdjustmentType'], ['Remove', 'Damage', 'Loss', 'Transfer']) ? '-' : '');
                                                echo $sign . number_format($adjustment['Quantity'], 0); 
                                                ?> bags
                                                <div class="text-xs text-muted">
                                                    (<?php echo $sign . number_format($adjustment['Quantity'] * $adjustment['BagKg'], 0); ?> kg)
                                                </div>
                                            </td>
                                            <td class="text-right">
                                                <?php echo number_format($adjustment['PreviousStock'], 0); ?> bags
                                                <div class="text-xs text-muted">
                                                    (<?php echo number_format($adjustment['PreviousStock'] * $adjustment['BagKg'], 0); ?> kg)
                                                </div>
                                            </td>
                                            <td class="text-right font-weight-bold text-success">
                                                <?php echo number_format($adjustment['NewStock'], 0); ?> bags
                                                <div class="text-xs text-muted">
                                                    (<?php echo number_format($adjustment['NewStock'] * $adjustment['BagKg'], 0); ?> kg)
                                                </div>
                                            </td>
                                            <td title="<?php echo htmlspecialchars($adjustment['Reason']); ?>">
                                                <?php echo htmlspecialchars(substr($adjustment['Reason'], 0, 30)) . (strlen($adjustment['Reason']) > 30 ? '...' : ''); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($adjustment['ReferenceNumber']); ?></td>
                                            <td>
                                                <?php echo htmlspecialchars($adjustment['CreatedByName']); ?><br>
                                                <small class="text-muted"><?php echo date('d/m/Y H:i', strtotime($adjustment['CreatedDate'])); ?></small>
                                            </td>
                                            <td>
                                                <button class="btn btn-info btn-sm" onclick="viewAdjustment(<?php echo $adjustment['ID']; ?>)" 
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <?php if ($userType == 'admin' || $adjustment['CreatedBy'] == $userId): ?>
                                                <button class="btn btn-danger btn-sm ml-1" 
                                                        onclick="deleteAdjustment(<?php echo $adjustment['ID']; ?>, '<?php echo addslashes($adjustment['RiceBagName']); ?>')" 
                                                        title="Reverse Adjustment">
                                                    <i class="fas fa-undo"></i>
                                                </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php 
                                            endwhile;
                                        else:
                                        ?>
                                        <tr>
                                            <td colspan="11" class="text-center text-muted py-4">
                                                <i class="fas fa-inbox fa-3x mb-3"></i><br>
                                                No stock adjustments found
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <nav aria-label="Stock adjustment pagination">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>&ricebag=<?php echo $filterRiceBag; ?>&date_from=<?php echo $filterDateFrom; ?>&date_to=<?php echo $filterDateTo; ?>">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); ?>&type=<?php echo urlencode($filterType); ?>&ricebag=<?php echo $filterRiceBag; ?>&date_from=<?php echo $filterDateFrom; ?>&date_to=<?php echo $filterDateTo; ?>"><?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); ?>&type=<?php echo urlencode($filterType); ?>&ricebag=<?php echo $filterRiceBag; ?>&date_from=<?php echo $filterDateFrom; ?>&date_to=<?php echo $filterDateTo; ?>">Next</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

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

    <!-- Stock Adjustment Modal -->
    <div class="modal fade" id="stockAdjustmentModal" tabindex="-1" role="dialog" aria-labelledby="stockAdjustmentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="stockAdjustmentModalLabel">
                        <i class="fas fa-boxes mr-2"></i>Stock Adjustment
                    </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="stockAdjustmentForm">
                    <input type="hidden" name="action" value="adjust_stock">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="riceBagId">Rice Bag Product <span class="required">*</span></label>
                                    <select class="form-control" id="riceBagId" name="riceBagId" required onchange="loadStockInfo()">
                                        <option value="">Select Rice Bag</option>
                                        <!-- Options will be loaded via JavaScript -->
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="adjustmentType">Adjustment Type <span class="required">*</span></label>
                                    <select class="form-control" id="adjustmentType" name="adjustmentType" required onchange="updatePreview()">
                                        <option value="">Select Type</option>
                                        <option value="Add">Add Stock</option>
                                        <option value="Remove">Remove Stock</option>
                                        <option value="Damage">Damage</option>
                                        <option value="Loss">Loss</option>
                                        <option value="Transfer">Transfer</option>
                                        <option value="Correction">Stock Correction</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Stock Info Display -->
                        <div id="stockInfoDisplay" style="display: none;">
                            <div class="stock-info">
                                <div class="current-stock" id="currentStockDisplay">0 bags</div>
                                <div class="stock-details">
                                    <span>Current Stock</span>
                                    <span id="stockLocation">-</span>
                                </div>
                                <div class="stock-details">
                                    <span id="currentStockKg">0 kg total</span>
                                    <span id="stockBagWeight">0kg per bag</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="quantity">Number of Bags <span class="required">*</span></label>
                                    <input type="number" class="form-control quantity-input" id="quantity" name="quantity" 
                                           step="1" min="1" required oninput="updatePreview(); calculateKgFromBags()"
                                    <small class="form-text text-muted" id="quantityHelp">Enter the number of bags to adjust</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="totalKg">Total Weight (kg) <i class="fas fa-calculator text-info" title="Auto-calculated from bags"></i></label>
                                    <input type="number" class="form-control bags-input" id="totalKg" name="totalKg" 
                                           step="0.01" min="0" readonly>
                                    <small class="form-text text-info" id="kgHelp">Automatically calculated</small>
                                    <div id="bagCalculationInfo" class="bag-calculation-info" style="display: none;">
                                        <i class="fas fa-info-circle mr-1"></i>
                                        <span id="bagWeightInfo">0kg per bag</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="adjustmentDate">Adjustment Date <span class="required">*</span></label>
                                    <input type="date" class="form-control" id="adjustmentDate" name="adjustmentDate" 
                                           value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="referenceNumber">Reference Number</label>
                                    <input type="text" class="form-control" id="referenceNumber" name="referenceNumber" 
                                           placeholder="e.g., ADJ-001, PO-123">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="location">Location</label>
                                    <input type="text" class="form-control" id="location" name="location" 
                                           placeholder="e.g., Warehouse A, Godown 1">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="reason">Reason <span class="required">*</span></label>
                            <textarea class="form-control" id="reason" name="reason" rows="3" required 
                                      placeholder="Enter the reason for this stock adjustment"></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">Additional Notes</label>
                            <textarea class="form-control" id="notes" name="notes" rows="2" 
                                      placeholder="Any additional notes or comments"></textarea>
                        </div>
                        
                        <!-- Adjustment Preview -->
                        <div id="adjustmentPreview" class="adjustment-preview" style="display: none;">
                            <h6><i class="fas fa-calculator mr-2"></i>Adjustment Preview</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="preview-row">
                                        <span>Current Stock:</span>
                                        <span id="previewCurrentStock">0.00 kg</span>
                                    </div>
                                    <div class="preview-row">
                                        <span>Adjustment:</span>
                                        <span id="previewAdjustment">0.00 kg</span>
                                    </div>
                                    <hr>
                                    <div class="preview-row">
                                        <span><strong>New Stock:</strong></span>
                                        <span class="preview-new-stock" id="previewNewStock">0.00 kg</span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="preview-row">
                                        <span>Current Bags:</span>
                                        <span id="previewCurrentBags">0.00 bags</span>
                                    </div>
                                    <div class="preview-row">
                                        <span>Adjustment Bags:</span>
                                        <span id="previewAdjustmentBags">0.00 bags</span>
                                    </div>
                                    <hr>
                                    <div class="preview-row">
                                        <span><strong>New Bags:</strong></span>
                                        <span class="preview-new-stock" id="previewNewBags">0.00 bags</span>
                                    </div>
                                </div>
                            </div>
                        </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 Adjustment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Adjustment Modal -->
    <div class="modal fade" id="viewAdjustmentModal" tabindex="-1" role="dialog" aria-labelledby="viewAdjustmentModalLabel" 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="viewAdjustmentModalLabel">
                        <i class="fas fa-eye mr-2"></i>Adjustment 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="adjustmentDetailsContent">
                    <!-- Content will be loaded via JavaScript -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>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="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <script>
        let riceBags = [];
        let currentStock = 0;
        let currentBags = 0;
        let bagWeight = 0;

        // Load rice bags on page load
        $(document).ready(function() {
            loadRiceBags();
        });

        function loadRiceBags() {
            fetch('api/get-stock-data.php')
                .then(response => response.json())
                .then(data => {
                    riceBags = data;
                    const select = document.getElementById('riceBagId');
                    select.innerHTML = '<option value="">Select Rice Bag</option>';
                    
                    data.forEach(bag => {
                        const option = document.createElement('option');
                        option.value = bag.ID;
                        option.textContent = `${bag.RiceBagName} - ${bag.Brand} (${bag.BagKg}kg) - Stock: ${bag.StockInBags || 0} bags`;
                        option.dataset.stock = bag.CurrentStock;
                        option.dataset.stockBags = bag.StockInBags || 0;
                        option.dataset.bagKg = bag.BagKg;
                        option.dataset.location = bag.Location || 'Not specified';
                        select.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('Error loading rice bags:', error);
                    alert('Error loading rice bags');
                });
        }

        function loadStockInfo() {
            const select = document.getElementById('riceBagId');
            const selectedOption = select.options[select.selectedIndex];
            
            if (selectedOption.value) {
                currentStock = parseFloat(selectedOption.dataset.stock || 0);
                currentBags = parseInt(selectedOption.dataset.stockBags || 0);
                bagWeight = parseFloat(selectedOption.dataset.bagKg || 0);
                const location = selectedOption.dataset.location || 'Not specified';
                
                document.getElementById('currentStockDisplay').textContent = currentBags + ' bags';
                document.getElementById('currentStockKg').textContent = currentStock.toFixed(0) + ' kg total';
                document.getElementById('stockBagWeight').textContent = bagWeight + 'kg per bag';
                document.getElementById('stockLocation').textContent = location;
                document.getElementById('stockInfoDisplay').style.display = 'block';
                document.getElementById('location').value = location;
                
                // Update kg calculation info
                if (bagWeight > 0) {
                    document.getElementById('kgHelp').textContent = `Auto-calculated from bags × ${bagWeight}kg`;
                    document.getElementById('bagWeightInfo').textContent = `${bagWeight}kg per bag`;
                    document.getElementById('bagCalculationInfo').style.display = 'block';
                } else {
                    document.getElementById('kgHelp').textContent = 'Bag weight not specified';
                    document.getElementById('bagCalculationInfo').style.display = 'none';
                }
                
                calculateKgFromBags();
                updatePreview();
            } else {
                document.getElementById('stockInfoDisplay').style.display = 'none';
                document.getElementById('adjustmentPreview').style.display = 'none';
                document.getElementById('bagCalculationInfo').style.display = 'none';
                document.getElementById('totalKg').value = '';
                bagWeight = 0;
                currentBags = 0;
            }
        }

        function calculateKgFromBags() {
            const bags = parseInt(document.getElementById('quantity').value) || 0;
            
            if (bagWeight > 0 && bags > 0) {
                const totalKg = bags * bagWeight;
                document.getElementById('totalKg').value = totalKg.toFixed(0);
            } else {
                document.getElementById('totalKg').value = '';
            }
        }

        function updatePreview() {
            const riceBagSelect = document.getElementById('riceBagId');
            const adjustmentType = document.getElementById('adjustmentType').value;
            const bags = parseInt(document.getElementById('quantity').value) || 0;
            
            if (riceBagSelect.value && adjustmentType && bags > 0) {
                let newBags = currentBags;
                let newStock = currentStock;
                let adjustmentText = '';
                let bagAdjustmentText = '';
                let adjustmentSign = '';
                
                const adjustmentKg = bags * bagWeight;
                
                switch (adjustmentType) {
                    case 'Add':
                        newBags = currentBags + bags;
                        newStock = currentStock + adjustmentKg;
                        adjustmentText = `+${adjustmentKg.toFixed(0)} kg`;
                        bagAdjustmentText = `+${bags} bags`;
                        adjustmentSign = '+';
                        document.getElementById('quantityHelp').textContent = 'Enter number of bags to add to stock';
                        break;
                    case 'Remove':
                    case 'Damage':
                    case 'Loss':
                    case 'Transfer':
                        newBags = currentBags - bags;
                        newStock = currentStock - adjustmentKg;
                        adjustmentText = `-${adjustmentKg.toFixed(0)} kg`;
                        bagAdjustmentText = `-${bags} bags`;
                        adjustmentSign = '-';
                        document.getElementById('quantityHelp').textContent = 'Enter number of bags to remove from stock';
                        break;
                    case 'Correction':
                        newBags = bags;
                        newStock = bags * bagWeight;
                        adjustmentText = `Set to ${newStock.toFixed(0)} kg`;
                        bagAdjustmentText = `Set to ${bags} bags`;
                        adjustmentSign = '=';
                        document.getElementById('quantityHelp').textContent = 'Enter the correct number of bags in stock';
                        break;
                }
                
                // Validate negative stock
                if (newBags < 0 && adjustmentType !== 'Correction') {
                    document.getElementById('quantity').classList.add('is-invalid');
                    document.getElementById('submitBtn').disabled = true;
                    document.getElementById('quantityHelp').textContent = 'Insufficient stock! Available: ' + currentBags + ' bags';
                    document.getElementById('quantityHelp').className = 'form-text text-danger';
                } else {
                    document.getElementById('quantity').classList.remove('is-invalid');
                    document.getElementById('submitBtn').disabled = false;
                    document.getElementById('quantityHelp').className = 'form-text text-muted';
                }
                
                // Update preview - Bags (primary)
                document.getElementById('previewCurrentBags').textContent = currentBags + ' bags';
                document.getElementById('previewAdjustmentBags').textContent = bagAdjustmentText;
                document.getElementById('previewNewBags').textContent = newBags + ' bags';
                document.getElementById('previewNewBags').style.color = newBags >= 0 ? '#1cc88a' : '#e74a3b';
                
                // Update preview - Stock (secondary)
                document.getElementById('previewCurrentStock').textContent = currentStock.toFixed(0) + ' kg';
                document.getElementById('previewAdjustment').textContent = adjustmentText;
                document.getElementById('previewNewStock').textContent = newStock.toFixed(0) + ' kg';
                document.getElementById('previewNewStock').style.color = newStock >= 0 ? '#1cc88a' : '#e74a3b';
                
                document.getElementById('adjustmentPreview').style.display = 'block';
            } else {
                document.getElementById('adjustmentPreview').style.display = 'none';
            }
        }

        function clearForm() {
            document.getElementById('stockAdjustmentForm').reset();
            document.getElementById('adjustmentDate').value = new Date().toISOString().split('T')[0];
            document.getElementById('stockInfoDisplay').style.display = 'none';
            document.getElementById('adjustmentPreview').style.display = 'none';
            document.getElementById('bagCalculationInfo').style.display = 'none';
            document.getElementById('quantity').classList.remove('is-invalid');
            document.getElementById('totalKg').value = '';
            document.getElementById('submitBtn').disabled = false;
            document.getElementById('quantityHelp').className = 'form-text text-muted';
            document.getElementById('quantityHelp').textContent = 'Enter the number of bags to adjust';
            document.getElementById('kgHelp').textContent = 'Automatically calculated';
            currentStock = 0;
            currentBags = 0;
            bagWeight = 0;
        }

        function viewAdjustment(adjustmentId) {
            // This would fetch and display adjustment details
            // For now, we'll show a placeholder
            document.getElementById('adjustmentDetailsContent').innerHTML = `
                <div class="text-center">
                    <i class="fas fa-spinner fa-spin fa-2x mb-3"></i><br>
                    Loading adjustment details...
                </div>
            `;
            $('#viewAdjustmentModal').modal('show');
            
            // You can implement the actual fetch here
            // fetch('api/get-adjustment-details.php?id=' + adjustmentId)
        }

        function deleteAdjustment(adjustmentId, productName) {
            if (confirm(`Are you sure you want to reverse this stock adjustment for "${productName}"? This will restore the previous stock level.`)) {
                window.location.href = 'stock-adjustment.php?delete=' + adjustmentId;
            }
        }

        function exportAdjustments() {
            // Create workbook
            const wb = XLSX.utils.book_new();
            
            // Get table data
            const table = document.querySelector('.table');
            const ws = XLSX.utils.table_to_sheet(table);
            
            // Set column widths
            ws['!cols'] = [
                { width: 5 },   // #
                { width: 12 },  // Date
                { width: 25 },  // Product
                { width: 12 },  // Type
                { width: 12 },  // Quantity
                { width: 15 },  // Previous Stock
                { width: 15 },  // New Stock
                { width: 30 },  // Reason
                { width: 15 },  // Reference
                { width: 15 },  // Created By
                { width: 12 }   // Actions (will be empty in export)
            ];
            
            XLSX.utils.book_append_sheet(wb, ws, 'Stock Adjustments');
            
            // Save file
            const fileName = 'Stock_Adjustments_Export_' + new Date().toISOString().slice(0, 10) + '.xlsx';
            XLSX.writeFile(wb, fileName);
        }

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

        // Initialize tooltips
        $(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });

        // Auto-generate reference number
        document.getElementById('adjustmentType').addEventListener('change', function() {
            if (this.value && !document.getElementById('referenceNumber').value) {
                const date = new Date();
                const dateStr = date.getFullYear().toString().substr(-2) + 
                               String(date.getMonth() + 1).padStart(2, '0') + 
                               String(date.getDate()).padStart(2, '0');
                const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                document.getElementById('referenceNumber').value = `ADJ-${dateStr}-${randomNum}`;
            }
        });
    </script>
</body>
</html>
