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

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

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

// Log the request for debugging
error_log("=== SAVE BATCH REQUEST START ===");
error_log("POST data: " . print_r($_POST, true));

if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    error_log("Session expired or missing");
    echo json_encode(['status' => 'error', 'message' => 'Session expired. Please login again.']);
    exit;
}

$user_id = $_SESSION['user']['id'];
$shop_id = $_SESSION['user']['shop_id'];

error_log("User ID: $user_id, Shop ID: $shop_id");

// Validate required fields
$required = ['product_id', 'batch_no', 'expiry_date', 'supplier_id', 'quantity', 'cost_price', 'sell_price'];
$missing_fields = [];

foreach ($required as $field) {
    if (!isset($_POST[$field]) || trim($_POST[$field]) === '') {
        $missing_fields[] = $field;
    }
}

if (!empty($missing_fields)) {
    error_log("Missing required fields: " . implode(', ', $missing_fields));
    echo json_encode([
        'status' => 'error', 
        'message' => "Missing required fields: " . implode(', ', $missing_fields)
    ]);
    exit;
}

// Sanitize and validate input
$product_id = intval($_POST['product_id']);
$batch_no = trim($_POST['batch_no']);
$expiry_date = $_POST['expiry_date'];
$supplier_id = intval($_POST['supplier_id']);
$quantity = intval($_POST['quantity']);
$cost_price = floatval($_POST['cost_price']);
$sell_price = floatval($_POST['sell_price']);

error_log("Parsed values - Product ID: $product_id, Batch No: $batch_no, Quantity: $quantity");

// Validate numeric values
if ($quantity <= 0) {
    error_log("Invalid quantity: $quantity");
    echo json_encode(['status' => 'error', 'message' => 'Quantity must be greater than 0.']);
    exit;
}

if ($cost_price <= 0) {
    error_log("Invalid cost price: $cost_price");
    echo json_encode(['status' => 'error', 'message' => 'Cost price must be greater than 0.']);
    exit;
}

if ($sell_price <= 0) {
    error_log("Invalid sell price: $sell_price");
    echo json_encode(['status' => 'error', 'message' => 'Selling price must be greater than 0.']);
    exit;
}

try {
    // Verify product exists and belongs to shop
    $check_sql = "SELECT id, name FROM products WHERE id = ? AND shop_id = ?";
    $check_stmt = $pdo->prepare($check_sql);
    $check_stmt->execute([$product_id, $shop_id]);
    $product = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        error_log("Product not found: ID $product_id, Shop $shop_id");
        echo json_encode([
            'status' => 'error', 
            'message' => 'Product not found or you do not have permission to add batches to this product.'
        ]);
        exit;
    }
    
    error_log("Product found: " . $product['name'] . " (ID: " . $product['id'] . ")");
    
    // Check if batch number already exists for this product
    $batch_check_sql = "SELECT id, batch_no FROM product_batches WHERE product_id = ? AND batch_no = ? AND shop_id = ?";
    $batch_check_stmt = $pdo->prepare($batch_check_sql);
    $batch_check_stmt->execute([$product_id, $batch_no, $shop_id]);
    
    if ($existing_batch = $batch_check_stmt->fetch(PDO::FETCH_ASSOC)) {
        error_log("Batch number already exists: " . $existing_batch['batch_no'] . " (ID: " . $existing_batch['id'] . ")");
        echo json_encode([
            'status' => 'error', 
            'message' => "Batch number '$batch_no' already exists for this product. Please use a different batch number."
        ]);
        exit;
    }
    
    // Check if supplier exists
    $supplier_check_sql = "SELECT id FROM suppliers WHERE id = ?";
    $supplier_check_stmt = $pdo->prepare($supplier_check_sql);
    $supplier_check_stmt->execute([$supplier_id]);
    
    if (!$supplier_check_stmt->fetch()) {
        error_log("Supplier not found: ID $supplier_id");
        echo json_encode(['status' => 'error', 'message' => 'Selected supplier does not exist.']);
        exit;
    }
    
    // Validate expiry date format
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiry_date)) {
        error_log("Invalid expiry date format: $expiry_date");
        echo json_encode(['status' => 'error', 'message' => 'Invalid expiry date format. Use YYYY-MM-DD.']);
        exit;
    }
    
    // Start transaction
    $pdo->beginTransaction();
    error_log("Transaction started");
    
    // Insert batch record - using DEFAULT values for timestamps
    $insert_sql = "INSERT INTO product_batches 
                  (product_id, batch_no, qty, cost_price, sell_price, expiry_date, supplier_id, created_by, shop_id, updated_by)
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    error_log("Insert SQL: $insert_sql");
    error_log("Insert values: [$product_id, '$batch_no', $quantity, $cost_price, $sell_price, '$expiry_date', $supplier_id, $user_id, $shop_id, $user_id]");
    
    $insert_stmt = $pdo->prepare($insert_sql);
    $insert_result = $insert_stmt->execute([
        $product_id,
        $batch_no,
        $quantity,
        $cost_price,
        $sell_price,
        $expiry_date,
        $supplier_id,
        $user_id,
        $shop_id,
        $user_id  // updated_by
    ]);
    
    if (!$insert_result) {
        error_log("Failed to insert batch record");
        $error_info = $insert_stmt->errorInfo();
        error_log("SQL Error: " . print_r($error_info, true));
        throw new Exception("Failed to insert batch record: " . ($error_info[2] ?? 'Unknown error'));
    }
    
    $batch_id = $pdo->lastInsertId();
    error_log("Batch inserted successfully. Batch ID: $batch_id");
    
    // Create inventory movement for purchase
    $movement_sql = "INSERT INTO inventory_movements 
                    (product_id, batch_id, change_qty, movement_type, created_by, shop_id)
                    VALUES (?, ?, ?, 'PURCHASE', ?, ?)";
    
    error_log("Movement SQL: $movement_sql");
    
    $movement_stmt = $pdo->prepare($movement_sql);
    $movement_result = $movement_stmt->execute([
        $product_id,
        $batch_id,
        $quantity,
        $user_id,
        $shop_id
    ]);
    
    if (!$movement_result) {
        error_log("Failed to insert inventory movement");
        $error_info = $movement_stmt->errorInfo();
        error_log("SQL Error: " . print_r($error_info, true));
        throw new Exception("Failed to insert inventory movement: " . ($error_info[2] ?? 'Unknown error'));
    }
    
    // Update product's buying and selling prices if this is the first batch
    $update_product_sql = "UPDATE products 
                          SET buying_price = ?, selling_price = ?
                          WHERE id = ? AND (buying_price = 0 OR buying_price IS NULL)";
    $update_product_stmt = $pdo->prepare($update_product_sql);
    $update_product_stmt->execute([$cost_price, $sell_price, $product_id]);
    
    // Commit transaction
    $pdo->commit();
    error_log("Transaction committed successfully");
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Batch added successfully! Stock has been updated.',
        'batch_id' => $batch_id,
        'product_id' => $product_id,
        'product_name' => $product['name'],
        'batch_no' => $batch_no,
        'quantity' => $quantity
    ]);
    
} catch (Exception $e) {
    // Rollback on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
        error_log("Transaction rolled back due to error");
    }
    
    error_log("Save batch error: " . $e->getMessage());
    
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to add batch: ' . $e->getMessage()
    ]);
}

error_log("=== SAVE BATCH REQUEST END ===");
?>