<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Siswa;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Throwable;

class SiswaController extends Controller
{
    public function index(Request $request)
    {
        try {
            $perPage = (int) $request->input('per_page', 7);
            $perPage = in_array($perPage, [5, 7, 10, 25, 50, 100]) ? $perPage : 7;
            $search = trim((string) $request->input('search', ''));

            $query = Siswa::with('user')->orderBy('id', 'desc');

            if ($search !== '') {
                $query->where(function ($q) use ($search) {
                    $q->where('nama_lengkap', 'like', "%{$search}%")
                        ->orWhere('nisn', 'like', "%{$search}%")
                        ->orWhere('kelas', 'like', "%{$search}%")
                        ->orWhereHas('user', function ($user) use ($search) {
                            $user->where('username', 'like', "%{$search}%");
                        });
                });
            }

            $siswa = $query->paginate($perPage);

            return response()->json(['success' => true, 'data' => $siswa], 200);
        } catch (Throwable $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username'     => ['required', Rule::unique(User::class, 'username')],
            'password'     => 'required|min:6',
            'nama_lengkap' => 'required',
            'nisn'         => ['required', Rule::unique(Siswa::class, 'nisn')],
            'kelas'        => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => 'Validasi gagal', 'errors' => $validator->errors()], 422);
        }

        DB::beginTransaction();
        try {
            $usernameClean = str_replace(' ', '', $request->username);
            $otomatisEmail = strtolower($usernameClean) . '@gmail.com';

            $user = User::create([
                'name'     => $request->nama_lengkap, 
                'username' => $request->username,
                'email'    => $otomatisEmail,
                'password' => Hash::make($request->password),
                'role'     => 'siswa',
            ]);

            Siswa::create([
                'user_id'      => $user->id,
                'nama_lengkap' => $request->nama_lengkap,
                'nisn'         => $request->nisn,
                'kelas'        => $request->kelas,
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data siswa berhasil ditambahkan.'], 201);
        } catch (\Throwable $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Gagal menyimpan data.', 'error' => $e->getMessage()], 500);
        }
    }

    public function show($id)
    {
        try {
            $siswa = Siswa::with('user')->find($id);

            if (!$siswa) {
                return response()->json(['success' => false, 'message' => 'Data siswa tidak ditemukan.'], 404);
            }

            return response()->json(['success' => true, 'data' => $siswa], 200);
        } catch (Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Gagal memuat rincian.', 'error' => $e->getMessage()], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $siswa = Siswa::find($id);
        
        if (!$siswa) {
            return response()->json(['success' => false, 'message' => 'Data siswa tidak ditemukan.'], 404);
        }

        $validator = Validator::make($request->all(), [
            'username'     => [
                'nullable',
                Rule::unique(User::class, 'username')->ignore($siswa->user_id)
            ],
            'nisn'         => [
                'required',
                Rule::unique(Siswa::class, 'nisn')->ignore($siswa->id)
            ],
            'nama_lengkap' => 'required',
            'kelas'        => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => 'Validasi gagal', 'errors' => $validator->errors()], 422);
        }

        DB::beginTransaction();
        try {
            if ($siswa->user_id) {
                $user = User::find($siswa->user_id);
                if ($user) {
                    $user->name = $request->nama_lengkap;
                    
                    if ($request->filled('username')) {
                        $user->username = $request->username;
                        $usernameClean = str_replace(' ', '', $request->username);
                        $user->email = strtolower($usernameClean) . '@gmail.com';
                    }

                    if ($request->filled('password')) {
                        $user->password = Hash::make($request->password);
                    }
                    $user->save();
                }
            }

            $siswa->update([
                'nama_lengkap' => $request->nama_lengkap,
                'nisn'         => $request->nisn,
                'kelas'        => $request->kelas
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Data siswa berhasil diperbarui.',
                'data'    => $siswa->load('user')
            ], 200);
        } catch (Throwable $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Gagal memperbarui data.', 'error' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $siswa = Siswa::find($id);

            if (!$siswa) {
                return response()->json(['success' => false, 'message' => 'Data tidak ditemukan.'], 404);
            }

            if ($siswa->user_id) {
                $userId = $siswa->user_id;
                $siswa->delete(); 
                User::destroy($userId); 
            } else {
                $siswa->delete();
            }

            return response()->json(['success' => true, 'message' => 'Data berhasil dihapus.'], 200);
        } catch (Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Gagal menghapus.', 'error' => $e->getMessage()], 500);
        }
    }
}