<?php
namespace App\Controllers;

use App\Services\AuthService;
use App\Services\ExportService;
use App\Services\RbacService;
use App\Utils\Sanitizer;

class ExportController extends ApiController
{
    private ExportService $exportService;
    private AuthService $authService;
    private ?RbacService $rbacService;

    public function __construct(ExportService $exportService, AuthService $authService, ?RbacService $rbacService = null)
    {
        $this->exportService = $exportService;
        $this->authService = $authService;
        $this->rbacService = $rbacService;
    }

    public function catalog()
    {
        $isAdmin = $this->authService->isAdmin();
        $isAccountant = $this->authService->isAccountant();
        $hasRbacExportAccess = $this->rbacService ? ($this->rbacService->can('menu.exports') || $this->rbacService->can('export.catalog')) : false;

        if (!$isAdmin && !$isAccountant && !$hasRbacExportAccess) {
            $this->errorResponse('دسترسی محدود است');
        }

        $catalog = $this->exportService->getCatalog();
        
        if ($isAccountant && !$isAdmin) {
            // Filter catalog to only show payments
            $catalog['datasets'] = array_filter($catalog['datasets'], fn($d) => $d['id'] === 'payments');
            $catalog['datasets'] = array_values($catalog['datasets']);
        }

        if ($this->rbacService && !$isAdmin) {
            $catalog['datasets'] = array_values(array_filter($catalog['datasets'], function ($d) {
                $id = (string)($d['id'] ?? '');
                return $id !== '' && $this->rbacService->canExportDataset($id);
            }));
        }

        $this->successResponse($catalog);
    }

    public function run()
    {
        $isAdmin = $this->authService->isAdmin();
        $isAccountant = $this->authService->isAccountant();
        $hasRbacExportAccess = $this->rbacService ? ($this->rbacService->can('menu.exports') || $this->rbacService->can('export.catalog')) : false;

        if (!$isAdmin && !$isAccountant && !$hasRbacExportAccess) {
            $this->errorResponse('دسترسی محدود است');
        }

        $dataset = Sanitizer::sanitize($_POST['dataset'] ?? '');
        
        if ($isAccountant && !$isAdmin && $dataset !== 'payments') {
            $this->errorResponse('شما فقط مجاز به دریافت گزارش پرداخت‌ها هستید');
        }

        if ($this->rbacService && !$isAdmin && !$this->rbacService->canExportDataset($dataset)) {
            $this->errorResponse('شما به این خروجی دسترسی ندارید', 403);
        }

        $format = Sanitizer::sanitize($_POST['format'] ?? 'csv');
        $columnsJson = $_POST['columns_json'] ?? '[]';
        $filtersJson = $_POST['filters_json'] ?? '{}';

        $columns = json_decode((string)$columnsJson, true);
        $filters = json_decode((string)$filtersJson, true);
        if (!is_array($columns)) $columns = [];
        if (!is_array($filters)) $filters = [];

        // Convert checkbox to boolean
        if (isset($filters['include_raw_json'])) {
            $filters['include_raw_json'] = $filters['include_raw_json'] === '1' || $filters['include_raw_json'] === 1 || $filters['include_raw_json'] === true;
        }

        // This method streams a file and exits.
        $this->exportService->export($dataset, $columns, $filters, $format);
        exit;
    }
}

