<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class SettingController extends Controller
{
    /**
     * Display the settings edit form.
     *
     * @return \Inertia\Response
     */
    public function index()
    {
        $setting = Setting::firstOrCreate([], [
            'app_name' => config('app.name', 'Ujian Online'),
            'app_logo' => null,
        ]);

        return inertia('Admin/Settings/Index', [
            'setting' => $setting,
        ]);
    }

    /**
     * Update the settings.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        //validate request
        $request->validate([
            'app_name' => 'required|string|max:255',
            'app_logo' => 'nullable|image|mimes:jpeg,jpg,png,webp|max:2048',
        ]);

        $setting = Setting::firstOrCreate([], [
            'app_name' => config('app.name', 'Ujian Online'),
            'app_logo' => null,
        ]);

        //check if image is uploaded
        if ($request->hasFile('app_logo')) {

            //upload new image
            $image = $request->file('app_logo');
            $image->storeAs('settings', $image->hashName(), 'public');

            //delete old image
            if ($setting->app_logo) {
                Storage::disk('public')->delete('settings/' . basename($setting->app_logo));
            }

            //update setting with new image
            $setting->update([
                'app_name' => $request->app_name,
                'app_logo' => $image->hashName(),
            ]);

        } else {

            //update setting without image
            $setting->update([
                'app_name' => $request->app_name,
            ]);

        }

        //redirect
        return redirect()->route('admin.settings.index')->with('success', 'Pengaturan Berhasil Diupdate!.');
    }

    /**
     * Reset all academic data (lessons, students, classrooms, teachers, question banks, exams, exam sessions, reports).
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function resetData(Request $request)
    {
        $request->validate([
            'pin' => 'required|string',
        ]);

        // Verify PIN
        if ($request->pin !== '12345678') {
            return back()->withErrors(['pin' => 'PIN yang dimasukkan salah.']);
        }

        // Disable foreign key checks, truncate tables, then re-enable
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        // Laporan / Grades (reports)
        DB::table('grades')->truncate();

        // Jawaban siswa
        DB::table('answers')->truncate();

        // Enrollments (exam_groups)
        DB::table('exam_groups')->truncate();

        // Sesi Ujian
        DB::table('exam_sessions')->truncate();

        // Relasi soal-ujian (pivot)
        DB::table('exam_questions')->truncate();

        // Ujian
        DB::table('exams')->truncate();

        // Bank Soal
        DB::table('questions')->truncate();

        // Siswa
        DB::table('students')->truncate();

        // Kelas
        DB::table('classrooms')->truncate();

        // Mata Pelajaran
        DB::table('lessons')->truncate();

        // User guru (hanya role guru, bukan admin)
        DB::table('users')->where('role', 'guru')->delete();

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        return redirect()->route('admin.settings.index')->with('success', 'Semua data berhasil direset!');
    }
}
