<?php
/**
 * Generate eTIMS Invoice AJAX Endpoint
 * Generate invoice for premium, contribution, or service fee
 */

require_once __DIR__ . '/../layouts/main.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/ETIMSService.php';

requireLogin();
requirePermission('generate_etims_invoices');

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

$input = json_decode(file_get_contents('php://input'), true);
$source_type = $input['source_type'] ?? $_POST['source_type'] ?? '';
$source_id = $input['source_id'] ?? $_POST['source_id'] ?? null;

if (empty($source_type) || !$source_id) {
    echo json_encode([
        'success' => false,
        'message' => 'Source type and source ID are required'
    ]);
    exit();
}

$etimsService = new ETIMSService($conn);

switch ($source_type) {
    case 'PREMIUM':
        $result = $etimsService->generatePremiumInvoice($source_id);
        break;
        
    case 'CONTRIBUTION':
        $result = $etimsService->generateContributionInvoice($source_id);
        break;
        
    case 'SERVICE_FEE':
        $member_id = $input['member_id'] ?? null;
        $amount = $input['amount'] ?? null;
        $description = $input['description'] ?? 'Service Fee';
        $reference = $input['reference'] ?? null;
        
        if (!$member_id || !$amount) {
            echo json_encode([
                'success' => false,
                'message' => 'Member ID and amount are required for service fee'
            ]);
            exit();
        }
        
        $result = $etimsService->generateServiceFeeInvoice($member_id, $amount, $description, $reference);
        break;
        
    default:
        echo json_encode([
            'success' => false,
            'message' => 'Invalid source type'
        ]);
        exit();
}

// Log the action
$sql = "INSERT INTO audit_logs (
           event_type, event_category, user_id,
           event_description, performed_by, ip_address
       ) VALUES (?, ?, ?, ?, ?, ?)";

$event_type = 'ETIMS_INVOICE_GENERATED';
$event_category = 'ETIMS';
$description = "Generated eTIMS invoice for $source_type #$source_id";
$performed_by = $_SESSION['username'] ?? 'SYSTEM';
$ip_address = $_SERVER['REMOTE_ADDR'] ?? null;

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssisss", $event_type, $event_category, $_SESSION['user_id'], $description, $performed_by, $ip_address);
$stmt->execute();

echo json_encode($result);
