<?php

namespace Tests\Feature\Api\V1\Workflows;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\AssertsE2EApiResponses;
use Tests\Concerns\SeedsE2ETestFixtures;
use Tests\TestCase;

/**
 * Scenario R: Attendance operations and exception handling.
 *
 * This covers the actual attendance day: teacher grid, submission, admin edits,
 * late slips, early dismissal, follow-up, violation tracking, and templates.
 */
class ScenarioRAttendanceOperationsAndExceptionHandlingTest extends TestCase
{
    use RefreshDatabase;
    use SeedsE2ETestFixtures;
    use AssertsE2EApiResponses;

    public function test_teacher_admin_and_staff_handle_attendance_day_end_to_end(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $teacher = $world['teacher'];
        $admin = $this->actingAsApiAdministrator();
        $studentId = $world['student_id'];
        $classSectionId = $world['class_section_id'];

        $this->actingAs($teacher, 'api');
        $this->getJson('/api/v1/attendance/teacher/grid?class_section_id=' . $classSectionId . '&date=2025-10-05')
            ->assertSuccessful();
        $this->getJson('/api/v1/attendance/teacher/form?class_section_id=' . $classSectionId . '&date=2025-10-05')
            ->assertSuccessful();

        $submit = $this->postJson('/api/v1/attendance/teacher/submit', [
            'class_section_id' => $classSectionId,
            'date' => '2025-10-05',
            'attendance' => [
                [
                    'student_id' => $studentId,
                    'status' => 'present',
                    'comment' => 'On time',
                ],
            ],
            'semester' => self::E2E_SEMESTER,
            'school_year' => self::E2E_SCHOOL_YEAR,
        ]);
        $this->assertNoServerError($submit, 'Teacher attendance submit');

        $this->actingAs($admin, 'api');
        $this->getJson('/api/v1/attendance/admin/daily?date=2025-10-05&class_section_id=' . $classSectionId)
            ->assertSuccessful();

        $manualAdd = $this->postJson('/api/v1/attendance/admin/add-entry', [
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'date' => '2025-10-05',
            'status' => 'late',
            'comment' => 'Arrived after assembly.',
            'semester' => self::E2E_SEMESTER,
            'school_year' => self::E2E_SCHOOL_YEAR,
        ]);
        $this->assertNoServerError($manualAdd, 'Admin attendance manual entry');

        $this->getJson('/api/v1/attendance/staff/month?month=2025-10')
            ->assertSuccessful();
        $this->getJson('/api/v1/attendance/staff/admins')
            ->assertSuccessful();

        $staffCell = $this->postJson('/api/v1/attendance/staff/cell', [
            'user_id' => $admin->id,
            'date' => '2025-10-05',
            'status' => 'present',
            'school_year' => self::E2E_SCHOOL_YEAR,
        ]);
        $this->assertNoServerError($staffCell, 'Staff attendance cell save');
    }

    public function test_early_dismissal_late_slip_and_violation_tracking_are_connected(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $admin = $this->actingAsApiAdministrator();
        $studentId = $world['student_id'];
        $classSectionId = $world['class_section_id'];
        $this->actingAs($admin, 'api');

        $this->getJson('/api/v1/attendance/early-dismissals/student-options')
            ->assertSuccessful();

        $dismissal = $this->postJson('/api/v1/attendance/early-dismissals', [
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'dismissal_date' => '2025-10-05',
            'dismissal_time' => '12:10',
            'reason' => 'Medical appointment',
            'released_to' => 'Parent Fixture',
            'relationship' => 'Parent',
        ]);
        $this->assertNoServerError($dismissal, 'Early dismissal creation');

        $signature = $this->post('/api/v1/attendance/early-dismissals/signature', [
            'student_id' => $studentId,
            'signature' => UploadedFile::fake()->image('signature.png', 200, 100),
        ]);
        $this->assertSuccessfulOrValidation($signature, 'Early dismissal signature upload');

        $this->getJson('/api/v1/attendance/late-slip-logs')
            ->assertSuccessful();

        $record = $this->postJson('/api/v1/attendance-tracking/record', [
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'date' => '2025-10-05',
            'type' => 'late',
            'status' => 'pending',
            'note' => 'Second late arrival this month.',
            'school_year' => self::E2E_SCHOOL_YEAR,
            'semester' => self::E2E_SEMESTER,
        ]);
        $this->assertNoServerError($record, 'Attendance tracking record');

        $this->getJson('/api/v1/attendance-tracking/pending-violations')
            ->assertSuccessful();
        $this->getJson('/api/v1/attendance-tracking/student-case/' . $studentId)
            ->assertSuccessful();
        $this->getJson('/api/v1/attendance-tracking/compose?student_id=' . $studentId)
            ->assertSuccessful();

        $note = $this->postJson('/api/v1/attendance-tracking/save-notification-note', [
            'student_id' => $studentId,
            'note' => 'Parent notified about attendance pattern.',
            'date' => '2025-10-05',
        ]);
        $this->assertNoServerError($note, 'Attendance tracking note');
    }

    public function test_attendance_comment_templates_support_create_update_delete_and_legacy_aliases(): void
    {
        $this->seedE2EConfiguration();
        $admin = $this->actingAsApiAdministrator();
        $this->actingAs($admin, 'api');

        $create = $this->postJson('/api/v1/attendance-comment-templates', [
            'comment' => 'E2E: arrived after first lesson.',
            'type' => 'late',
            'is_active' => true,
        ]);
        $create->assertCreated();

        $templateId = (int) DB::table('attendance_comment_templates')
            ->where('comment', 'E2E: arrived after first lesson.')
            ->value('id');
        $this->assertGreaterThan(0, $templateId);

        $this->getJson('/api/v1/attendance-comment-templates/list-data')
            ->assertOk();
        $this->putJson('/api/v1/attendance-comment-templates/' . $templateId, [
            'comment' => 'E2E: arrived late, parent notified.',
            'type' => 'late',
            'is_active' => true,
        ])->assertSuccessful();

        $this->postJson('/api/v1/attendance-templates/save', [
            'id' => $templateId,
            'comment' => 'Legacy alias update',
            'type' => 'late',
        ])->assertSuccessful();

        $this->deleteJson('/api/v1/attendance-comment-templates/' . $templateId)
            ->assertSuccessful();
    }
}
