<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Concerns\BuildsPortalPayloads;
use App\Http\Controllers\Controller;
use App\Models\FeeChallan;
use App\Models\Student;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

/**
 * Mobile API for the Student role. All data is scoped to the student's own record.
 */
class StudentController extends Controller
{
    use BuildsPortalPayloads;

    private function self(Request $request): Student
    {
        $student = $request->user()->student;
        abort_if(! $student, 403, 'No student record is linked to this account.');

        return $student;
    }

    public function dashboard(Request $request): JsonResponse
    {
        $student = $this->self($request);
        $fees = $student->family_id ? $this->challanListPayload($student->family_id) : ['outstanding' => 0];

        return response()->json([
            'card' => $this->childCardPayload($student),
            'outstanding' => $fees['outstanding'],
            'notices' => $this->noticesPayload($student->branch_id, 'students', 5),
        ]);
    }

    public function attendance(Request $request): JsonResponse
    {
        $student = $this->self($request);
        $month = $request->input('month', Carbon::today()->format('Y-m'));

        return response()->json($this->attendancePayload($student, $month));
    }

    public function results(Request $request): JsonResponse
    {
        $student = $this->self($request);

        return response()->json($this->resultPayload($student, $request->integer('exam_id') ?: null));
    }

    public function fees(Request $request): JsonResponse
    {
        $student = $this->self($request);
        abort_if(! $student->family_id, 403, 'No family linked.');

        return response()->json($this->challanListPayload($student->family_id));
    }

    public function feeDetail(Request $request, FeeChallan $challan): JsonResponse
    {
        $student = $this->self($request);
        abort_unless($challan->family_id === $student->family_id, 403);

        return response()->json($this->challanDetailPayload($challan));
    }

    public function notices(Request $request): JsonResponse
    {
        $student = $this->self($request);

        return response()->json(['notices' => $this->noticesPayload($student->branch_id, 'students', 50)]);
    }

    public function profile(Request $request): JsonResponse
    {
        $student = $this->self($request);

        return response()->json([
            'account' => ['name' => $request->user()->name, 'email' => $request->user()->email],
            'student' => $this->studentPayload($student),
            'family' => $student->family ? [
                'code' => $student->family->family_code,
                'father_name' => $student->family->father_name,
                'father_mobile' => $student->family->father_mobile,
            ] : null,
        ]);
    }
}
