<?php
session_start();
require_once '../includes/auth.php';
require_once __DIR__ . '/stock_helpers.php';

function stock_redirect_back(string $fallback = 'list.php'): void {
    $back = $_POST['redirect'] ?? ($_SERVER['HTTP_REFERER'] ?? $fallback);
    header('Location: ' . $back);
    exit;
}
function stock_msg(string $type, string $message): void {
    $_SESSION['stock_' . $type] = $message;
}

$action = (string)($_POST['action'] ?? '');
$target = (string)($_POST['target'] ?? 'product');
$reasonCode = trim((string)($_POST['reason_code'] ?? 'manual_adjustment')) ?: 'manual_adjustment';
$notes = trim((string)($_POST['notes'] ?? ''));
$adminId = current_admin_id();

try {
    if ($action === 'bulk') {
        $bulkMode = (string)($_POST['bulk_mode'] ?? 'add');
        $bulkQty = (int)($_POST['bulk_qty'] ?? 0);
        $ids = $_POST['ids'] ?? [];
        if (!is_array($ids) || !$ids) {
            throw new RuntimeException('اختر عناصر أولاً للتعديل الجماعي.');
        }
        $conn->begin_transaction();
        $done = 0;
        foreach ($ids as $id) {
            $id = (int)$id;
            if ($id <= 0) {
                continue;
            }
            $row = nay_stock_fetch_target($conn, 'product', $id);
            if (!$row || ($row['managed_by'] ?? '') === 'variants') {
                continue;
            }
            nay_stock_apply_change($conn, 'product', $id, $bulkMode, $bulkQty, [
                'admin_id' => $adminId,
                'source' => 'admin_bulk',
                'reason_code' => $reasonCode,
                'notes' => $notes,
            ]);
            $done++;
        }
        $conn->commit();
        stock_msg('success', 'تم تنفيذ التعديل الجماعي على المخزون لعدد ' . $done . ' عنصر.');
        stock_redirect_back('stock_manage.php');
    }

    $id = (int)($_POST['id'] ?? 0);
    $qty = (int)($_POST['qty'] ?? 0);
    if ($id <= 0) {
        throw new RuntimeException('العنصر غير صالح.');
    }
    if (!in_array($target, ['product', 'variant'], true)) {
        throw new RuntimeException('نوع الهدف غير صالح.');
    }

    $conn->begin_transaction();
    $result = nay_stock_apply_change($conn, $target, $id, $action, $qty, [
        'admin_id' => $adminId,
        'source' => 'admin_quick',
        'reason_code' => $reasonCode,
        'notes' => $notes,
    ]);
    $conn->commit();

    $label = $target === 'variant' ? 'الفاريانت' : 'المنتج';
    stock_msg('success', 'تم تحديث مخزون ' . $label . ' بنجاح. (' . number_format((int)$result['before']) . ' ← ' . number_format((int)$result['after']) . ')');
    stock_redirect_back($target === 'variant' ? 'stock_manage.php' : 'inventory.php?product_id=' . $id);
} catch (Throwable $e) {
    if ($conn->errno) {
        $conn->rollback();
    }
    stock_msg('error', 'خطأ: ' . $e->getMessage());
    stock_redirect_back('stock_manage.php');
}
