<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\API\BaseApiController;
use App\Models\Meeting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminMeetingController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $meetings = Meeting::with(['investor:id,uid,name,email', 'proposal:id,code,name', 'opportunity:id,code,title_pt'])
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->search, fn($q) =>
                $q->whereHas('investor', fn($q2) => $q2->where('name', 'like', "%{$request->search}%"))
            )
            ->orderByDesc('requested_at')
            ->get();

        $stats = Meeting::selectRaw("
            COUNT(*) as total,
            SUM(status = 'pendente')  as pendente,
            SUM(status = 'aprovada')  as aprovada,
            SUM(status = 'recusada')  as recusada
        ")->first();

        return response()->json([
            'success' => true,
            'message' => 'Dados obtidos com sucesso',
            'data'    => $meetings,
            'stats'   => [
                'total'    => (int) $stats->total,
                'pendente' => (int) $stats->pendente,
                'aprovada' => (int) $stats->aprovada,
                'recusada' => (int) $stats->recusada,
            ],
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $meeting = Meeting::with(['investor:id,uid,name,email,phone', 'admin:id,name', 'proposal:id,code,name', 'opportunity:id,code,title_pt'])->findOrFail($id);
        return $this->successResponse($meeting);
    }

    public function approve(Request $request, int $id): JsonResponse
    {
        $meeting = Meeting::findOrFail($id);
        $request->validate([
            'scheduled_at' => 'required|date|after:now',
            'meeting_url'  => 'nullable|url',
            'location'     => 'nullable|string|max:255',
        ]);

        $meeting->update([
            'status'       => 'aprovada',
            'admin_id'     => $request->user()->id,
            'scheduled_at' => $request->scheduled_at,
            'meeting_url'  => $request->meeting_url,
            'location'     => $request->location,
        ]);

        return $this->successResponse($meeting, 'Reunião aprovada e agendada');
    }

    public function reject(Request $request, int $id): JsonResponse
    {
        $meeting = Meeting::findOrFail($id);
        $request->validate(['reason' => 'required|string|max:500']);

        $meeting->update([
            'status'           => 'recusada',
            'rejection_reason' => $request->reason,
            'admin_id'         => $request->user()->id,
        ]);

        return $this->successResponse(null, 'Reunião recusada');
    }

    public function complete(Request $request, int $id): JsonResponse
    {
        $meeting = Meeting::findOrFail($id);
        $meeting->update([
            'status'        => 'realizada',
            'completed_at'  => now(),
            'meeting_notes' => $request->meeting_notes,
        ]);

        return $this->successResponse($meeting, 'Reunião marcada como realizada');
    }
}
