<?php
require_once '../includes/auth.php';

admin_require_post_action('product_toggle', admin_url('products/list.php'));

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$back = (string)($_POST['back'] ?? admin_url('products/list.php'));
if (!str_starts_with($back, '/app/admin/products/')) {
    $back = admin_url('products/list.php');
}

if ($id <= 0) {
    $_SESSION['product_form_errors'] = ['معرّف المنتج غير صالح.'];
    redirect_to($back);
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $stmt = $conn->prepare("SELECT id, status FROM products WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $product = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!$product) {
        $_SESSION['product_form_errors'] = ['المنتج غير موجود.'];
        redirect_to($back);
    }

    $newStatus = ((int)$product['status'] === 1) ? 0 : 1;

    $update = $conn->prepare("UPDATE products SET status = ? WHERE id = ?");
    $update->bind_param("ii", $newStatus, $id);
    $update->execute();
    $update->close();

    $_SESSION['success_message'] = $newStatus === 1
        ? 'تم تفعيل المنتج بنجاح.'
        : 'تم إيقاف المنتج بنجاح.';

    admin_log_activity('product.toggle_status', 'تغيير حالة منتج', 'تم تغيير حالة المنتج.', 'product', $id, ['status' => $newStatus], true);
    redirect_to($back);

} catch (Throwable $e) {
    $_SESSION['product_form_errors'] = ['خطأ أثناء تحديث الحالة: ' . $e->getMessage()];
    redirect_to($back);
}