<?php
// ajax/get_batch_history.php
session_start();
require_once '../../assets/db_connect.php';

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

if (!isset($_SESSION['user']['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Not logged in']);
    exit();
}

if (!isset($_GET['batch_id']) || !is_numeric($_GET['batch_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid batch ID']);
    exit();
}

$batch_id = intval($_GET['batch_id']);
$shop_id = $_SESSION['user']['shop_id'];

try {
    // Get batch basic info
    $batch_sql = "SELECT pb.*, p.name as product_name, p.sku, s.name as supplier_name
                 FROM product_batches pb
                 JOIN products p ON pb.product_id = p.id
                 LEFT JOIN suppliers s ON pb.supplier_id = s.id
                 WHERE pb.id = ? AND pb.shop_id = ?";
    
    $batch_stmt = $pdo->prepare($batch_sql);
    $batch_stmt->execute([$batch_id, $shop_id]);
    $batch = $batch_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$batch) {
        throw new Exception('Batch not found');
    }
    
    // Get batch movement history
    $history_sql = "SELECT 
                    im.id,
                    im.change_qty,
                    im.movement_type,
                    im.reference_id,
                    im.note,
                    DATE_FORMAT(im.created_at, '%Y-%m-%d %H:%i') as movement_date,
                    u.fullname as user_name,
                    CASE 
                        WHEN im.movement_type IN ('PURCHASE', 'RETURN') THEN 'IN'
                        WHEN im.movement_type IN ('SALE', 'ADJUSTMENT') THEN 'OUT'
                        ELSE 'OTHER'
                    END as movement_direction,
                    CASE 
                        WHEN im.movement_type = 'PURCHASE' THEN 'Purchase'
                        WHEN im.movement_type = 'SALE' THEN 'Sale'
                        WHEN im.movement_type = 'ADJUSTMENT' THEN 'Adjustment'
                        WHEN im.movement_type = 'RETURN' THEN 'Return'
                        ELSE im.movement_type
                    END as movement_type_label
                    FROM inventory_movements im
                    LEFT JOIN users u ON im.created_by = u.id
                    WHERE im.batch_id = ?
                    ORDER BY im.created_at DESC";
    
    $history_stmt = $pdo->prepare($history_sql);
    $history_stmt->execute([$batch_id]);
    $history = $history_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate running balance
    $running_qty = 0;
    foreach ($history as &$record) {
        if ($record['movement_direction'] === 'IN') {
            $running_qty += $record['change_qty'];
        } else {
            $running_qty -= $record['change_qty'];
        }
        $record['running_qty'] = $running_qty;
        
        // Add reference links based on movement type
        if ($record['movement_type'] === 'PURCHASE') {
            $record['reference_link'] = "view_purchase.php?id=" . $record['reference_id'];
            $record['reference_text'] = "Purchase #" . $record['reference_id'];
        } elseif ($record['movement_type'] === 'SALE') {
            $record['reference_link'] = "view_sale.php?id=" . $record['reference_id'];
            $record['reference_text'] = "Sale #" . $record['reference_id'];
        } else {
            $record['reference_link'] = "#";
            $record['reference_text'] = "-";
        }
    }
    
    // Get current stock level from movements
    $stock_sql = "SELECT 
                  COALESCE(SUM(
                      CASE 
                          WHEN movement_type IN ('PURCHASE', 'RETURN') THEN change_qty
                          WHEN movement_type IN ('SALE', 'ADJUSTMENT') THEN -change_qty
                          ELSE 0
                      END
                  ), 0) as current_stock
                  FROM inventory_movements
                  WHERE batch_id = ?";
    
    $stock_stmt = $pdo->prepare($stock_sql);
    $stock_stmt->execute([$batch_id]);
    $current_stock = $stock_stmt->fetchColumn();
    
    // Return response
    echo json_encode([
        'status' => 'success',
        'batch' => $batch,
        'history' => $history,
        'current_stock' => $current_stock,
        'history_count' => count($history)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>