<?php
/**
 * Expense Approval AJAX Handler
 * Handles approve/reject actions for expenses
 */

// Start session to access session variables
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Start output buffering to catch any unwanted output
ob_start();

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

try {
    include '../db.php';
    include '../includes/tax_helpers.php';
    include '../financial_helpers.php';
    include '../journal_entry_handler.php';
    
    // Clear any output that might have been generated
    ob_clean();
} catch (Exception $e) {
    ob_clean();
    echo json_encode(['success' => false, 'message' => 'System error: ' . $e->getMessage()]);
    exit;
}

// Simple authentication check - just verify user is logged in
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

$action = $_POST['action'] ?? '';
$expense_id = intval($_POST['expense_id'] ?? 0);

if (!$expense_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid expense ID']);
    exit;
}

try {
    // Get expense details
    $stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ?");
    $stmt->bind_param("i", $expense_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if (!$expense = $result->fetch_assoc()) {
        echo json_encode(['success' => false, 'message' => 'Expense not found']);
        exit;
    }
    
    if ($expense['status'] !== 'pending') {
        echo json_encode(['success' => false, 'message' => 'Expense is not pending approval']);
        exit;
    }
    
    $user_id = $_SESSION['user_id'];
    $current_time = date('Y-m-d H:i:s');
    
    if ($action === 'approve') {
        // Approve the expense
        $stmt = $conn->prepare("UPDATE expenses SET status = 'approved', approved_by = ?, approved_at = ? WHERE id = ?");
        $stmt->bind_param("isi", $user_id, $current_time, $expense_id);
        
        if ($stmt->execute()) {
            // Try to create journal entry if mapping exists
            $journal_entry_id = null;
            
            // Check if mapping columns exist
            $columns_exist = false;
            $result = mysqli_query($conn, "SHOW COLUMNS FROM expense_accounts LIKE 'chart_of_account_id'");
            if ($result && mysqli_num_rows($result) > 0) {
                $columns_exist = true;
            }
            
            if ($columns_exist) {
                // Try to create journal entry
                if (createExpenseJournalEntry($conn, $expense_id, $expense['amount'], $expense['account_id'], $expense['payment_method'], $_SESSION['store_id'] ?? 1, $expense['bank_account_id'])) {
                    // Get the journal entry ID
                    $stmt = mysqli_prepare($conn, "SELECT id FROM journal_entries WHERE source_type = 'expense' AND reference_id = ? ORDER BY created_at DESC LIMIT 1");
                    mysqli_stmt_bind_param($stmt, "i", $expense_id);
                    mysqli_stmt_execute($stmt);
                    $result = mysqli_stmt_get_result($stmt);
                    if ($row = mysqli_fetch_assoc($result)) {
                        $journal_entry_id = $row['id'];
                        
                        // Update expense with journal entry ID
                        $update_sql = "UPDATE expenses SET journal_entry_id = ? WHERE id = ?";
                        $stmt = mysqli_prepare($conn, $update_sql);
                        mysqli_stmt_bind_param($stmt, "ii", $journal_entry_id, $expense_id);
                        mysqli_stmt_execute($stmt);
                    }
                }
            }
            
            echo json_encode([
                'success' => true, 
                'message' => 'Expense approved successfully' . ($journal_entry_id ? ' and journal entry created' : '')
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to approve expense']);
        }
        
    } elseif ($action === 'reject') {
        $reason = mysqli_real_escape_string($conn, $_POST['reason'] ?? '');
        
        if (empty($reason)) {
            echo json_encode(['success' => false, 'message' => 'Rejection reason is required']);
            exit;
        }
        
        // Reject the expense
        $stmt = $conn->prepare("UPDATE expenses SET status = 'rejected', approved_by = ?, approved_at = ?, rejection_reason = ? WHERE id = ?");
        $stmt->bind_param("issi", $user_id, $current_time, $reason, $expense_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Expense rejected successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to reject expense']);
        }
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    ob_clean();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

// End output buffering and ensure clean JSON output
ob_end_flush();
?>
