<?php

namespace App\Http\Controllers\Api\AttendanceTracking;

use App\Http\Controllers\Controller;
use App\Services\AttendanceTracking\AttendanceTrackingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AttendanceTrackingController extends Controller
{
    public function __construct(
        protected AttendanceTrackingService $service
    ) {
    }

    public function pendingViolations(Request $request): JsonResponse
    {
        $result = $this->service->getPendingViolations(
            $request->query('school_year'),
            $request->query('semester')
        );

        return response()->json([
            'success' => true,
            'data' => $result,
        ]);
    }

    public function notifiedViolations(Request $request): JsonResponse
    {
        $result = $this->service->getNotifiedViolations(
            $request->query('school_year'),
            $request->query('semester')
        );

        return response()->json([
            'success' => true,
            'data' => $result,
        ]);
    }

    public function studentCase(int $studentId, Request $request): JsonResponse
    {
        $result = $this->service->getStudentCase(
            $studentId,
            $request->query('code'),
            $request->query('incident_date'),
            filter_var($request->query('include_notified'), FILTER_VALIDATE_BOOL) === true,
            filter_var($request->query('pending_only'), FILTER_VALIDATE_BOOL) === true,
            $request->query('school_year'),
            $request->query('semester'),
        );

        return response()->json(
            $result,
            $result['status'] ?? 200
        );
    }

    public function record(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'student_id' => ['required', 'integer', 'min:1'],
            'date' => ['required', 'date_format:Y-m-d'],
            'parent_email' => ['nullable', 'email'],
            'parent_name' => ['nullable', 'string'],
            'subject_type' => ['nullable', 'string'],
            'semester' => ['nullable', 'string'],
            'school_year' => ['nullable', 'string'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $result = $this->service->record($validator->validated());

        return response()->json(
            $result,
            $result['status'] ?? 200
        );
    }

    public function sendAutoEmails(Request $request): JsonResponse
    {
        $result = $this->service->sendAutoEmails($request->input('variant'));

        return response()->json($result);
    }

    public function compose(Request $request): JsonResponse
    {
        $validator = Validator::make($request->query(), [
            'student_id' => ['required', 'integer', 'min:1'],
            'code' => ['nullable', 'string'],
            'variant' => ['nullable', 'string'],
            'incident_date' => ['nullable', 'date_format:Y-m-d'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $data = $validator->validated();
        $result = $this->service->compose(
            (int) ($data['student_id'] ?? 0),
            (string) ($data['code'] ?? 'ABS_1'),
            (string) ($data['variant'] ?? 'default'),
            $data['incident_date'] ?? null,
        );

        return response()->json(
            $result,
            $result['status'] ?? 200
        );
    }

    public function sendManualEmail(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'student_id' => ['required', 'integer', 'min:1'],
            'to' => ['required', 'email'],
            'subject' => ['required', 'string'],
            'body_html' => ['required', 'string'],
            'code' => ['required', 'string'],
            'variant' => ['nullable', 'string'],
            'incident_date' => ['nullable', 'date_format:Y-m-d'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $result = $this->service->sendEmailManual($validator->validated());

        return response()->json(
            $result,
            $result['status'] ?? 200
        );
    }

    public function parentsInfo(Request $request): JsonResponse
    {
        $validator = Validator::make($request->query(), [
            'student_id' => ['required', 'integer', 'min:1'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $data = $validator->validated();
        $result = $this->service->parentsInfo((int) ($data['student_id'] ?? 0));

        return response()->json(
            $result,
            $result['status'] ?? 200
        );
    }

    public function saveNotificationNote(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'student_id' => ['required', 'integer', 'min:1'],
            'code' => ['required', 'string'],
            'note' => ['required', 'string'],
            'incident_date' => ['nullable', 'date_format:Y-m-d'],
            'to' => ['nullable', 'email'],
            'subject' => ['nullable', 'string'],
            'variant' => ['nullable', 'string'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $result = $this->service->saveNotificationNote($validator->validated());

        return response()->json(
            $result,
            $result['status'] ?? 200
        );
    }
}
