<?php
session_start(); // Start the session at the beginning of the script

// Check if company_id is set in the session
if (!isset($_SESSION['company_id'])) {
    // Redirect to login page or handle the error as needed
    die("Access denied. Please log in to access this page.");
}

// Include the database connection file
include('includes/dbconn.php');

// Retrieve POST data from the form submission
$accountId = $_POST['account_id'];
$companyId = $_SESSION['company_id']; // Retrieved from session
$amount = $_POST['amount'];
$type = $_POST['type'];
$date = $_POST['date'];
$description = $_POST['description'] ?? ''; // Fallback to an empty string if not set

// Prepare SQL statement to insert into the transactions table
$stmt = $conn->prepare("INSERT INTO transactions (company_id, account_id, amount, type, transaction_date, description) 
                        VALUES (?, ?, ?, ?, ?, ?)");

// Check if the prepare statement was successful
if ($stmt === false) {
    die("Error preparing statement: " . $conn->error);
}

// Bind parameters and execute the insert statement
$stmt->bind_param("iidsss", $companyId, $accountId, $amount, $type, $date, $description);
$stmt->execute();

// Check for errors in the transaction insert
if ($stmt->error) {
    echo "Error in transaction insert: " . $stmt->error;
} else {
    // If transaction type is 'Debit', it's an expense, so also insert into expenses table
    if ($type === 'Debit') {
        // Prepare SQL to insert into the expenses table
        $sqlExpense = "INSERT INTO expenses (user_id, expense_name, expense_date, capture_date, description, amount, category, company_id) 
                       VALUES (?, ?, ?, CURDATE(), ?, ?, 'General', ?)";
        $stmtExpense = $conn->prepare($sqlExpense);

        // Bind parameters for expenses insert
        $userId = $_SESSION['user_id']; // Assuming user_id is also stored in the session
        $expenseName = $description; // Using the transaction description as the expense name
        $stmtExpense->bind_param("isssdi", $userId, $expenseName, $date, $description, $amount, $companyId);
        $stmtExpense->execute();

        // Check for errors in the expense insert
        if ($stmtExpense->error) {
            echo "Error in expense insert: " . $stmtExpense->error;
        } else {
            echo "Expense recorded successfully.";
        }

        // Close the expenses statement
        $stmtExpense->close();
    }

    // Redirect to the chart of accounts page
    header("Location: coa.php");
    exit();
}

// Close the transaction statement and connection
$stmt->close();
$conn->close();
?>
