<?php

namespace App\Http\Controllers;

use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Models\Payment;
use App\Domain\Identity\Services\PermissionService;
use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Services\ReportService;
use App\Domain\Training\Models\Enrollment;
use App\Livewire\Reports\ReportViewer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ExportController extends Controller
{
    public function participants(Request $request): StreamedResponse
    {
        Gate::authorize('participants.list');

        $user = auth()->user();
        $branchId = session()->has('active_branch_id')
            ? session('active_branch_id')
            : $user->branch_id;

        $query = Participant::with(['person', 'branch', 'primaryActivity'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($request->search, function ($q) use ($request) {
                $search = $request->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('participant_number', 'ilike', "%{$search}%")
                       ->orWhere('membership_id', 'ilike', "%{$search}%")
                       ->orWhereHas('person', function ($pq) use ($search) {
                           $pq->where('name_ar', 'ilike', "%{$search}%")
                              ->orWhere('name', 'ilike', "%{$search}%")
                              ->orWhere('phone', 'like', "%{$search}%")
                              ->orWhere('national_id', 'like', "%{$search}%");
                       });
                });
            })
            ->when($request->status, fn ($q, $s) => $q->where('status', $s))
            ->when($request->activity, fn ($q, $a) => $q->where('primary_activity_id', $a))
            ->when($request->skill_level, fn ($q, $s) => $q->where('skill_level', $s))
            ->when($request->membership_type, fn ($q, $m) => $q->where('membership_type', $m))
            ->when($request->is_free !== null && $request->is_free !== '', fn ($q) => $q->where('is_free', $request->is_free === '1'));

        app(PermissionService::class)->applyScope($query, $user, 'participants.list');

        $allowedSorts = ['name_ar', 'participant_number', 'primary_activity_id', 'membership_type', 'status', 'created_at'];
        $sortBy = in_array($request->get('sort_by'), $allowedSorts) ? $request->get('sort_by') : 'name_ar';
        $sortDir = in_array($request->get('sort_dir'), ['asc', 'desc']) ? $request->get('sort_dir') : 'asc';

        if ($sortBy === 'name_ar') {
            $query->join('people', 'participants.person_id', '=', 'people.id')
                  ->orderBy('people.name_ar', $sortDir)
                  ->select('participants.*');
        } else {
            $query->orderBy($sortBy, $sortDir);
        }

        return $this->streamCsv('participants', [
            'الاسم', 'الهاتف', 'البريد', 'الحالة', 'نوع العضوية', 'رقم العضوية', 'مجاني', 'الفرع', 'النشاط', 'تاريخ التسجيل',
        ], $query, function ($p) {
            return [
                $p->person?->name_ar ?? $p->person?->name ?? '',
                $p->person?->phone ?? '',
                $p->person?->email ?? '',
                $p->status?->value ?? $p->status ?? '',
                $p->membership_type?->value ?? $p->membership_type ?? '',
                $p->membership_id ?? '',
                $p->is_free ? 'نعم' : 'لا',
                $p->branch?->name_ar ?? '',
                $p->primaryActivity?->name_ar ?? '',
                $p->created_at?->format('Y-m-d'),
            ];
        });
    }

    public function payments(Request $request): StreamedResponse
    {
        Gate::authorize('invoices.list');

        $branchId = session('active_branch_id');
        $from = $request->get('from', now()->startOfMonth()->toDateString());
        $to = $request->get('to', now()->toDateString());

        $query = Payment::with(['invoice', 'creator'])
            ->where('status', 'confirmed')
            ->whereBetween('payment_date', [$from, $to])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->orderByDesc('payment_date');

        return $this->streamCsv('payments', [
            'التاريخ', 'المرجع', 'المبلغ', 'الطريقة', 'رقم الفاتورة', 'بواسطة',
        ], $query, function ($p) {
            return [
                $p->payment_date?->format('Y-m-d'),
                $p->reference ?? '',
                number_format($p->amount / 100, 2),
                $p->method?->value ?? '',
                $p->invoice?->number ?? '',
                $p->creator?->name ?? '',
            ];
        });
    }

    public function invoices(Request $request): StreamedResponse
    {
        Gate::authorize('invoices.list');

        $branchId = session('active_branch_id');

        $query = Invoice::with(['billable.person'])
            ->when($branchId, fn ($q) => $q->whereHasMorph('billable', [\App\Domain\Participant\Models\Participant::class], fn ($pq) => $pq->where('branch_id', $branchId)))
            ->when($request->status, fn ($q, $s) => $q->where('status', $s))
            ->when($request->search, function ($q) use ($request) {
                $search = $request->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('number', 'ilike', "%{$search}%")
                       ->orWhere('contact_name', 'ilike', "%{$search}%");
                });
            })
            ->when($request->from, fn ($q, $from) => $q->where('created_at', '>=', $from))
            ->when($request->to, fn ($q, $to) => $q->where('created_at', '<=', $to . ' 23:59:59'))
            ->orderByDesc('created_at');

        return $this->streamCsv('invoices', [
            'رقم الفاتورة', 'المشترك', 'الإجمالي', 'المدفوع', 'المستحق', 'الحالة', 'التاريخ', 'تاريخ الاستحقاق',
        ], $query, function ($inv) {
            $name = $inv->contact_name
                ?? $inv->billable?->person?->name_ar
                ?? $inv->billable?->name_ar
                ?? '';
            return [
                $inv->number ?? '',
                $name,
                number_format($inv->total_amount / 100, 2),
                number_format($inv->paid_amount / 100, 2),
                number_format(($inv->total_amount - $inv->paid_amount) / 100, 2),
                $inv->status?->value ?? $inv->status ?? '',
                $inv->created_at?->format('Y-m-d'),
                $inv->due_date?->format('Y-m-d') ?? '',
            ];
        });
    }

    public function enrollments(Request $request): StreamedResponse
    {
        Gate::authorize('enrollments.list');

        $branchId = session('active_branch_id');

        $query = Enrollment::with(['participant.person', 'group.program', 'group.branch'])
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->when($request->status, fn ($q, $s) => $q->where('status', $s))
            ->orderByDesc('enrollment_date');

        return $this->streamCsv('enrollments', [
            'المشترك', 'البرنامج', 'المجموعة', 'الحالة', 'تاريخ التسجيل', 'الفرع',
        ], $query, function ($e) {
            return [
                $e->participant?->person?->name_ar ?? '',
                $e->group?->program?->name_ar ?? '',
                $e->group?->name_ar ?? '',
                $e->status ?? '',
                $e->enrollment_date?->format('Y-m-d') ?? '',
                $e->group?->branch?->name_ar ?? '',
            ];
        });
    }

    public function report(Request $request, ReportService $reportService): StreamedResponse
    {
        Gate::authorize('reports.view');

        $reportKey = $request->get('report');
        $viewer = new ReportViewer();
        $configs = $viewer->getReportConfig();

        if (!$reportKey || !isset($configs[$reportKey])) {
            abort(404);
        }

        $config = $configs[$reportKey];
        $method = $config['method'];
        $usesDates = $config['uses_dates'] ?? true;
        $branchId = session()->has('active_branch_id') ? session('active_branch_id') : auth()->user()->branch_id;

        $from = $request->get('from', now()->startOfMonth()->toDateString());
        $to = $request->get('to', now()->toDateString());

        if ($usesDates) {
            $data = $reportService->$method($from, $to, $branchId);
        } else {
            $data = $reportService->$method($branchId);
        }

        $moneyCols = $config['money_cols'] ?? [];
        $columns = $config['columns'];

        $date = now()->format('Y-m-d');

        return response()->streamDownload(function () use ($config, $data, $columns, $moneyCols) {
            $handle = fopen('php://output', 'w');
            fprintf($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));
            fputcsv($handle, $config['headers']);

            foreach ($data as $row) {
                $csvRow = [];
                foreach ($columns as $col) {
                    $value = is_array($row) ? ($row[$col] ?? '') : ($row->$col ?? '');
                    if (in_array($col, $moneyCols)) {
                        $value = number_format($value / 100, 2);
                    }
                    $csvRow[] = $value;
                }
                fputcsv($handle, $csvRow);
            }

            fclose($handle);
        }, "{$reportKey}-{$date}.csv", [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }

    private function streamCsv(string $filename, array $headers, $query, callable $rowMapper): StreamedResponse
    {
        $date = now()->format('Y-m-d');

        return response()->streamDownload(function () use ($headers, $query, $rowMapper) {
            $handle = fopen('php://output', 'w');
            fprintf($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));
            fputcsv($handle, $headers);

            foreach ($query->cursor() as $record) {
                fputcsv($handle, $rowMapper($record));
            }

            fclose($handle);
        }, "{$filename}-{$date}.csv", [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }
}
