<?php
/**
 * Finance Integration Examples
 * 
 * This file demonstrates how to integrate the Finance Service hooks
 * into existing Invoicing (Accounts Receivable) and Expenditure (Accounts Payable) modules.
 */

// Include the Finance Service
require_once __DIR__ . '/finance_service.php';

/**
 * ============================================
 * EXAMPLE 1: Invoicing Module Integration
 * ============================================
 * 
 * When an invoice is marked as paid, call recordIncome()
 */

/**
 * Example: Process invoice payment and record income
 * 
 * @param int $invoiceId - The invoice ID
 * @param int $bankAccountId - Bank account to receive payment
 * @param float $amount - Payment amount
 * @param array $paymentData - Additional payment details
 * @return array Result of the operation
 */
function processInvoicePayment($invoiceId, $bankAccountId, $amount, $paymentData = []) {
    // Step 1: Include Finance Service
    $financeService = new FinanceService();
    
    // Step 2: Prepare extra data for the transaction
    $extraData = [
        'customer_id' => $paymentData['customer_id'] ?? null,
        'customer_name' => $paymentData['customer_name'] ?? 'Unknown Customer',
        'account_head' => 'Sales Revenue',
        'payment_mode' => $paymentData['payment_mode'] ?? 'Bank Transfer',
        'narration' => 'Invoice payment received - Invoice #' . $invoiceId . 
                       ($paymentData['notes'] ? ' - ' . $paymentData['notes'] : ''),
        'document_reference' => 'INV-' . $invoiceId,
        'cost_center' => $paymentData['cost_center'] ?? 'Sales',
        'entered_by' => $_SESSION['user_id'] ?? null,
        'transaction_date' => $paymentData['payment_date'] ?? date('Y-m-d')
    ];
    
    // Step 3: Call recordIncome() to create Receipt transaction
    $result = $financeService->recordIncome($invoiceId, $bankAccountId, $amount, $extraData);
    
    if ($result['success']) {
        // Step 4: Update invoice status in your invoice table
        // $mysqli->query("UPDATE invoices SET status='paid', payment_voucher='{$result['voucher_number']}' WHERE id=$invoiceId");
        
        // Log the successful integration
        error_log("Invoice #$invoiceId payment recorded. Voucher: {$result['voucher_number']}, Transaction ID: {$result['transaction_id']}");
    }
    
    return $result;
}


/**
 * Example: Process multiple partial payments on an invoice
 */
function processPartialInvoicePayment($invoiceId, $bankAccountId, $amount, $totalInvoiceAmount, $paymentData = []) {
    $financeService = new FinanceService();
    
    // Determine if this is final payment
    $isFinalPayment = ($paymentData['cumulative_paid'] + $amount) >= $totalInvoiceAmount;
    
    $extraData = [
        'customer_id' => $paymentData['customer_id'] ?? null,
        'customer_name' => $paymentData['customer_name'] ?? 'Unknown Customer',
        'account_head' => 'Sales Revenue',
        'payment_mode' => $paymentData['payment_mode'] ?? 'Bank Transfer',
        'narration' => ($isFinalPayment ? 'Final payment' : 'Partial payment') . 
                       ' for Invoice #' . $invoiceId .
                       ' (Paid: ' . number_format($paymentData['cumulative_paid'] + $amount, 2) . 
                       ' / ' . number_format($totalInvoiceAmount, 2) . ')',
        'document_reference' => 'INV-' . $invoiceId . '-PARTIAL',
        'cost_center' => $paymentData['cost_center'] ?? 'Sales',
        'entered_by' => $_SESSION['user_id'] ?? null,
        'transaction_date' => $paymentData['payment_date'] ?? date('Y-m-d')
    ];
    
    return $financeService->recordIncome($invoiceId, $bankAccountId, $amount, $extraData);
}


/**
 * ============================================
 * EXAMPLE 2: Expenditure Module Integration
 * ============================================
 * 
 * When an expenditure is recorded, call recordExpense()
 */

/**
 * Example: Process expense payment
 * 
 * @param int $expenseId - The expense/expenditure ID
 * @param int $bankAccountId - Bank account to deduct from
 * @param float $amount - Expense amount
 * @param array $expenseData - Additional expense details
 * @return array Result of the operation
 */
function processExpensePayment($expenseId, $bankAccountId, $amount, $expenseData = []) {
    // Step 1: Include Finance Service
    $financeService = new FinanceService();
    
    // Step 2: Map expense category to account head
    $accountHeadMap = [
        'salary' => 'Salary & Wages',
        'rent' => 'Rent Expense',
        'utilities' => 'Utilities',
        'transport' => 'Transportation',
        'office' => 'Office Supplies',
        'marketing' => 'Marketing',
        'maintenance' => 'Maintenance',
        'purchase' => 'Purchase Expenses',
        'other' => 'Other Expenses'
    ];
    
    $category = $expenseData['category'] ?? 'other';
    $accountHead = $accountHeadMap[$category] ?? 'Other Expenses';
    
    // Step 3: Prepare extra data for the transaction
    $extraData = [
        'supplier_id' => $expenseData['supplier_id'] ?? null,
        'supplier_name' => $expenseData['supplier_name'] ?? 'Unknown Supplier',
        'account_head' => $accountHead,
        'payment_mode' => $expenseData['payment_mode'] ?? 'Bank Transfer',
        'narration' => $expenseData['description'] ?? 'Expense payment - Expense #' . $expenseId,
        'document_reference' => 'EXP-' . $expenseId,
        'cost_center' => $expenseData['cost_center'] ?? 'Administration',
        'entered_by' => $_SESSION['user_id'] ?? null,
        'transaction_date' => $expenseData['expense_date'] ?? date('Y-m-d')
    ];
    
    // Step 4: Call recordExpense() to create Payment transaction
    $result = $financeService->recordExpense($expenseId, $bankAccountId, $amount, $extraData);
    
    if ($result['success']) {
        // Step 5: Update expense status in your expenditure table
        // $mysqli->query("UPDATE expenditures SET status='paid', payment_voucher='{$result['voucher_number']}' WHERE id=$expenseId");
        
        // Log the successful integration
        error_log("Expense #$expenseId payment recorded. Voucher: {$result['voucher_number']}, New Balance: {$result['new_balance']}");
    }
    
    return $result;
}


/**
 * Example: Process purchase order payment to supplier
 */
function processPurchaseOrderPayment($poId, $bankAccountId, $amount, $poData = []) {
    $financeService = new FinanceService();
    
    $extraData = [
        'supplier_id' => $poData['supplier_id'] ?? null,
        'supplier_name' => $poData['supplier_name'] ?? 'Unknown Supplier',
        'account_head' => 'Purchase Expenses',
        'payment_mode' => $poData['payment_mode'] ?? 'Bank Transfer',
        'narration' => 'PO Payment - Purchase Order #' . $poId . 
                       ' - ' . ($poData['description'] ?? 'Supplier payment'),
        'document_reference' => 'PO-' . $poId,
        'cost_center' => $poData['cost_center'] ?? 'Purchasing',
        'entered_by' => $_SESSION['user_id'] ?? null,
        'transaction_date' => $poData['payment_date'] ?? date('Y-m-d')
    ];
    
    return $financeService->recordExpense($poId, $bankAccountId, $amount, $extraData);
}


/**
 * ============================================
 * EXAMPLE 3: Batch Processing
 * ============================================
 */

/**
 * Process multiple invoice payments in batch
 */
function batchProcessInvoicePayments($payments) {
    $results = [];
    $successCount = 0;
    $failureCount = 0;
    
    foreach ($payments as $payment) {
        $result = processInvoicePayment(
            $payment['invoice_id'],
            $payment['bank_account_id'],
            $payment['amount'],
            $payment['extra_data'] ?? []
        );
        
        $results[] = $result;
        
        if ($result['success']) {
            $successCount++;
        } else {
            $failureCount++;
            error_log("Batch processing failed for Invoice #{$payment['invoice_id']}: {$result['message']}");
        }
    }
    
    return [
        'total' => count($payments),
        'successful' => $successCount,
        'failed' => $failureCount,
        'details' => $results
    ];
}


/**
 * ============================================
 * EXAMPLE 4: API Integration for AJAX Calls
 * ============================================
 */

/**
 * API endpoint handler for recording invoice payment via AJAX
 */
function handleInvoicePaymentAPI() {
    // This would be called from your api/invoices.php or similar
    
    $invoiceId = intval($_POST['invoice_id'] ?? 0);
    $bankAccountId = intval($_POST['bank_account_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    
    if (!$invoiceId || !$bankAccountId || $amount <= 0) {
        return ['success' => false, 'message' => 'Missing required fields'];
    }
    
    $paymentData = [
        'customer_id' => intval($_POST['customer_id'] ?? 0),
        'customer_name' => sanitize($_POST['customer_name'] ?? ''),
        'payment_mode' => sanitize($_POST['payment_mode'] ?? 'Bank Transfer'),
        'payment_date' => sanitize($_POST['payment_date'] ?? date('Y-m-d')),
        'notes' => sanitize($_POST['notes'] ?? ''),
        'cost_center' => sanitize($_POST['cost_center'] ?? 'Sales')
    ];
    
    return processInvoicePayment($invoiceId, $bankAccountId, $amount, $paymentData);
}


/**
 * API endpoint handler for recording expense payment via AJAX
 */
function handleExpensePaymentAPI() {
    $expenseId = intval($_POST['expense_id'] ?? 0);
    $bankAccountId = intval($_POST['bank_account_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    
    if (!$expenseId || !$bankAccountId || $amount <= 0) {
        return ['success' => false, 'message' => 'Missing required fields'];
    }
    
    $expenseData = [
        'supplier_id' => intval($_POST['supplier_id'] ?? 0),
        'supplier_name' => sanitize($_POST['supplier_name'] ?? ''),
        'category' => sanitize($_POST['category'] ?? 'other'),
        'payment_mode' => sanitize($_POST['payment_mode'] ?? 'Bank Transfer'),
        'expense_date' => sanitize($_POST['expense_date'] ?? date('Y-m-d')),
        'description' => sanitize($_POST['description'] ?? ''),
        'cost_center' => sanitize($_POST['cost_center'] ?? 'Administration')
    ];
    
    return processExpensePayment($expenseId, $bankAccountId, $amount, $expenseData);
}


/**
 * Helper function for sanitizing input
 */
function sanitize($input) {
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}


/**
 * ============================================
 * USAGE EXAMPLES IN EXISTING CODE
 * ============================================
 */

/*

// Example 1: In your existing invoice payment processing code
// File: api/invoices.php (when marking invoice as paid)

require_once __DIR__ . '/../includes/finance_service.php';

case 'record_payment':
    $invoiceId = intval($_POST['invoice_id']);
    $bankAccountId = intval($_POST['bank_account_id']);
    $amount = floatval($_POST['amount']);
    
    // Get invoice details from your existing query
    $invoice = getInvoiceDetails($invoiceId);
    
    // Call the finance service hook
    $result = processInvoicePayment($invoiceId, $bankAccountId, $amount, [
        'customer_id' => $invoice['customer_id'],
        'customer_name' => $invoice['customer_name'],
        'payment_mode' => $_POST['payment_mode'],
        'payment_date' => $_POST['payment_date'],
        'notes' => $_POST['notes']
    ]);
    
    if ($result['success']) {
        // Update your invoice record with the voucher number
        $mysqli->query("UPDATE invoices SET 
            status='paid', 
            payment_voucher='{$result['voucher_number']}',
            payment_transaction_id={$result['transaction_id']},
            paid_amount=$amount,
            paid_date=NOW()
            WHERE id=$invoiceId");
        
        json_response(['success' => true, 'data' => $result]);
    } else {
        json_response(['success' => false, 'message' => $result['message']], 400);
    }
    break;


// Example 2: In your existing expenditure processing code
// File: api/expenditures.php (when recording an expense)

require_once __DIR__ . '/../includes/finance_service.php';

case 'create_expense':
    // First, create the expense record in your existing table
    $expenseId = createExpenseRecord($_POST);
    
    if ($expenseId && !empty($_POST['bank_account_id'])) {
        // Auto-record the payment if bank account is specified
        $result = processExpensePayment($expenseId, $_POST['bank_account_id'], $_POST['amount'], [
            'supplier_id' => intval($_POST['supplier_id'] ?? 0),
            'supplier_name' => $_POST['supplier_name'],
            'category' => $_POST['expense_category'],
            'payment_mode' => $_POST['payment_mode'],
            'expense_date' => $_POST['expense_date'],
            'description' => $_POST['description']
        ]);
        
        if ($result['success']) {
            // Update expense with payment details
            $mysqli->query("UPDATE expenditures SET 
                payment_status='paid',
                payment_voucher='{$result['voucher_number']}',
                payment_transaction_id={$result['transaction_id']}
                WHERE id=$expenseId");
        }
    }
    
    json_response(['success' => true, 'expense_id' => $expenseId]);
    break;


// Example 3: Simple standalone usage

require_once __DIR__ . '/../includes/finance_service.php';

// Record a customer payment
$paymentResult = recordInvoiceIncome(
    $invoiceId = 123,
    $bankAccountId = 1,
    $amount = 50000.00,
    [
        'customer_name' => 'ABC Company',
        'payment_mode' => 'Bank Transfer',
        'narration' => 'Payment for granite slabs'
    ]
);

if ($paymentResult['success']) {
    echo "Payment recorded. Voucher: " . $paymentResult['voucher_number'];
}

// Record an expense payment
$expenseResult = recordExpensePayment(
    $expenseId = 456,
    $bankAccountId = 1,
    $amount = 25000.00,
    [
        'supplier_name' => 'XYZ Suppliers',
        'category' => 'purchase',
        'description' => 'Raw material purchase'
    ]
);

if ($expenseResult['success']) {
    echo "Expense recorded. Voucher: " . $expenseResult['voucher_number'];
    echo "New bank balance: " . $expenseResult['new_balance'];
}

*/
?>
