<?php

namespace App\Http\Controllers\Sms;

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 SmsMessageController extends Controller
{
    public function absents(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $absents = $schoolId
            ? DB::table('attendance_records')
                ->join('students', 'students.id', '=', 'attendance_records.student_id')
                ->join('attendance_sessions', 'attendance_sessions.id', '=', 'attendance_records.attendance_session_id')
                ->join('classrooms', 'classrooms.id', '=', 'attendance_sessions.classroom_id')
                ->where('attendance_records.school_id', $schoolId)
                ->where('attendance_records.status', 'absent')
                ->whereDate('attendance_records.created_at', today())
                ->select([
                    'students.first_name',
                    'students.last_name',
                    'students.father_mobile',
                    'students.mother_mobile',
                    'classrooms.name as classroom_name',
                ])
                ->get()
            : collect();

        return Inertia::render('Sms/SendToAbsents', [
            'absents' => $absents->map(fn ($item): array => [
                'student' => trim($item->first_name.' '.$item->last_name),
                'classroom' => $item->classroom_name,
                'recipient' => $item->father_mobile ? 'پدر' : ($item->mother_mobile ? 'مادر' : 'بدون شماره'),
                'status' => ($item->father_mobile || $item->mother_mobile) ? 'آماده ارسال' : 'اطلاعات ناقص',
            ])->values(),
        ]);
    }

    public function storeAbsenceRequests(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $sessions = DB::table('attendance_records')
            ->join('attendance_sessions', 'attendance_sessions.id', '=', 'attendance_records.attendance_session_id')
            ->where('attendance_records.school_id', $schoolId)
            ->where('attendance_records.status', 'absent')
            ->whereDate('attendance_records.created_at', today())
            ->select('attendance_sessions.id')
            ->distinct()
            ->pluck('id');

        if ($sessions->isEmpty()) {
            return redirect()->route('school.sms.absents')->with('success', 'غیبتی برای ساخت درخواست SMS وجود ندارد.');
        }

        foreach ($sessions as $sessionId) {
            $absentCount = DB::table('attendance_records')
                ->where('school_id', $schoolId)
                ->where('attendance_session_id', $sessionId)
                ->where('status', 'absent')
                ->count();

            DB::table('attendance_approval_requests')->updateOrInsert(
                [
                    'school_id' => $schoolId,
                    'attendance_session_id' => $sessionId,
                    'type' => 'absence_sms',
                    'status' => 'pending',
                ],
                [
                    'requested_by' => $request->user()?->id,
                    'absent_count' => $absentCount,
                    'sms_cost' => $absentCount,
                    'updated_at' => now(),
                    'created_at' => now(),
                ]
            );
        }

        return redirect()->route('school.attendance.approvals')->with('success', 'درخواست‌های تایید SMS غیبت ساخته شد.');
    }
}
