<?php
// ajax/adjust_stock.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../assets/db_connect.php';

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

if (!isset($_SESSION['user']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$batch_id = $_POST['batch_id'] ?? 0;
$adjustment_type = $_POST['adjustment_type'] ?? '';
$quantity = intval($_POST['quantity'] ?? 0);
$reason = trim($_POST['reason'] ?? '');

if ($batch_id <= 0 || $quantity <= 0 || empty($adjustment_type) || empty($reason)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid parameters']);
    exit;
}

try {
    // Get batch details
    $stmt = $pdo->prepare("SELECT pb.*, p.name as product_name FROM product_batches pb 
                          JOIN products p ON pb.product_id = p.id WHERE pb.id = ?");
    $stmt->execute([$batch_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$batch) {
        echo json_encode(['status' => 'error', 'message' => 'Batch not found']);
        exit;
    }
    
    // Calculate new quantity based on adjustment type
    $current_qty = $batch['qty'];
    $change_qty = 0;
    
    switch ($adjustment_type) {
        case 'ADD':
            $change_qty = $quantity;
            $new_qty = $current_qty + $quantity;
            break;
        case 'REMOVE':
            $change_qty = -$quantity;
            $new_qty = max(0, $current_qty - $quantity);
            break;
        case 'SET':
            $change_qty = $quantity - $current_qty;
            $new_qty = $quantity;
            break;
        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid adjustment type']);
            exit;
    }
    
    // Update batch quantity
    $stmt = $pdo->prepare("UPDATE product_batches SET qty = ? WHERE id = ?");
    $stmt->execute([$new_qty, $batch_id]);
    
    // Create inventory movement record
    $stmt = $pdo->prepare("
        INSERT INTO inventory_movements 
        (product_id, batch_id, change_qty, movement_type, note, created_by, shop_id)
        VALUES (?, ?, ?, 'ADJUSTMENT', ?, ?, ?)
    ");
    $stmt->execute([
        $batch['product_id'],
        $batch_id,
        $change_qty,
        "Stock adjustment: $reason",
        $_SESSION['user']['id'],
        $batch['shop_id']
    ]);
    
    echo json_encode([
        'status' => 'success', 
        'message' => "Stock adjusted successfully. New quantity: $new_qty",
        'new_qty' => $new_qty
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error', 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>