<?php

//redirect ke folder
namespace App\Http\Controllers\Admin\Perpus;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\Master\DaerahModel;
use App\Models\Perpus\SekolahModel;
use App\Models\Perpus\JurusanModel;
use App\Models\Master\PeriodeModel;

use DB;
use Illuminate\Support\Facades\Hash;
use Str;
use File;

class SekolahController extends Controller
{
    private $views      = 'admin/perpus/sekolah';
    private $url        = 'admin/master/sekolah';
    private $url2        = 'admin/master/sekolah/jurusan';
    private $url3        = 'admin/master/sekolah/tingkat';
    private $title      = 'Halaman Master Sekolah';

public function __construct()
    {
        createLogActivity();
        // Di isi Construct. Biasanya saya isi untuk Model

        $this->mDaerah         = new DaerahModel();
        $this->mPerpusSekolah         = new SekolahModel();
        $this->mPerpusJurusan         = new JurusanModel();
        $this->mPeriode               = New PeriodeModel();
    
    }

    public function index()
    {
        $perpus_sekolah = $this->mPerpusSekolah->get();
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Sekolah',
            'perpus_sekolah'          => $perpus_sekolah,
        ];

        // View, menuju file index di dalam folder = admin/mPerpusSekolah
        return view($this->views . "/index", $data);
    }

    public function create()
    {
        $daerah = $this->mDaerah->get();
        $periode    = $this->mPeriode->get();

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Tambah Data Sekolah',
            'daerah'        => $daerah,
            'periode'       => $periode,
        ];

        // View, menuju file index di dalam folder = admin/mPerpusSekolah
        return view($this->views . "/create", $data);
    }

    public function store(Request $request)
    {
        $validateData = $request->validate([
            'photo'                    => 'required|mimes:jpg,jpeg,png',
            'gambar'                   => 'required|mimes:jpg,jpeg,png'
        ],[
            'photo.required'           => 'Pilih file terlebih dahulu',
            'gambar.required'          => 'Pilih file terlebih dahulu',
            'photo.mimes'              => 'Format data harus jpg, jpeg, atau png',
            'gambar.mimes'             => 'Format data harus jpg, jpeg, atau png',
        ]);
        
        $sekolah = $this->mPerpusSekolah->where('npsn', $request->npsn)->first();

        if ($sekolah) {
            return redirect("$this->url")->with('gagal', 'Sekolah sudah terdaftar');
        }

        if ($request->hasFile('photo')) {
            $file       = $request->file('photo');
            $fileName   = Str::uuid()."-".time().".".$file->extension();
            // $file->move(public_path(). "/upload/logo_sekolah/", $fileName);
            $file->move( "upload/logo_sekolah/", $fileName);
        }
        if ($request->hasFile('gambar')) {
            $file       = $request->file('gambar');
            $fileNama   = Str::uuid()."-".time().".".$file->extension();
            // $file->move(public_path(). "/upload/logo_sekolah/", $fileNama);
            $file->move( "upload/logo_gambar/", $fileNama);
        }

        $dataPerpusSekolah = [
            'idMDaerah'     => $request->idMDaerah,
            'idPPeriode'    => $request->idPPeriode,
            'nama'          => $request->nama,
            'alamat'        => $request->alamat ?? '',
            'logo'          => $fileName ?? '',
            'logo_gambar'   => $fileNama ?? '',
            'telp'          => $request->telp ?? '',
            'web'           => $request->web ?? '',
            'email'         => $request->email ?? '',
            'npsn'          => $request->npsn,
        ];
        $this->mPerpusSekolah->create($dataPerpusSekolah);

        return redirect("$this->url")->with('sukses', 'Data Sekolah berhasil di tambahkan');
    }

    public function show($id)
    {
        // Get Data
        $perpus_jurusan = $this->mPerpusJurusan->where('idPSekolah', $id)->first();
        $perpus_sekolah      = $this->mPerpusSekolah->where('id', $id)->first();

        $data = [
            'title'             => $this->title,
            'url'               => $this->url,
            'url2'               => $this->url2,
            'page'              => 'Detail Data Sekolah',
            'id'                => $id,
            'perpus_jurusan'    => $perpus_jurusan,
            'perpus_sekolah'    => $perpus_sekolah,
        ];
        return view($this->views . "/show", $data);
    }

    public function edit($id)
    {
        // Get Data
        $perpus_sekolah      = $this->mPerpusSekolah->where('id', $id)->first();
        $daerah = $this->mDaerah->get();

        $data = [
            'title'             => $this->title,
            'url'               => $this->url,
            'page'              => 'Edit Data Sekolah',
            'id'                => $id,
            'perpus_sekolah'    => $perpus_sekolah,
            'daerah'            => $daerah,
        ];
        return view($this->views . "/edit", $data);
    }

    public function update(Request $request, $id)
    {
        try {
            // Validasi data
            $validateData = $request->validate([
                'nama'   => 'required',
                'telp'   => 'required',
                'web'   => 'required',
                'email'   => 'required',
            ],[
                'nama.required'    => 'Nama Sekolah kosong',
                'telp.required'    => 'Telpon Sekolah kosong',
                'web.required'    => 'Alamat web Sekolah kosong',
                'email.required'    => 'Email Sekolah kosong',
            ]);

            // Handle file photo
            if ($request->hasFile('photo')) {
                $file = $request->file('photo');
                $fileName = Str::uuid()."-".time().".".$file->extension();
                $file->move("upload/logo_sekolah/", $fileName);
                $validateData['photo'] = $fileName; // Menyimpan nama file ke dalam data yang akan diupdate
            }

            // Handle file gambar
            if ($request->hasFile('gambar')) {
                $file = $request->file('gambar');
                $fileNama = Str::uuid()."-".time().".".$file->extension();
                $file->move("upload/logo_gambar/", $fileNama);
                $validateData['gambar'] = $fileNama; // Menyimpan nama file ke dalam data yang akan diupdate
            }

            // Data yang akan diupdate
            $dataPerpusSekolah = [
                'nama'   => $request->nama,
                'telp'   => $request->telp,
                'web'    => $request->web,
                'email'  => $request->email,
            ];

            // Jika photo dan gambar diupload, tambahkan ke data yang diupdate
            if (isset($validateData['photo'])) {
                $dataPerpusSekolah['photo'] = $validateData['photo'];
            }
            if (isset($validateData['gambar'])) {
                $dataPerpusSekolah['gambar'] = $validateData['gambar'];
            }

            // Update data di database
            $this->mPerpusSekolah->where('id', $id)->update($dataPerpusSekolah);

            // Berikan respon sukses
            return redirect("$this->url")->with('sukses', 'Data Sekolah berhasil di edit');
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Jika terjadi kesalahan validasi, redirect kembali dan tampilkan error
            return redirect()->back()->withErrors($e->validator)->withInput();
        } catch (\Exception $e) {
            // Jika ada kesalahan lain, tampilkan pesan gagal
            return redirect()->back()->with('gagal', 'Terjadi kesalahan saat mengedit data. Silakan coba lagi.');
        }
    }

}
