<?php

namespace App\Http\Controllers\Api\Admin;

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

class GuruController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        try {
            $perPage = (int) $request->input('per_page', 7);
            $perPage = in_array($perPage, [5, 7, 10, 25]) ? $perPage : 7;

            $search = trim((string) $request->input('search', ''));

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

            if ($search !== '') {
                $query->where(function ($q) use ($search) {
                    $q->where('id_guru', 'like', "%{$search}%")
                        ->orWhere('nama_guru', 'like', "%{$search}%");
                });
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Data guru berhasil dimuat.',
                'data' => $guru->items(),
                'current_page' => $guru->currentPage(),
                'last_page' => $guru->lastPage(),
                'per_page' => $guru->perPage(),
                'total' => $guru->total(),
            ], 200);
            
        } catch (Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat memuat data guru.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama_guru' => 'required|string|max:255',
            'username'  => 'required|string|max:255|unique:users,username',
            'email'     => 'required|string|email|max:255|unique:users,email',
            'password'  => 'required|string|min:8',
        ]);

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

        DB::beginTransaction();

        try {
            // Create User Akun
            $user = User::create([
                'name'     => $request->nama_guru,
                'username' => $request->username,
                'email'    => $request->email,
                'password' => Hash::make($request->password),
                'role'     => 'admin', 
            ]);

            // Create Data Guru terikat dengan user_id
            $guru = Guru::create([
                'user_id'   => $user->id,
                'nama_guru' => $request->nama_guru,
            ]);

            DB::commit();

            $guru->load('user');

            return response()->json([
                'success' => true,
                'message' => 'Data guru dan akun login berhasil disimpan.',
                'data'    => $guru
            ], 201);

        } catch (Throwable $e) {
            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat menyimpan data guru.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        try {
            $guru = Guru::with('user')->find($id);

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

            return response()->json([
                'success' => true,
                'message' => 'Detail data guru berhasil ditemukan.',
                'data'    => $guru
            ], 200);

        } catch (Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat mengambil detail data guru.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            $guru = Guru::find($id);

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

            $validator = Validator::make($request->all(), [
                'nama_guru' => 'required|string|max:255',
            ]);

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

            DB::beginTransaction();

            $guru->update([
                'nama_guru' => $request->nama_guru
            ]);

            if ($guru->user) {
                $guru->user->update([
                    'name' => $request->nama_guru
                ]);
            }

            DB::commit();
            $guru->load('user');

            return response()->json([
                'success' => true,
                'message' => 'Data guru berhasil diperbarui.',
                'data'    => $guru
            ], 200);

        } catch (Throwable $e) {
            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat memperbarui data guru.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $guru = Guru::find($id);

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

            DB::beginTransaction();

            if ($guru->user_id) {
                User::destroy($guru->user_id);
            } 
            
            $guru->delete();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Data guru dan akun login berhasil dihapus.'
            ], 200);

        } catch (Throwable $e) {
            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => 'Data guru tidak dapat dihapus atau terjadi kesalahan server.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }
}