<?php
// Suppress any error output that could break JSON
error_reporting(0);
ini_set('display_errors', 0);

session_start();
include '../db.php';

// Simple session check instead of complex permission system
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

// Check if the new 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;
}

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

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

// Function definitions
function add_expense_account($conn, $columns_exist) {
    $account_name = trim($_POST['account_name'] ?? '');
    $category_id = intval($_POST['category_id'] ?? 0);
    $subcategory_id = intval($_POST['subcategory_id'] ?? 0);
    $chart_of_account_id = !empty($_POST['chart_of_account_id']) ? intval($_POST['chart_of_account_id']) : null;
    
    // Validate required fields
    if (empty($account_name)) {
        echo json_encode(['success' => false, 'message' => 'Account name is required']);
        return;
    }
    
    if ($category_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Valid category is required']);
        return;
    }
    
    if ($subcategory_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Valid subcategory is required']);
        return;
    }
    
    // Check for duplicate account name
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_accounts WHERE name = ?");
    mysqli_stmt_bind_param($stmt, "s", $account_name);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) > 0) {
        echo json_encode(['success' => false, 'message' => 'An expense account with this name already exists']);
        return;
    }
    
    // Verify category and subcategory exist
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_categories WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $category_id);
    mysqli_stmt_execute($stmt);
    if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Selected category does not exist']);
        return;
    }
    
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_subcategories WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $subcategory_id);
    mysqli_stmt_execute($stmt);
    if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Selected subcategory does not exist']);
        return;
    }
    
    // If chart_of_account_id provided, verify it's a valid expense account
    if ($chart_of_account_id && $columns_exist) {
        $stmt = mysqli_prepare($conn, "SELECT id FROM chart_of_accounts WHERE id = ? AND account_type = 'expense' AND is_active = 1");
        mysqli_stmt_bind_param($stmt, "i", $chart_of_account_id);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
            echo json_encode(['success' => false, 'message' => 'Selected chart of account is not a valid active expense account']);
            return;
        }
    }
    
    // Insert the expense account
    if ($columns_exist && $chart_of_account_id) {
        $stmt = mysqli_prepare($conn, "INSERT INTO expense_accounts (name, chart_of_account_id, category_id, subcategory_id, mapped_at, mapped_by) VALUES (?, ?, ?, ?, NOW(), ?)");
        $user_id = $_SESSION['user_id'] ?? 0;
        mysqli_stmt_bind_param($stmt, "siiii", $account_name, $chart_of_account_id, $category_id, $subcategory_id, $user_id);
    } else {
        $stmt = mysqli_prepare($conn, "INSERT INTO expense_accounts (name, category_id, subcategory_id) VALUES (?, ?, ?)");
        mysqli_stmt_bind_param($stmt, "sii", $account_name, $category_id, $subcategory_id);
    }
    
    if (mysqli_stmt_execute($stmt)) {
        $message = 'Expense account added successfully';
        if ($chart_of_account_id && $columns_exist) {
            $message .= ' and mapped to chart of account';
        }
        echo json_encode(['success' => true, 'message' => $message]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add expense account: ' . mysqli_error($conn)]);
    }
}

function update_expense_account($conn, $columns_exist) {
    $account_id = intval($_POST['account_id'] ?? 0);
    $account_name = trim($_POST['account_name'] ?? '');
    $category_id = intval($_POST['category_id'] ?? 0);
    $subcategory_id = intval($_POST['subcategory_id'] ?? 0);
    $chart_of_account_id = !empty($_POST['chart_of_account_id']) ? intval($_POST['chart_of_account_id']) : null;
    
    // Validate required fields
    if ($account_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Valid account ID is required']);
        return;
    }
    
    if (empty($account_name)) {
        echo json_encode(['success' => false, 'message' => 'Account name is required']);
        return;
    }
    
    if ($category_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Valid category is required']);
        return;
    }
    
    if ($subcategory_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Valid subcategory is required']);
        return;
    }
    
    // Check if account exists
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_accounts WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $account_id);
    mysqli_stmt_execute($stmt);
    if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Expense account not found']);
        return;
    }
    
    // Check for duplicate account name (excluding current account)
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_accounts WHERE name = ? AND id != ?");
    mysqli_stmt_bind_param($stmt, "si", $account_name, $account_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) > 0) {
        echo json_encode(['success' => false, 'message' => 'An expense account with this name already exists']);
        return;
    }
    
    // Verify category and subcategory exist
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_categories WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $category_id);
    mysqli_stmt_execute($stmt);
    if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Selected category does not exist']);
        return;
    }
    
    $stmt = mysqli_prepare($conn, "SELECT id FROM expense_subcategories WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $subcategory_id);
    mysqli_stmt_execute($stmt);
    if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Selected subcategory does not exist']);
        return;
    }
    
    // If chart_of_account_id provided, verify it's a valid expense account
    if ($chart_of_account_id && $columns_exist) {
        $stmt = mysqli_prepare($conn, "SELECT id FROM chart_of_accounts WHERE id = ? AND account_type = 'expense' AND is_active = 1");
        mysqli_stmt_bind_param($stmt, "i", $chart_of_account_id);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows == 0) {
            echo json_encode(['success' => false, 'message' => 'Selected chart of account is not a valid active expense account']);
            return;
        }
    }
    
    // Update the expense account
    if ($columns_exist) {
        $stmt = mysqli_prepare($conn, "UPDATE expense_accounts SET name = ?, category_id = ?, subcategory_id = ?, chart_of_account_id = ?, mapped_at = NOW(), mapped_by = ? WHERE id = ?");
        $user_id = $_SESSION['user_id'] ?? 0;
        mysqli_stmt_bind_param($stmt, "siiiii", $account_name, $category_id, $subcategory_id, $chart_of_account_id, $user_id, $account_id);
    } else {
        $stmt = mysqli_prepare($conn, "UPDATE expense_accounts SET name = ?, category_id = ?, subcategory_id = ? WHERE id = ?");
        mysqli_stmt_bind_param($stmt, "siii", $account_name, $category_id, $subcategory_id, $account_id);
    }
    
    if (mysqli_stmt_execute($stmt)) {
        $message = 'Expense account updated successfully';
        if ($chart_of_account_id && $columns_exist) {
            $message .= ' and mapped to chart of account';
        } elseif ($columns_exist) {
            $message .= ' (mapping removed)';
        }
        echo json_encode(['success' => true, 'message' => $message]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update expense account: ' . mysqli_error($conn)]);
    }
}

$action = $_POST['action'] ?? '';

switch ($action) {
    case 'add_expense_account':
        add_expense_account($conn, $columns_exist);
        break;
        
    case 'update_expense_account':
        update_expense_account($conn, $columns_exist);
        break;
        
    case 'map_account':
        if (!$columns_exist) {
            echo json_encode(['success' => false, 'message' => 'Database columns not added yet. Please run the SQL queries first.']);
            exit;
        }
        
        $expense_account_id = $_POST['expense_account_id'] ?? 0;
        $chart_of_account_id = $_POST['chart_of_account_id'] ?? 0;
        
        if (!$expense_account_id || !$chart_of_account_id) {
            echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
            exit;
        }
        
        // Verify expense account exists
        $stmt = $conn->prepare("SELECT id, name FROM expense_accounts WHERE id = ?");
        $stmt->bind_param("i", $expense_account_id);
        $stmt->execute();
        $expense_account = $stmt->get_result()->fetch_assoc();
        
        if (!$expense_account) {
            echo json_encode(['success' => false, 'message' => 'Expense account not found']);
            exit;
        }
        
        // Verify chart of account exists and is an expense account
        $stmt = $conn->prepare("SELECT id, account_code, account_name, account_type FROM chart_of_accounts WHERE id = ? AND account_type = 'expense' AND is_active = 1");
        $stmt->bind_param("i", $chart_of_account_id);
        $stmt->execute();
        $chart_account = $stmt->get_result()->fetch_assoc();
        
        if (!$chart_account) {
            echo json_encode(['success' => false, 'message' => 'Invalid chart of account selected. Please select an expense account.']);
            exit;
        }
        
        // Update the mapping
        $stmt = $conn->prepare("UPDATE expense_accounts SET chart_of_account_id = ?, mapped_at = CURRENT_TIMESTAMP, mapped_by = ? WHERE id = ?");
        $user_id = $_SESSION['user_id'] ?? 1;
        $stmt->bind_param("iii", $chart_of_account_id, $user_id, $expense_account_id);
        
        if ($stmt->execute()) {
            echo json_encode([
                'success' => true, 
                'message' => 'Expense account mapped successfully!',
                'data' => [
                    'expense_account_name' => $expense_account['name'],
                    'chart_account_code' => $chart_account['account_code'],
                    'chart_account_name' => $chart_account['account_name']
                ]
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error updating mapping: ' . $conn->error]);
        }
        break;
        
    case 'unmap_account':
        if (!$columns_exist) {
            echo json_encode(['success' => false, 'message' => 'Database columns not added yet. Please run the SQL queries first.']);
            exit;
        }
        
        $expense_account_id = $_POST['expense_account_id'] ?? 0;
        
        if (!$expense_account_id) {
            echo json_encode(['success' => false, 'message' => 'Missing expense account ID']);
            exit;
        }
        
        // Remove the mapping
        $stmt = $conn->prepare("UPDATE expense_accounts SET chart_of_account_id = NULL, mapped_at = NULL, mapped_by = NULL WHERE id = ?");
        $stmt->bind_param("i", $expense_account_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Mapping removed successfully!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error removing mapping: ' . $conn->error]);
        }
        break;
        
    case 'get_expense_accounts':
        if ($columns_exist) {
            // Get all expense accounts with their mapping status
            $stmt = $conn->prepare("
                SELECT 
                    ea.id,
                    ea.name,
                    ea.category_id,
                    ea.subcategory_id,
                    ea.chart_of_account_id,
                    ea.mapped_at,
                    ec.name as category_name,
                    esc.name as subcategory_name,
                    coa.account_code,
                    coa.account_name as chart_account_name
                FROM expense_accounts ea
                LEFT JOIN expense_categories ec ON ea.category_id = ec.id
                LEFT JOIN expense_subcategories esc ON ea.subcategory_id = esc.id
                LEFT JOIN chart_of_accounts coa ON ea.chart_of_account_id = coa.id
                ORDER BY ea.name
            ");
            $stmt->execute();
            $accounts = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        } else {
            // Fallback without mapping columns
            $stmt = $conn->prepare("
                SELECT 
                    ea.id,
                    ea.name,
                    ea.category_id,
                    ea.subcategory_id,
                    NULL as chart_of_account_id,
                    NULL as mapped_at,
                    ec.name as category_name,
                    esc.name as subcategory_name,
                    NULL as account_code,
                    NULL as chart_account_name
                FROM expense_accounts ea
                LEFT JOIN expense_categories ec ON ea.category_id = ec.id
                LEFT JOIN expense_subcategories esc ON ea.subcategory_id = esc.id
                ORDER BY ea.name
            ");
            $stmt->execute();
            $accounts = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        }
        
        echo json_encode(['success' => true, 'data' => $accounts]);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
?>
