<?php
/**
 * Expense Categories Process Handler
 * 
 * Handles all add, edit, delete operations for expense categories
 */
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user ID for tracking
$user_id = $_SESSION['user_id'];

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method";
    header('Location: expense_categories.php');
    exit();
}

// Get action from form
$action = $_POST['action'] ?? '';

// Process based on action
switch ($action) {
    case 'add':
        addCategory($conn, $user_id);
        break;
    case 'edit':
        editCategory($conn, $user_id);
        break;
    case 'delete':
        deleteCategory($conn);
        break;
    default:
        $_SESSION['error_message'] = "Invalid action specified";
        header('Location: expense_categories.php');
        exit();
}

/**
 * Add a new expense category
 */
function addCategory($conn, $user_id) {
    // Get form data
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $type = $_POST['type'] ?? 'Office';
    $status = $_POST['status'] ?? 'Active';
    
    // Validate data
    if (empty($name)) {
        $_SESSION['error_message'] = "Category name is required";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Check if category already exists
    $check_sql = "SELECT * FROM expense_categories WHERE name = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("s", $name);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        $_SESSION['error_message'] = "A category with that name already exists";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Insert the new category
    try {
        $sql = "INSERT INTO expense_categories (name, description, type, status, created_by) 
                VALUES (?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssi", $name, $description, $type, $status, $user_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Expense category added successfully";
        } else {
            throw new Exception("Error adding category: " . $stmt->error);
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
    
    header('Location: expense_categories.php');
    exit();
}

/**
 * Edit an existing expense category
 */
function editCategory($conn, $user_id) {
    // Get form data
    $category_id = intval($_POST['category_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $type = $_POST['type'] ?? 'Office';
    $status = $_POST['status'] ?? 'Active';
    
    // Validate data
    if ($category_id <= 0) {
        $_SESSION['error_message'] = "Invalid category ID";
        header('Location: expense_categories.php');
        exit();
    }
    
    if (empty($name)) {
        $_SESSION['error_message'] = "Category name is required";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Check if category exists
    $check_sql = "SELECT * FROM expense_categories WHERE category_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $category_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        $_SESSION['error_message'] = "Category not found";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Check if name already exists for a different category
    $name_check_sql = "SELECT * FROM expense_categories WHERE name = ? AND category_id != ?";
    $name_check_stmt = $conn->prepare($name_check_sql);
    $name_check_stmt->bind_param("si", $name, $category_id);
    $name_check_stmt->execute();
    $name_check_result = $name_check_stmt->get_result();
    
    if ($name_check_result->num_rows > 0) {
        $_SESSION['error_message'] = "Another category with that name already exists";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Update the category
    try {
        $sql = "UPDATE expense_categories 
                SET name = ?, description = ?, type = ?, status = ? 
                WHERE category_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssi", $name, $description, $type, $status, $category_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Expense category updated successfully";
        } else {
            throw new Exception("Error updating category: " . $stmt->error);
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
    
    header('Location: expense_categories.php');
    exit();
}

/**
 * Delete an expense category
 */
function deleteCategory($conn) {
    // Get category ID
    $category_id = intval($_POST['category_id'] ?? 0);
    
    // Validate data
    if ($category_id <= 0) {
        $_SESSION['error_message'] = "Invalid category ID";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Check if category exists
    $check_sql = "SELECT * FROM expense_categories WHERE category_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $category_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        $_SESSION['error_message'] = "Category not found";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Check if the category is in use
    $usage_check_sql = "SELECT COUNT(*) as count FROM expenses WHERE category_id = ?";
    $usage_check_stmt = $conn->prepare($usage_check_sql);
    $usage_check_stmt->bind_param("i", $category_id);
    $usage_check_stmt->execute();
    $usage_result = $usage_check_stmt->get_result();
    $usage_count = $usage_result->fetch_assoc()['count'];
    
    if ($usage_count > 0) {
        $_SESSION['error_message'] = "Cannot delete category because it is being used by {$usage_count} expenses. Set it to inactive instead.";
        header('Location: expense_categories.php');
        exit();
    }
    
    // Delete the category
    try {
        $sql = "DELETE FROM expense_categories WHERE category_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $category_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Expense category deleted successfully";
        } else {
            throw new Exception("Error deleting category: " . $stmt->error);
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
    
    header('Location: expense_categories.php');
    exit();
}
?>