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

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

// Check admin access
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    // Validate input
    if (empty($_POST['section']) || empty($_POST['description']) || !isset($_POST['amount'])) {
        throw new Exception('Missing required fields');
    }

    // Insert entry
    $stmt = $pdo->prepare("
        INSERT INTO accounting_templates 
            (section, description, amount, category, is_active) 
        VALUES 
            (?, ?, ?, 'custom', 1)
    ");

    $success = $stmt->execute([
        $_POST['section'],
        $_POST['description'],
        $_POST['amount']
    ]);

    if ($success) {
        echo json_encode(['success' => true]);
    } else {
        throw new Exception('Failed to save entry');
    }

} catch (Exception $e) {
    error_log("Accounting Entry Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}