<?php

namespace App\Http\Controllers\Api;

use App\Exports\SiswaTemplateExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\ImportSiswaRequest;
use App\Http\Requests\StoreSiswaRequest;
use App\Http\Requests\UpdateSiswaRequest;
use App\Http\Resources\SiswaCollection;
use App\Http\Resources\SiswaResource;
use App\Imports\SiswaImport;
use App\Models\Siswa;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class SiswaController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Siswa::query();

        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('nisn', 'like', "%{$request->search}%")
                  ->orWhere('nama', 'like', "%{$request->search}%");
            });
        }

        if ($request->status) {
            $query->where('status_kelulusan', $request->status);
        }

        if ($request->kelas) {
            $query->where('kelas', $request->kelas);
        }

        $perPage = (int) ($request->per_page ?? 15);
        $siswa = $query->orderBy('nama')->paginate($perPage);

        return response()->json(array_merge(
            ['success' => true],
            (new SiswaCollection($siswa))->toArray($request)
        ));
    }

    public function store(StoreSiswaRequest $request): JsonResponse
    {
        $siswa = Siswa::create($request->validated());

        activity()->causedBy($request->user())->performedOn($siswa)->log('siswa_created');

        return response()->json([
            'success' => true,
            'message' => 'Data siswa berhasil ditambahkan.',
            'data'    => new SiswaResource($siswa),
        ], 201);
    }

    public function show(int $id): JsonResponse
    {
        $siswa = Siswa::findOrFail($id);

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

    public function update(UpdateSiswaRequest $request, int $id): JsonResponse
    {
        $siswa = Siswa::findOrFail($id);
        $siswa->update($request->validated());

        activity()->causedBy($request->user())->performedOn($siswa)->log('siswa_updated');

        return response()->json([
            'success' => true,
            'message' => 'Data siswa berhasil diperbarui.',
            'data'    => new SiswaResource($siswa),
        ]);
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        $siswa = Siswa::findOrFail($id);
        $nama = $siswa->nama;
        $siswa->delete();

        activity()->causedBy($request->user())->log("siswa_deleted: {$nama}");

        return response()->json([
            'success' => true,
            'message' => 'Data siswa berhasil dihapus.',
        ]);
    }

    public function import(ImportSiswaRequest $request): JsonResponse
    {
        $import = new SiswaImport();
        Excel::import($import, $request->file('file'));

        activity()->causedBy($request->user())->log("siswa_imported: {$import->imported} record");

        return response()->json([
            'success'  => true,
            'message'  => "Import selesai. {$import->imported} data berhasil diimpor.",
            'imported' => $import->imported,
            'failed'   => $import->failed,
        ]);
    }

    public function kelasList(): JsonResponse
    {
        $kelas = Siswa::distinct()
            ->orderBy('kelas')
            ->pluck('kelas');

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

    public function exportTemplate(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        return Excel::download(new SiswaTemplateExport(), 'template-import-siswa.xlsx');
    }
}
