<?php
require_once 'functions.php';
checkLogin();
$conn = connect();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $type = $_POST['transaction_type'];
    $date = strtotime($_POST['date']);
    
    // Clean amount (remove /=, commas, spaces)
    $amount_raw = str_replace(['/=', ',', ' '], '', $_POST['amount']);
    $amount = (float)$amount_raw;
    
    $details = sanitize($conn, $_POST['details']);
    $cat_id = (int)$_POST['type_id'];
    $user_id = $_SESSION['log_id'];

    if ($type === 'DR') {
        // ... (Existing DR Logic) ...
        $entity = $_POST['entity'];
        $entity_parts = explode('_', $entity);
        $cust_id = ($entity_parts[0] == 'customer') ? (int)$entity_parts[1] : "NULL";
        $group_id = ($entity_parts[0] == 'group') ? (int)$entity_parts[1] : "NULL";
        $receipt = sanitize($conn, $_POST['ref_no']);

        $sql = "INSERT INTO incomes (inc_date, inctype_id, cust_id, group_id, inc_amount, inc_receipt, inc_text, user_id) 
                VALUES ('$date', '$cat_id', $cust_id, $group_id, '$amount', '$receipt', '$details', '$user_id')";
        
        mysqli_query($conn, $sql) or die(mysqli_error($conn));
        header("Location: finance.php?view=cashins");
    }
    elseif ($type === 'CR') {
        // ... (Updated CR Logic) ...
        $voucher = sanitize($conn, $_POST['ref_no']);
        
        // Note: You might want to save 'Prepared by' into 'exp_recipient' or a new column
        // For now, I'll append it to details if no specific column exists
        $prepared = sanitize($conn, $_POST['prepared_by']);
        if(!empty($prepared)) $details .= " (Prep: $prepared)";
        
        // Receipt No for Expenses (if any)
        $receipt_no = sanitize($conn, $_POST['receipt_no']);
        if(!empty($receipt_no)) $details .= " (Rcpt: $receipt_no)";

        $sql = "INSERT INTO expenses (exp_date, exptype_id, exp_amount, exp_voucher, exp_text, user_id) 
                VALUES ('$date', '$cat_id', '$amount', '$voucher', '$details', '$user_id')";

        mysqli_query($conn, $sql) or die(mysqli_error($conn));
        header("Location: finance.php?view=cashouts");
    }
}
?>