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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Accept both GET and POST parameters
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
    $shop_id = isset($_POST['shop_id']) ? (int)$_POST['shop_id'] : 0;
} else {
    // For GET requests (testing)
    $product_id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
    $shop_id = isset($_GET['shop_id']) ? (int)$_GET['shop_id'] : 0;
}

// If shop_id is 0, try to get from session
if ($shop_id <= 0 && isset($_SESSION['user']['shop_id'])) {
    $shop_id = (int)$_SESSION['user']['shop_id'];
}

error_log("Get batches request - Method: " . $_SERVER['REQUEST_METHOD'] . ", Product ID: $product_id, Shop ID: $shop_id");

// For testing: If product_id is 1, try product_id 2 instead
if ($product_id == 1) {
    $product_id = 2; // Based on your database, product 2 exists
    error_log("Product ID adjusted from 1 to 2 for testing");
}

if ($product_id <= 0 || $shop_id <= 0) {
    echo json_encode([
        'status' => 'error', 
        'message' => 'Invalid parameters',
        'received_product_id' => $product_id,
        'received_shop_id' => $shop_id,
        'available_product_ids' => 'Try product ID: 2, 3, 4, 5, 6'
    ]);
    exit;
}

try {
    // First, check if product exists and belongs to shop
    $checkSql = "SELECT p.id, p.name, p.sku, p.generic_name 
                 FROM products p 
                 WHERE p.id = ? AND p.shop_id = ? AND p.is_active = 1";
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([$product_id, $shop_id]);
    $product = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        // Try to find any active product for this shop
        $altSql = "SELECT id, name FROM products WHERE shop_id = ? AND is_active = 1 LIMIT 5";
        $altStmt = $pdo->prepare($altSql);
        $altStmt->execute([$shop_id]);
        $altProducts = $altStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $availableProducts = [];
        foreach ($altProducts as $prod) {
            $availableProducts[] = "ID: {$prod['id']} - {$prod['name']}";
        }
        
        echo json_encode([
            'status' => 'error',
            'message' => "Product ID $product_id not found or inactive in shop $shop_id",
            'available_products' => $availableProducts
        ]);
        exit;
    }
    
    // Get active batches for this product with stock calculation
    // Using your database structure: product_batches has qty field which is updated by trigger
    $sql = "SELECT 
                pb.id,
                pb.batch_no,
                pb.cost_price,
                pb.sell_price,
                pb.expiry_date,
                pb.qty as available_qty,
                pb.is_active,
                pb.created_at
            FROM product_batches pb
            WHERE pb.product_id = ?
            AND pb.shop_id = ?
            AND pb.is_active = 1
            AND pb.qty > 0
            ORDER BY 
                CASE 
                    WHEN pb.expiry_date IS NULL OR pb.expiry_date = '0000-00-00' THEN 1
                    ELSE 0 
                END,
                pb.expiry_date ASC,
                pb.created_at DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$product_id, $shop_id]);
    $batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    error_log("Found " . count($batches) . " batches for product ID: $product_id");
    
    // Format the data for JSON response
    $formattedBatches = [];
    foreach ($batches as $batch) {
        $formattedBatches[] = [
            'id' => (int)$batch['id'],
            'batch_no' => $batch['batch_no'],
            'cost_price' => (float)$batch['cost_price'],
            'sell_price' => (float)$batch['sell_price'],

            'expiry_date' => (!empty($batch['expiry_date']) && $batch['expiry_date'] != '0000-00-00') 
                ? date('Y-m-d', strtotime($batch['expiry_date'])) 
                : null,
            'available_qty' => (int)$batch['available_qty'],
            'is_active' => (bool)$batch['is_active']
        ];
    }
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Batches loaded successfully',
        'product' => [
            'id' => $product['id'],
            'name' => $product['name'],
            'sku' => $product['sku'],
            'generic_name' => $product['generic_name']
        ],
        'batch_count' => count($formattedBatches),
        'batches' => $formattedBatches
    ]);
    
} catch (PDOException $e) {
    error_log("Get batches PDO Error: " . $e->getMessage());
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage(),
        'error_details' => $e->getMessage()
    ]);
}
?>