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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exit(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Begin transaction
    $pdo->beginTransaction();
    
    // Clear existing entries for the date
    $stmt = $pdo->prepare("DELETE FROM accounting_entries WHERE entry_date = ?");
    $stmt->execute([$data['date']]);
    
    // Prepare insert statement
    $stmt = $pdo->prepare("
        INSERT INTO accounting_entries 
        (section, description, amount, entry_type, entry_date) 
        VALUES (?, ?, ?, ?, ?)
    ");
    
    // Insert revenue entries
    foreach ($data['revenue'] as $entry) {
        $stmt->execute([
            'revenue',
            $entry['description'],
            $entry['amount'],
            'credit',
            $data['date']
        ]);
    }
    
    // Insert cost entries
    foreach ($data['costs'] as $entry) {
        $stmt->execute([
            'costs',
            $entry['description'],
            $entry['amount'],
            'debit',
            $data['date']
        ]);
    }
    
    // Insert expense entries
    foreach ($data['expenses'] as $entry) {
        $stmt->execute([
            'expenses',
            $entry['description'],
            $entry['amount'],
            'debit',
            $data['date']
        ]);
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode(['success' => true]);
    
} catch (Exception $e) {
    // Rollback on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Error saving entries: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error saving entries']);
}