<?php
session_start();
include_once "../config/database.php";

if(!isset($_SESSION['user_id'])){
    header("Location: /beauty_pos/login.php");
    exit;
}

if(!isset($_GET['id']) || !is_numeric($_GET['id'])){
    header("Location: /beauty_pos/brands/index.php");
    exit;
}

$id = (int)$_GET['id'];

/* ---------- CHECK BRAND ---------- */

$brand = mysqli_query($conn,"
SELECT id
FROM brands
WHERE id='$id'
");

if(mysqli_num_rows($brand)==0){
    header("Location: /beauty_pos/brands/index.php");
    exit;
}

/* ---------- CHECK USED IN PRODUCTS ---------- */

$check = mysqli_query($conn,"
SELECT id
FROM products
WHERE brand_id='$id'
LIMIT 1
");

if(mysqli_num_rows($check)>0){

    header("Location: /beauty_pos/brands/index.php?error=used");
    exit;

}

/* ---------- DELETE ---------- */

$delete = mysqli_query($conn,"
DELETE FROM brands
WHERE id='$id'
");

if($delete){

    header("Location: /beauty_pos/brands/index.php?success=deleted");
    exit;

}else{

    header("Location: /beauty_pos/brands/index.php?error=delete");
    exit;

}
?>