<?php
// Load only the database, helpers, and auth – no HTML yet
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

$id = $_GET['id'] ?? null;
if ($id) {
    // Fetch brand to get logo URL
    $stmt = $pdo->prepare("SELECT logo_url FROM brands WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $brand = $stmt->fetch();

    if ($brand) {
        // Delete the brand record
        $pdo->prepare("DELETE FROM brands WHERE id = :id")->execute([':id' => $id]);

        // Delete logo file if exists
        if (!empty($brand['logo_url'])) {
            $logoPath = $brand['logo_url'];

            // If it's a full URL, extract the filename; otherwise treat as simple filename
            if (filter_var($logoPath, FILTER_VALIDATE_URL)) {
                $filename = basename(parse_url($logoPath, PHP_URL_PATH));
            } else {
                $filename = $logoPath;
            }

            if (!empty($filename)) {
                deleteFile('../assets/uploads/' . $filename);
            }
        }

        setFlash('success', 'Brand deleted.');
    } else {
        setFlash('danger', 'Brand not found.');
    }
} else {
    setFlash('danger', 'Invalid request.');
}

// Now redirect – no output has been sent yet, so this will always work
header('Location: brands.php');
exit;