<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$name = trim($_POST['name'] ?? '');

if ($name === '') {
    die('Category name is required.');
}

/*
    Prevent duplicate category
*/
$stmt = $db->prepare("
    SELECT COUNT(*)
    FROM categories
    WHERE name = ?
");

$stmt->execute([$name]);

if ($stmt->fetchColumn() > 0) {
    die('Category already exists.');
}

/*
    Insert category
*/
$stmt = $db->prepare("
    INSERT INTO categories (name)
    VALUES (?)
");

$stmt->execute([$name]);

header('Location: index.php');
exit;
?>