<?php
namespace App\Http\Controllers;
use App\Models\Account;
use App\Models\Activity;
use App\Models\Contact;
use App\Models\Deal;
use App\Models\FollowUp;
use App\Models\Lead;
use App\Models\Message;
use App\Models\Note;
use App\Models\Ticket;
use App\Models\Campaign;
use App\Models\Project;
use App\Models\CrmCase;
use App\Models\Survey;
use Illuminate\Support\Facades\Schema;
use App\Models\Todo;
use Illuminate\View\View;

class RelatedActivityController extends Controller
{
    public function index(string $module, int $id): View
    {
        $map = ['contacts'=>Contact::class,'leads'=>Lead::class,'deals'=>Deal::class,
            'accounts'=>Account::class,'tickets'=>Ticket::class,'campaigns'=>Campaign::class,
            'projects'=>Project::class,'cases'=>CrmCase::class,'surveys'=>Survey::class];
        abort_unless(isset($map[$module]), 404);
        $record = $map[$module]::findOrFail($id);
        abort_unless($record->business_id === auth()->user()->business_id, 403);
        $foreign = rtrim($module, 's').'_id';
        $activityForeign = $module === 'campaigns' ? 'related_campaign_id' : $foreign;
        $activities = Schema::hasColumn('activities', $activityForeign)
            ? Activity::where('business_id', $record->business_id)->where($activityForeign, $id)->latest()->get() : collect();
        $related = ['related_type' => $record::class, 'related_id' => $id];
        $messages = Message::where($related)->latest()->get();
        $followUps = FollowUp::where($related)->latest()->get();
        $todos = Todo::where($related)->latest()->get();
        $notes = Schema::hasColumn('notes', $foreign)
            ? Note::visibleTo(auth()->user())->where($foreign, $id)->latest()->get() : collect();
        $lastInteraction=$activities->where('lifecycle_status','completed')->sortByDesc(fn($item)=>$item->completed_at ?? $item->created_at)->first();
        $nextCandidates=$activities->whereNotIn('lifecycle_status',['completed','cancelled'])->map(fn($item)=>['title'=>$item->title,'at'=>\Carbon\Carbon::parse(($item->start_date ?: now()->toDateString()).' '.($item->start_time ?: '00:00'))])->merge($followUps->where('status','pending')->map(fn($item)=>['title'=>$item->title,'at'=>$item->follow_up_at]))->merge($todos->whereNotIn('status',['completed','cancelled'])->map(fn($item)=>['title'=>$item->title,'at'=>$item->due_at]))->filter(fn($item)=>$item['at'])->sortBy('at')->first();
        return view('applications.related-activity', compact('module','record','activities','messages','followUps','todos','notes','lastInteraction','nextCandidates'));
    }
}
