<?php
session_start();

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

include_once "../config/database.php";

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

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

/* Check Category */

$check=mysqli_query($conn,"SELECT * FROM categories WHERE id='$id'");

if(mysqli_num_rows($check)==0){
    header("Location:index.php");
    exit();
}

/* Check Products */

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

if(mysqli_num_rows($productCheck)>0){

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

}

/* Delete */

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

if($delete){

    header("Location:index.php?deleted=1");
    exit();

}else{

    header("Location:index.php?error=1");
    exit();

}
?>