<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Package;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class BtrcReportController extends Controller
{
    public function __construct()
    {
        $this->middleware('can:reports.view')->only('index');
        $this->middleware('can:reports.export')->only('export');
    }

    public function index(Request $request)
    {
        $filters = $this->filters($request);
        $base = $this->query($filters);
        $customers = (clone $base)->paginate(50)->withQueryString();
        $summary = [
            'total' => (clone $base)->count(),
            'active' => (clone $base)->where('status', 1)->count(),
            'inactive' => (clone $base)->where('status', '!=', 1)->count(),
            'monthly_revenue' => (clone $base)->where('status', 1)->sum('monthly_bill'),
        ];
        $zones = Customer::whereNotNull('zone')->distinct()->orderBy('zone')->pluck('zone');
        $packages = Package::orderBy('name')->get(['id', 'name']);

        return view('admin.reports.btrc', compact('customers', 'summary', 'zones', 'packages', 'filters'));
    }

    public function export(Request $request): StreamedResponse
    {
        $customers = $this->query($this->filters($request))->cursor();

        return response()->streamDownload(function () use ($customers) {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['SL', 'Customer ID', 'Subscriber Name', 'Mobile', 'NID', 'Address', 'Zone', 'Package', 'Bandwidth', 'IP Address', 'Connection Type', 'Connection Date', 'Status', 'MikroTik', 'ONU MAC']);
            $sl = 1;
            foreach ($customers as $customer) {
                fputcsv($out, [$sl++, $customer->customer_code, $customer->name, $customer->contact_phone, $customer->national_id, $customer->office_address, $customer->zone, $customer->package?->name, $customer->package?->net_speed, $customer->ip_address, $customer->connection_type, $customer->connection_date?->format('Y-m-d'), $customer->status == 1 ? 'Active' : 'Inactive', $customer->mikrotik?->name, $customer->onumac]);
            }
            fclose($out);
        }, 'btrc-subscriber-report-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv']);
    }

    private function filters(Request $request): array
    {
        return $request->validate(['from' => ['nullable', 'date'], 'to' => ['nullable', 'date', 'after_or_equal:from'], 'status' => ['nullable', 'in:active,inactive'], 'zone' => ['nullable', 'max:255'], 'package_id' => ['nullable', 'exists:packages,id'], 'search' => ['nullable', 'max:255']]);
    }

    private function query(array $f)
    {
        return Customer::with(['package', 'mikrotik'])->when($f['from'] ?? null, fn ($q, $v) => $q->whereDate('connection_date', '>=', $v))->when($f['to'] ?? null, fn ($q, $v) => $q->whereDate('connection_date', '<=', $v))->when(($f['status'] ?? null) === 'active', fn ($q) => $q->where('status', 1))->when(($f['status'] ?? null) === 'inactive', fn ($q) => $q->where('status', '!=', 1))->when($f['zone'] ?? null, fn ($q, $v) => $q->where('zone', $v))->when($f['package_id'] ?? null, fn ($q, $v) => $q->where('package_id', $v))->when($f['search'] ?? null, fn ($q, $v) => $q->where(fn ($s) => $s->where('customer_code', 'like', "%$v%")->orWhere('name', 'like', "%$v%")->orWhere('contact_phone', 'like', "%$v%")->orWhere('national_id', 'like', "%$v%")->orWhere('ip_address', 'like', "%$v%")))->orderBy('customer_code');
    }
}
