<?php
session_start();
require_once '../config/db.php';

header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    if (!isset($_SESSION['username'])) {
        throw new Exception('User not logged in');
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    if (empty($_POST['category_name'])) {
        throw new Exception('Category name is required');
    }

    $category_name = strtoupper(trim($_POST['category_name']));
    
    // Validate category name
    if (strlen($category_name) < 2) {
        throw new Exception('Category name must be at least 2 characters long');
    }
    
    // Check if category exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM categories WHERE category_name = ?");
    $stmt->execute([$category_name]);
    if ($stmt->fetchColumn() > 0) {
        throw new Exception('Category already exists');
    }
    
    // Insert new category
    $stmt = $pdo->prepare("INSERT INTO categories (category_name) VALUES (?)");
    $stmt->execute([$category_name]);
    
    // Log the action
    $username = $_SESSION['username'];
    $stmt = $pdo->prepare("INSERT INTO transactions (username, activity_type, activity_details) 
                          VALUES (?, 'Add Category', ?)");
    $stmt->execute([$username, "Added new category: $category_name"]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Category added successfully'
    ]);

} catch (Exception $e) {
    error_log($e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    error_log($e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}