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

admin_require_post_action('product_delete', 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, main_image, extra_image
        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);
    }

    $variantImages = [];
    $varStmt = $conn->prepare("
        SELECT variant_image
        FROM product_variants
        WHERE product_id = ?
    ");
    $varStmt->bind_param("i", $id);
    $varStmt->execute();
    $varRes = $varStmt->get_result();
    if ($varRes) {
        while ($row = $varRes->fetch_assoc()) {
            if (!empty($row['variant_image'])) {
                $variantImages[] = $row['variant_image'];
            }
        }
    }
    $varStmt->close();

    $conn->begin_transaction();

    $delLinks = $conn->prepare("DELETE FROM product_type_links WHERE product_id = ?");
    $delLinks->bind_param("i", $id);
    $delLinks->execute();
    $delLinks->close();

    $delVariants = $conn->prepare("DELETE FROM product_variants WHERE product_id = ?");
    $delVariants->bind_param("i", $id);
    $delVariants->execute();
    $delVariants->close();

    $delProduct = $conn->prepare("DELETE FROM products WHERE id = ?");
    $delProduct->bind_param("i", $id);
    $delProduct->execute();
    $delProduct->close();

    $conn->commit();

    $uploadDir = dirname(__DIR__) . '/uploads/products/';

    $filesToDelete = array_filter(array_merge(
        [$product['main_image'] ?? '', $product['extra_image'] ?? ''],
        $variantImages
    ));

    foreach ($filesToDelete as $file) {
        $filePath = $uploadDir . $file;
        if (is_file($filePath)) {
            @unlink($filePath);
        }
    }

    $_SESSION['success_message'] = 'تم حذف المنتج وكل الفاريانتات المرتبطة به بنجاح.';
    admin_log_activity('product.delete', 'حذف منتج', 'تم حذف المنتج وكل الفاريانتات المرتبطة به.', 'product', $id, [], true);
    redirect_to($back);

} catch (Throwable $e) {
    if ($conn->errno || method_exists($conn, 'rollback')) {
        try {
            $conn->rollback();
        } catch (Throwable $rollbackError) {
        }
    }

    $_SESSION['product_form_errors'] = ['خطأ أثناء حذف المنتج: ' . $e->getMessage()];
    redirect_to($back);
}