<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'RegistrationLogger.php';

// Require admin login
requirePermission('registrations', 'view');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    $action = $input['action'] ?? '';
    $registrationId = $input['registration_id'] ?? '';
    $registrationNumber = $input['registration_number'] ?? '';
    
    if (empty($action) || empty($registrationId)) {
        throw new Exception('Missing required parameters');
    }
    
    $pdo = getDBConnection();
    $logger = new RegistrationLogger($pdo, $_SESSION['admin_user'] ?? null);
    
    switch ($action) {
        case 'print_details':
            $logger->logDataExport($registrationId, $registrationNumber, 'registration_details', 'print');
            break;
            
        case 'copy_invoice_url':
            $logger->logInvoiceGeneration($registrationId, $registrationNumber, 'public_url_copy');
            break;
            
        case 'view_invoice':
            $logger->logInvoiceGeneration($registrationId, $registrationNumber, 'admin_view');
            break;
            
        case 'view_public_invoice':
            $logger->logInvoiceGeneration($registrationId, $registrationNumber, 'public_view');
            break;
            
        default:
            throw new Exception('Unknown action: ' . $action);
    }
    
    echo json_encode(['success' => true]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
