<?php

namespace App\Http\Controllers;

use App\Models\Kelas;
use App\Models\Transaksi;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class TransaksiController extends Controller
{
    public function index(Request $request)
    {
        // Filter List & Initial Query
        $filters = $request->all();
        $query = Transaksi::query();
        $result_filters = [];

        // Has Query
        if ($filters) {
            if ($request->has('nis_siswa') && $request->nis_siswa != '') {
                // Find User ID
                $siswa = User::where('nis', $request->nis_siswa)->first();
                if($siswa){
                    // Push User ID
                    $filters['user_id'] = $siswa['id'];
                    // Remove nis_siswa from array
                    unset($filters['nis_siswa']);

                    $result_filters['nis_siswa'] = $siswa['nis'] . " - " . $siswa['nama'];
                }else{
                    return back()->with('failed', "NIS ". $request->nis_siswa . " Tidak ditemukan");
                }
            }
            foreach ($filters as $key => $val) {
                if ($key != 'start_date' && $key != 'end_date' && $key != 'nis_siswa' && $key != 'keterangan') {
                    // Common Query
                    $query->where($key, $val);

                    if($key == 'kelas_id'){
                        $kelas = Kelas::where('id', $val)->first();
                        if($kelas){
                            $result_filters['kelas'] = $kelas['kelas'];
                        }
                    }

                    if($key == 'status'){
                        $result_filters['status'] = ucfirst($val);
                    }
                }
            }
            // Special Query

            //// DateRange && Keterangan
            if ($request->only(['start_date', 'end_date', 'keterangan']) && ($request->start_date != '' && $request->end_date != '' && $request->keterangan != '')) {
                $query->whereBetween('waktu_terlambat', [$request->start_date, $request->end_date])->where('keterangan', 'like', '%' . $request->keterangan . '%');
                $result_filters['date_range'] = Carbon::parse($request->start_date)->format('d F Y') . " - " . Carbon::parse($request->end_date)->format('d F Y');
                $result_filters['keterangan'] = ucfirst($request->keterangan);
            }
            //// DateRange Only
            elseif ($request->only(['start_date', 'end_date']) && ($request->start_date != '' && $request->end_date != '')) {
                $query->whereBetween('waktu_terlambat', [$request->start_date, $request->end_date]);
                $result_filters['date_range'] = Carbon::parse($request->start_date)->format('d F Y') . " - " . Carbon::parse($request->end_date)->format('d F Y');            }
            //// Keterangan Only
            elseif ($request->only(['keterangan']) && $request->keterangan != '') {
                $query->where('keterangan', 'like', '%' . $request->keterangan . '%');
                $result_filters['keterangan'] = ucfirst($request->keterangan);
            }
            // Results
            $terlambats = $query->latest()->get();
        }
        // No Query
        else {
            $terlambats = Transaksi::with('user', 'disetujui_oleh')
                ->latest()
                ->get();
        }

        // dd($result_filters);

        // // Blade
        return view('admin.transaksi.terlambat.data_terlambat', ['title' => 'Data Keterlambatan'], compact('terlambats', 'result_filters'));
    }

    public function tambah()
    {
        return view('admin.transaksi.terlambat.tambah_terlambat', ['title' => 'Tambah Keterlambatan']);
    }

    public function checkNis(Request $request)
    {
        $siswa = User::with('kelas')
            ->where('nis', $request->nis)
            ->first();
        if ($siswa) {
            return response()->json($siswa, 200);
        } else {
            return response()->json('NIS Tidak Ditemukan', 404);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'nis' => 'required',
            'keterangan' => 'required',
            'jam_ke' => 'required',
            'decision' => 'required',
        ]);

        $today = Carbon::now();
        $siswa = User::where('nis', $request->nis)->first();
        if ($siswa) {
            $terlambat = Transaksi::create([
                'user_id' => $siswa->id,
                'kelas_id' => $siswa->kelas_id,
                'disetujui_oleh_id' => null,
                'status' => 'pending',
                'jam_ke' => $request->jam_ke,
                'keterangan' => $request->keterangan,
                'waktu_terlambat' => $today,
            ]);
            return redirect('/')->with('sweetAlertTerlambat', 'Surat Keterlambatan Berhasil Dibuat');
        }
    }

    public function print($id)
    {
        $terlambat = Transaksi::with('user', 'disetujui_oleh')
            ->where('id', $id)
            ->first();
        if ($terlambat && $terlambat['status'] == 'disetujui') {
            return view('admin.transaksi.terlambat.cetak_terlambat', ['title' => 'Cetak Struk'], compact('terlambat'));
        } else {
            return back()->with('failed', 'Surat tersebut di tolak oleh guru piket');
        }
    }

    public function export(Request $request)
    {
        // Filter List & Initial Query
        $filters = $request->all();
        $query = Transaksi::query();

        // Has Query
        if ($filters) {
            if ($request->has('nis_siswa') && $request->nis_siswa != '') {
                // Find User ID
                $siswa = User::where('nis', $request->nis_siswa)->first();
                // Push User ID
                $filters['user_id'] = $siswa['id'];
                // Remove nis_siswa from array
                unset($filters['nis_siswa']);
            }
            foreach ($filters as $key => $val) {
                if ($key != 'start_date' && $key != 'end_date' && $key != 'nis_siswa' && $key != 'keterangan') {
                    // Common Query
                    $query->where($key, $val);
                }
            }
            // Special Query

            //// DateRange && Keterangan
            if ($request->only(['start_date', 'end_date', 'keterangan']) && ($request->start_date != '' && $request->end_date != '' && $request->keterangan != '')) {
                $query->whereBetween('waktu_terlambat', [$request->start_date, $request->end_date])->where('keterangan', 'like', '%' . $request->keterangan . '%');
            }
            //// DateRange Only
            elseif ($request->only(['start_date', 'end_date']) && ($request->start_date != '' && $request->end_date != '')) {
                $query->whereBetween('waktu_terlambat', [$request->start_date, $request->end_date]);
            }
            //// Keterangan Only
            elseif ($request->only(['keterangan']) && $request->keterangan != '') {
                $query->where('keterangan', 'like', '%' . $request->keterangan . '%');
            }
            // Results
            $terlambats = $query->latest()->get();
        }
        // No Query
        else {
            $terlambats = Transaksi::with('user', 'disetujui_oleh')
                ->latest()
                ->get();
        }

        // Passing Query Data
        //// Kelas
        if ($request->has('kelas_id')) {
            $kelas = Kelas::where('id', $request->kelas_id)->first();
        } else {
            $kelas = null;
        }
        //// DateRange
        if ($request->has('start_date') && $request->has('end_date') && ($request->start_date != '' && $request->end_date != '')) {
            $rentang_tanggal = date_format(date_create($request->start_date), 'd M Y') . ' - ' . date_format(date_create($request->end_date), 'd M Y');
        } else {
            $rentang_tanggal = null;
        }
        $filter_result = [
            'NIS' => $request->has('nis_siswa') ? $request->nis_siswa : null,
            'Rentang Tanggal' => $rentang_tanggal,
            'Kelas' => $kelas,
            'Alasan' => $request->has('keterangan') ? $request->keterangan : null,
        ];

        $title = 'Data Keterlambatan - ' . date_format(date_create(Carbon::now()), 'd M Y');

        // Blade
        return view('admin.transaksi.terlambat.export_terlambat', compact('terlambats', 'filter_result', 'title'));
    }

    public function destroy(Request $request)
    {
        $terlambat = Transaksi::where('id', $request->delete_id)->first();
        if ($terlambat) {
            $terlambat->delete();
            return back()->with('success', 'Data Keterlambatan Berhasil Dihapus');
        }
    }

    public function findSiswaNis(Request $request)
    {
        $final_result = [];
        $results = User::where('nama', 'LIKE', '%' . $request->search . '%')
            ->orWhere('nis', 'LIKE', '%' . $request->search . '%')
            ->get();
        foreach ($results as $item){
            if($item->kelas_id == 37 || $item->kelas_id == 41){
                //
            }else{
                array_push($final_result, $item);
            }
        }
        return response()->json($final_result, 200);
    }

    public function approve(Request $request){
        $telat = Transaksi::where('id', $request->approve_id)->first();
        if($telat){
            $telat->update([
                'status' => $request->decision,
                'disetujui_oleh_id' => auth()->user()->id,
            ]);
            if($request->decision == 'disetujui'){
                $targetUrl = 'cetak-terlambat/'. $telat->id;
                return back()->with('targetUrl', $targetUrl);
            }else{
                return back()->with('failed', 'Surat Keterlambatan Siswa Ditolak');
            }
        }
    }
}
