<?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;
}

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

if ($id <= 0) {
    die('Invalid category ID.');
}

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

/*
    Check duplicate category excluding current record
*/
$stmt = $db->prepare("
    SELECT COUNT(*)
    FROM categories
    WHERE name = ?
    AND id != ?
");

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

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

/*
    Update category
*/
$stmt = $db->prepare("
    UPDATE categories
    SET name = ?
    WHERE id = ?
");

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

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