<?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);
        $columnsError = json_last_error();
        $filters = json_decode((string)$filtersJson, true);
        $filtersError = json_last_error();
        if ($columnsError !== JSON_ERROR_NONE || !is_array($columns)) {
            $this->errorResponse('columns_json نامعتبر است', 422);
        }
        if ($filtersError !== JSON_ERROR_NONE || !is_array($filters)) {
            $this->errorResponse('filters_json نامعتبر است', 422);
        }

        // 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;
        }

        if ($this->rbacService && !$isAdmin) {
            $resourceKey = $this->resourceForDataset($dataset);
            $requestedOwner = trim((string)($filters['owner_didar_id'] ?? ''));
            $filters = $this->rbacService->applyOwnerScope($filters, $resourceKey, $requestedOwner);
        }

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

    private function resourceForDataset(string $dataset): string
    {
        if (in_array($dataset, ['leads', 'persons'], true)) return 'leads';
        if (in_array($dataset, ['deals', 'legacy_deals'], true)) return 'deals';
        if ($dataset === 'payments') return 'payments';
        if ($dataset === 'commission_lines') return 'exports';
        if ($dataset === 'activities') return 'activities';
        return 'exports';
    }
}

