<?php
/**
 * Utility script to synchronize bag stock based on current kg stock
 * This ensures StockInBags is always accurate based on CurrentStock and BagKg
 */

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

// Check if user is logged in and is admin
if (!isset($_SESSION['uid']) || $_SESSION['role'] !== 'Admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized - Admin access required']);
    exit();
}

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

try {
    // Update StockInBags based on CurrentStock / BagKg
    $updateQuery = "
        UPDATE tblricebags 
        SET StockInBags = FLOOR(CurrentStock / BagKg) 
        WHERE BagKg > 0 AND IsActive = 1
    ";
    
    $result = mysqli_query($con, $updateQuery);
    
    if ($result) {
        $affectedRows = mysqli_affected_rows($con);
        
        // Get summary of updated records
        $summaryQuery = "
            SELECT 
                COUNT(*) as total_products,
                SUM(StockInBags) as total_bags,
                SUM(CurrentStock) as total_kg
            FROM tblricebags 
            WHERE IsActive = 1
        ";
        
        $summaryResult = mysqli_query($con, $summaryQuery);
        $summary = mysqli_fetch_assoc($summaryResult);
        
        echo json_encode([
            'success' => true,
            'message' => 'Bag stock synchronized successfully',
            'affected_rows' => $affectedRows,
            'summary' => $summary
        ]);
    } else {
        throw new Exception('Failed to update bag stock: ' . mysqli_error($con));
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
