<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use Illuminate\Http\Request;

use App\Models\Business;
use Illuminate\Pagination\LengthAwarePaginator;

class ToDoController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        // 1. Fetch Investor Follow-ups
        $leadQuery = Lead::whereNotNull('next_followup_date')->with(['creator:id,name']);
        
        if ($user->isHead()) {
             $teamMemberIds = $user->members->pluck('id')->toArray();
             $teamMemberIds[] = $user->id;

             $leadQuery->where(function($q) use ($teamMemberIds) {
                 $q->whereIn('created_by', $teamMemberIds)
                   ->orWhereHas('assignedTo', function ($sq) use ($teamMemberIds) {
                       $sq->whereIn('users.id', $teamMemberIds);
                   });
             });
        } elseif ($user->isTeamMember()) {
             $leadQuery->where(function($q) use ($user) {
                 $q->where('created_by', $user->id)
                   ->orWhereHas('assignedTo', function ($sq) use ($user) {
                       $sq->where('users.id', $user->id);
                   });
             });
        }
        
        $leads = $leadQuery->get()->each(function($item) {
            $item->setAttribute('type', 'investor');
        });

        // 2. Fetch Business Follow-ups
        $businessQuery = Business::whereNotNull('next_followup_date')->with(['creator:id,name']);
        
        if ($user->isHead()) {
             $teamMemberIds = $user->members->pluck('id')->toArray();
             $teamMemberIds[] = $user->id;

             $businessQuery->where(function($q) use ($teamMemberIds) {
                 $q->whereIn('created_by', $teamMemberIds)
                   ->orWhereHas('assignedTo', function ($sq) use ($teamMemberIds) {
                       $sq->whereIn('users.id', $teamMemberIds);
                   });
             });
        } elseif ($user->isTeamMember()) {
             $businessQuery->where(function($q) use ($user) {
                 $q->where('created_by', $user->id)
                   ->orWhereHas('assignedTo', function ($sq) use ($user) {
                       $sq->where('users.id', $user->id);
                   });
             });
        }

        $businesses = $businessQuery->get()->each(function($item) {
            $item->setAttribute('type', 'business');
        });

        // 3. Merge
        $merged = $leads->concat($businesses);

        // 4. Sort: Today's follow-ups first, then by date ASC
        $sorted = $merged->sort(function ($a, $b) {
            $dateA = \Carbon\Carbon::parse($a->next_followup_date)->startOfDay();
            $dateB = \Carbon\Carbon::parse($b->next_followup_date)->startOfDay();
            $today = \Carbon\Carbon::today();

            $isTodayA = $dateA->eq($today);
            $isTodayB = $dateB->eq($today);

            if ($isTodayA && !$isTodayB) return -1;
            if (!$isTodayA && $isTodayB) return 1;
            
            return $dateA->timestamp <=> $dateB->timestamp;
        });

        // 5. Pagination
        $page = request()->get('page', 1);
        $perPage = 50;
        $offset = ($page - 1) * $perPage;
        
        $items = $sorted->slice($offset, $perPage)->values();
        
        $paginated = new LengthAwarePaginator(
            $items,
            $sorted->count(),
            $perPage,
            $page,
            ['path' => request()->url(), 'query' => request()->query()]
        );

        return response()->json($paginated);
    }
}
