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

admin_require_post_action('brand_delete', admin_url('brands/index.php'));

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
    redirect_to(admin_url('brands/index.php?msg=notfound'));
}

$res = $conn->query("SELECT * FROM brands WHERE id = {$id} LIMIT 1");
if (!$res || $res->num_rows === 0) {
    redirect_to(admin_url('brands/index.php?msg=notfound'));
}

$row = $res->fetch_assoc();
$brandNameEsc = $conn->real_escape_string($row['name']);

$checkProducts = $conn->query("SELECT COUNT(*) AS total FROM products WHERE brand_part = '{$brandNameEsc}'");
$productsCount = 0;
if ($checkProducts) {
    $productsCount = (int)$checkProducts->fetch_assoc()['total'];
}

if ($productsCount > 0) {
    redirect_to(admin_url('brands/index.php?msg=blocked'));
}

if (!empty($row['image']) && file_exists('../uploads/' . $row['image'])) {
    @unlink('../uploads/' . $row['image']);
}

$conn->query("DELETE FROM brands WHERE id = {$id} LIMIT 1");
admin_log_activity('brand.delete', 'حذف براند', 'تم حذف براند من لوحة التحكم.', 'brand', $id, ['name' => (string)($row['name'] ?? '')], true);
redirect_to(admin_url('brands/index.php?msg=deleted'));
