<?php

namespace App\Services;

use App\Models\AttendanceRecord;
use App\Models\SchoolSetting;
use App\Models\User;
use App\Models\WarningLetter;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class WarningLetterService
{
    /**
     * Mendapatkan daftar siswa berisiko (Alpha >= 3x dalam sebulan)
     */
    public function getStudentsAtRisk(?string $month = null): array
    {
        $month = $month ?? now()->format('Y-m');

        // Ambil semua record status 'Alpha' pada bulan tersebut
        $query = AttendanceRecord::with('user')->where('status', 'Alpha');
        $dateParts = explode('-', $month);
        if (count($dateParts) == 2) {
            $query->whereYear('date', $dateParts[0])->whereMonth('date', $dateParts[1]);
        }
        $alphaRecords = $query->get()->groupBy('user_id');

        $result = [];

        foreach ($alphaRecords as $userId => $records) {
            $student = User::find($userId);
            if (!$student) continue;

            $alphaCount = $records->count();
            if ($alphaCount < 3) continue;

            $recommendedType = 'sp1';
            if ($alphaCount >= 7) {
                $recommendedType = 'panggilan_ortu';
            } elseif ($alphaCount >= 5) {
                $recommendedType = 'sp2';
            }

            // Periksa apakah surat jenis ini sudah pernah diterbitkan bulan ini
            $existingLetter = WarningLetter::where('user_id', $userId)
                ->where('month', $month)
                ->where('letter_type', $recommendedType)
                ->first();

            $result[] = [
                'student' => $student,
                'alpha_count' => $alphaCount,
                'month' => $month,
                'recommended_type' => $recommendedType,
                'existing_letter' => $existingLetter,
                'alpha_dates' => $records->pluck('date')->map(fn($d) => Carbon::parse($d)->translatedFormat('d F Y'))->toArray(),
            ];
        }

        return $result;
    }

    /**
     * Menerbitkan Surat Peringatan / Panggilan Orang Tua
     */
    public function issueWarningLetter(int $userId, string $letterType, ?string $notes = null, ?string $month = null): WarningLetter
    {
        $month = $month ?? now()->format('Y-m');
        $allowedTypes = ['sp1', 'sp2', 'panggilan_ortu'];

        if (!in_array($letterType, $allowedTypes, true)) {
            throw new \InvalidArgumentException('Jenis surat peringatan tidak valid.');
        }

        $student = User::findOrFail($userId);

        $existing = WarningLetter::where('user_id', $userId)
            ->where('month', $month)
            ->where('letter_type', $letterType)
            ->first();

        if ($existing) {
            return $existing;
        }

        $queryAlpha = AttendanceRecord::where('user_id', $userId)->where('status', 'Alpha');
        $dateParts = explode('-', $month);
        if (count($dateParts) == 2) {
            $queryAlpha->whereYear('date', $dateParts[0])->whereMonth('date', $dateParts[1]);
        }
        $alphaCount = $queryAlpha->count();

        // Format nomor surat resmi
        $countThisYear = WarningLetter::whereYear('created_at', now()->year)->count() + 1;
        $numPadded = str_pad($countThisYear, 3, '0', STR_PAD_LEFT);
        $typeTag = strtoupper($letterType === 'panggilan_ortu' ? 'PANGGILAN' : $letterType);
        $schoolCode = Str::slug(SchoolSetting::get('school_name', 'SMKN1GA'), '');
        $letterNumber = "421.5/{$typeTag}/{$schoolCode}/" . now()->year . "/{$numPadded}";

        return WarningLetter::create([
            'user_id' => $userId,
            'letter_type' => $letterType,
            'letter_number' => $letterNumber,
            'alpha_count' => $alphaCount,
            'month' => $month,
            'issued_date' => now()->toDateString(),
            'notes' => $notes,
            'created_by' => Auth::id(),
        ]);
    }

    /**
     * Menyiapkan data lengkap untuk cetak PDF Surat Peringatan
     */
    public function getPdfData(WarningLetter $letter): array
    {
        $schoolSettings = SchoolSetting::getAllCached();
        $student = $letter->user;

        $queryDates = AttendanceRecord::where('user_id', $student->id)->where('status', 'Alpha');
        $dateParts = explode('-', $letter->month);
        if (count($dateParts) == 2) {
            $queryDates->whereYear('date', $dateParts[0])->whereMonth('date', $dateParts[1]);
        }
        
        $alphaDates = $queryDates->orderBy('date', 'asc')
            ->pluck('date')
            ->map(fn($d) => Carbon::parse($d)->translatedFormat('l, d F Y'))
            ->toArray();

        return [
            'letter' => $letter,
            'student' => $student,
            'school' => $schoolSettings,
            'alphaDates' => $alphaDates,
            'logoUrl' => SchoolSetting::getFileUrl('school_logo'),
            'signatureUrl' => SchoolSetting::getFileUrl('principal_signature'),
        ];
    }
}
