<?php

namespace App\Http\Controllers\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class MessageController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;

        $inbox = DB::table('messages')
            ->join('message_recipients', 'message_recipients.message_id', '=', 'messages.id')
            ->leftJoin('users as sender', 'sender.id', '=', 'messages.sender_user_id')
            ->where('messages.school_id', $schoolId)
            ->where('message_recipients.recipient_user_id', $userId)
            ->orderByDesc('messages.created_at')
            ->limit(50)
            ->get([
                'messages.id',
                'messages.subject',
                'messages.body',
                'messages.created_at',
                'message_recipients.read_at',
                'sender.first_name as sender_first',
                'sender.last_name as sender_last',
                'sender.username as sender_username',
            ]);

        $sent = DB::table('messages')
            ->where('school_id', $schoolId)
            ->where('sender_user_id', $userId)
            ->orderByDesc('created_at')
            ->limit(50)
            ->get(['id', 'subject', 'body', 'created_at']);

        $sentIds = $sent->pluck('id');
        $recipientCounts = $sentIds->isNotEmpty()
            ? DB::table('message_recipients')
                ->whereIn('message_id', $sentIds)
                ->selectRaw('message_id, COUNT(*) as cnt')
                ->groupBy('message_id')
                ->pluck('cnt', 'message_id')
            : collect();

        $schoolUsers = DB::table('users')
            ->where('school_id', $schoolId)
            ->where('id', '!=', $userId)
            ->where('status', 'active')
            ->whereNotIn('role_key', ['super_admin', 'support', 'finance'])
            ->orderBy('first_name')
            ->get(['id', 'first_name', 'last_name', 'username', 'role_key']);

        $roleLabels = [
            'owner' => 'مدیر ارشد',
            'principal' => 'مدیر مدرسه',
            'moaven' => 'معاون',
            'teacher' => 'معلم',
            'student' => 'دانش‌آموز',
        ];

        return Inertia::render('School/Messages', [
            'inbox' => $inbox->map(fn ($m): array => [
                'id' => (int) $m->id,
                'subject' => $m->subject ?: '(بدون موضوع)',
                'body' => $m->body,
                'createdAt' => $this->jalaliDate($m->created_at, true),
                'readAt' => $m->read_at ? $this->jalaliDate($m->read_at, true) : null,
                'sender' => trim(($m->sender_first ?? '').' '.($m->sender_last ?? '')) ?: ($m->sender_username ?? 'سیستم'),
            ])->values(),
            'sent' => $sent->map(fn ($m): array => [
                'id' => (int) $m->id,
                'subject' => $m->subject ?: '(بدون موضوع)',
                'body' => $m->body,
                'createdAt' => $this->jalaliDate($m->created_at, true),
                'recipientCount' => (int) ($recipientCounts[$m->id] ?? 0),
            ])->values(),
            'users' => $schoolUsers->map(fn ($u): array => [
                'id' => (int) $u->id,
                'name' => trim(($u->first_name ?? '').' '.($u->last_name ?? '')) ?: $u->username,
                'role' => $roleLabels[$u->role_key] ?? $u->role_key,
            ])->values(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;

        $data = $request->validate([
            'recipient_ids' => ['required', 'array', 'min:1'],
            'recipient_ids.*' => ['integer'],
            'subject' => ['nullable', 'string', 'max:190'],
            'body' => ['required', 'string', 'max:5000'],
        ]);

        $validRecipientIds = DB::table('users')
            ->where('school_id', $schoolId)
            ->whereIn('id', $data['recipient_ids'])
            ->pluck('id');

        if ($validRecipientIds->isEmpty()) {
            return back()->withErrors(['recipient_ids' => 'گیرنده معتبری انتخاب نشده.']);
        }

        $messageId = DB::table('messages')->insertGetId([
            'school_id' => $schoolId,
            'sender_user_id' => $userId,
            'subject' => $data['subject'] ?? null,
            'body' => $data['body'],
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $now = now();
        DB::table('message_recipients')->insert(
            $validRecipientIds->map(fn ($rid): array => [
                'message_id' => $messageId,
                'recipient_user_id' => $rid,
                'created_at' => $now,
                'updated_at' => $now,
            ])->values()->all()
        );

        return redirect()->route('school.messages')->with('success', 'پیام ارسال شد.');
    }

    public function markRead(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;

        $message = DB::table('messages')->where('id', $id)->where('school_id', $schoolId)->first();
        abort_unless($message, 404);

        DB::table('message_recipients')
            ->where('message_id', $id)
            ->where('recipient_user_id', $userId)
            ->whereNull('read_at')
            ->update(['read_at' => now(), 'updated_at' => now()]);

        return back()->with('success', 'خوانده شد.');
    }
}
