<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function index()
    {
        $u = Auth::user();
        return view('notifications.index', [
            'unread' => $u->unreadNotifications()->take(50)->get(),
            'read' => $u->readNotifications()->orderByDesc('read_at')->take(30)->get(),
            'tasks' => self::myTasks($u),
        ]);
    }

    /** A5: live task list — approvals I can decide + overdue/expiry alerts (perm-gated). */
    public static function myTasks($u): array {
        $tasks = [];
        $approveTypes = [];
        foreach (\App\Services\ApprovalService::types() as $type => $t) {
            if ($u->canDo(\App\Services\ApprovalService::permFor($type).'.approve')) $approveTypes[] = $type;
        }
        if ($approveTypes) {
            $pend = \App\Models\Approval::with('requester')->where('status', 'pending')
                ->whereIn('document_type', $approveTypes)->orderBy('created_at')->take(20)->get();
            foreach ($pend as $a) {
                $t = \App\Services\ApprovalService::types()[$a->document_type];
                $url = crud_url($t['key'], 'show', $a->document_id);
                $tasks[] = ['icon' => '⏳', 'label' => $t['label'].' '.$a->document_no.' awaits your decision',
                    'sub' => 'Requested by '.($a->requester->name ?? '—').' · '.$a->created_at->diffForHumans(),
                    'url' => $url === '#' ? route('approvals.index') : $url];
            }
        }
        if ($u->canDo('finance.view')) {
            $od = \App\Models\TaxFiling::where('status', '!=', 'paid')->where('due_date', '<', today()->format('Y-m-d'))
                ->orderBy('due_date')->take(10)->get();
            foreach ($od as $f) {
                $tasks[] = ['icon' => '🧾', 'label' => (\App\Models\TaxFiling::types()[$f->tax_type] ?? $f->tax_type)." {$f->period} overdue — ".money($f->outstanding),
                    'sub' => 'Due '.fdate($f->due_date).($f->gra_receipt_no ? ' · '.$f->gra_receipt_no : ''),
                    'url' => crud_url('tax-filings', 'show', $f->id)];
            }
        }
        if ($u->canDo('fleet.view')) {
            $exp = \App\Models\EquipmentDocument::with('equipment')->whereNotNull('expiry_date')
                ->whereBetween('expiry_date', [today()->format('Y-m-d'), today()->addDays(30)->format('Y-m-d')])
                ->orderBy('expiry_date')->take(10)->get();
            foreach ($exp as $d) {
                $tasks[] = ['icon' => '📄', 'label' => ($d->equipment->code ?? 'Equipment').' — '.$d->doc_type.' expires '.fdate($d->expiry_date),
                    'sub' => today()->diffInDays($d->expiry_date).' day(s) left', 'url' => crud_url('equipment-documents', 'show', $d->id)];
            }
        }
        return $tasks;
    }

    public function open(string $id)
    {
        $n = Auth::user()->notifications()->findOrFail($id);
        $n->markAsRead();
        return redirect()->to($n->data['url'] ?? route('notifications.index'));
    }

    public function readAll(Request $r)
    {
        Auth::user()->unreadNotifications->markAsRead();
        return back()->with('success', 'All notifications marked as read.');
    }
}
