<?php

namespace App\Http\Controllers;

use App\Skjd;
use App\User;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Notifications\SkjdNotifications;
use Illuminate\Support\Facades\Notification;
use Carbon\Carbon;

class SkjdController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:lihat surat', ['only' => ['index', 'ktp', 'kk']]);
        $this->middleware('permission:tambah surat', ['only' => ['create', 'store']]);
        $this->middleware('permission:edit keterangan surat', ['only' => ['edit', 'update']]);
        $this->middleware('permission:acc pengajuan surat', ['only' => ['accstaff']]);
        $this->middleware('permission:acc validasi surat', ['only' => ['acclurah']]);
        $this->middleware('permission:acc cetak surat', ['only' => ['acccetak']]);
        $this->middleware('permission:print surat', ['only' => ['surat']]);
        $this->middleware('permission:hapus surat', ['only' => ['destroy']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (auth()->user()->roles->first()->name == 'warga') {
            $id = auth()->user()->id;
            $skjd = Skjd::where('user_id', $id)->get();
        } else {
            $skjd = Skjd::all();
        }

        
        $pageConfigs = ['pageHeader' => true];
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["name" => "Surat Keterangan Janda / Duda"]
        ];
        return view('skjd.index',[
            'pageConfigs'=>$pageConfigs,
            'breadcrumbs'=>$breadcrumbs,
            'skjd' => $skjd
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $pageConfigs = ['pageHeader' => true];
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["link" => "/skjd", "name" => "Surat Keterangan Janda / Duda"], ["name" => "Tambah SKJD"]
        ];
        return view('skjd.create',[
            'pageConfigs'=>$pageConfigs,
            'breadcrumbs'=>$breadcrumbs,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $request->validate([
            'jumlah_anak' => 'required|string|max:255',
            'nama_suami_istri' => 'required|string|max:255',
            'tanggal_meninggal' => 'required|string|max:255',
            'tempat_meninggal' => 'required|string|max:255',
            'instansi' => 'required|string|max:255',
            'scan_ktp' => 'required|mimes:jpg,png|max:2048',
            'scan_kk' => 'required|mimes:jpg,png|max:2048',
        ], [
            'scan_ktp.mimes' => 'Dokumen harus berupa file dengan jenis: jpg, png.',
            'scan_ktp.max' => 'Dokumen tidak boleh lebih besar dari 2Mb.',
            'scan_kk.mimes' => 'Dokumen harus berupa file dengan jenis: jpg, png.',
            'scan_kk.max' => 'Dokumen tidak boleh lebih besar dari 2Mb.',
        ]);

        $random = Str::random(10);
        
        $filektp = $request->file('scan_ktp')->getClientOriginalName();
        $extension = pathinfo($filektp, PATHINFO_EXTENSION);
        $ktp = 'KTP-'. auth()->user()->nik .'_'. $random .'.'. $extension;   

        $filekk = $request->file('scan_kk')->getClientOriginalName();
        $extension = pathinfo($filekk, PATHINFO_EXTENSION);
        $kk = 'KK-'. auth()->user()->nik .'_'. $random .'.'. $extension;   

        $skjd = new Skjd;
        $skjd->user_id = auth()->user()->id;
        $skjd->jumlah_anak = $request->get('jumlah_anak');
        $skjd->nama_suami_istri = $request->get('nama_suami_istri');
        $skjd->tanggal_meninggal = $request->get('tanggal_meninggal');
        $skjd->tempat_meninggal = $request->get('tempat_meninggal');
        $skjd->instansi = $request->get('instansi');
        $skjd->scan_ktp = $request->file('scan_ktp')->storeAs('SKJD/ScanKTP', $ktp, 'public');  
        $skjd->scan_kk = $request->file('scan_kk')->storeAs('SKJD/ScanKK', $kk, 'public');  
        $skjd->status = 'BELUM DI ACC';
        $skjd->save();

        $type = 'skjd';
        $user = User::find($skjd->user_id);
        $admins = User::role('staff')->get(); 
        Notification::send($admins, new SkjdNotifications($user, $skjd, $type));

        Alert::success('Berhasil', 'SKJD  telah ditambahkan!');

        return redirect()->route('skjd.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Skjd  $skjd
     * @return \Illuminate\Http\Response
     */
    public function show(Skjd $skjd)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Skjd  $skjd
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $skjd = Skjd::findOrFail($id);
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["link" => "/skjd", "name" => "Surat Keterangan Janda / Duda"], ["name" => "Edit SKJD"]
        ];
        $pageConfigs = ['pageHeader' => true];

        return view('skjd.edit',[
            'pageConfigs'=>$pageConfigs,
            'breadcrumbs'=>$breadcrumbs,
            'skjd' => $skjd,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Skjd  $skjd
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $request->validate([
            'keterangan' => 'required|string|max:255',
        ]);
        
        $skjd = Skjd::findOrFail($id);
        $skjd->keterangan = $request->get('keterangan');

        $skjd->save();
        
        Alert::success('Berhasil', 'Keterangan Berhasil diperbaharui!');

        return redirect()->route('skjd.index');
    }

    public function ktp($id)
    {
    	$skjd = Skjd::find($id);

	    return response()->json([
	      'data' => $skjd
	    ]);
    }

    public function kk($id)
    {
    	$skjd = Skjd::find($id);

	    return response()->json([
	      'data' => $skjd
	    ]);
    }

    public function accstaff(Skjd $skjd, $id)
    {
        //
        $skjd = Skjd::findOrFail($id);
        $skjd->status = 'SUDAH ACC STAFF';
        $skjd->save();

        $type = 'skjdaccstaff';
        $user = User::find($skjd->user_id);
        $lurah = User::role('lurah')->get(); 
        Notification::send($user, new SkjdNotifications($user, $skjd, $type));
        Notification::send($lurah, new SkjdNotifications($user, $skjd, $type));


        //Notification::send($user, new SkjdNotifications($skjd,$type));

        return redirect()->route('skjd.index');
    }

    public function acclurah(Skjd $skjd, $id)
    {
        //
        $no = Skjd::orderBy('no_surat', 'desc')->first();

        $skjd = Skjd::findOrFail($id);
        $skjd->status = 'SUDAH ACC LURAH';
        $skjd->no_surat = $no->no_surat+1;
        $skjd->tanggal = Carbon::now()->isoFormat('D MMMM Y');
        $skjd->save();

        $type = 'skjdacclurah';
        $user = User::find($skjd->user_id);
        $staff = User::role('staff')->get(); 
        Notification::send($user, new SkjdNotifications($user, $skjd, $type));
        Notification::send($staff, new SkjdNotifications($user, $skjd, $type));

        return redirect()->route('skjd.index');
    }

    public function acccetak(Skjd $skjd, $id)
    {
        //
        $skjd = Skjd::findOrFail($id);
        $skjd->status = 'SURAT SUDAH DICETAK';
        $skjd->save();

        $type = 'skjdacccetak';
        $user = User::find($skjd->user_id);
        Notification::send($user, new SkjdNotifications($user, $skjd, $type));

        return redirect()->route('skjd.index');
    }

    public function surat(Skjd $skjd, $id)
    {
        //
        $skjd = Skjd::findOrFail($id);
        $provinces = \Indonesia::findProvince($skjd->user->profil->provinsi);
        $cities = \Indonesia::findCity($skjd->user->profil->kabupaten_kota);
        $districts = \Indonesia::findDistrict($skjd->user->profil->kecamatan);
        $villages = \Indonesia::findVillage($skjd->user->profil->desa_kelurahan);
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["link" => "/skjd", "name" => "Surat Keterangan Janda / Duda"], ["name" => "Surat"]
        ];
        $pageConfigs = ['pageHeader' => true];

        return view('skjd.surat',[
            'pageConfigs'=>$pageConfigs,
            'breadcrumbs'=>$breadcrumbs,
            'skjd' => $skjd,
            'provinces' => $provinces,
            'cities' => $cities,
            'districts' => $districts,
            'villages' => $villages,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Skjd  $skjd
     * @return \Illuminate\Http\Response
     */
    public function destroy(Skjd $skjd, $id)
    {
        //
        $skjd = Skjd::findOrFail($id);
        if(file_exists(storage_path('app/public/' . $skjd->scan_ktp))){
            Storage::delete('public/' . $skjd->scan_ktp); 
        }
        if(file_exists(storage_path('app/public/' . $skjd->scan_kk))){
            Storage::delete('public/' . $skjd->scan_kk); 
        }
        $skjd->delete();

        return redirect()->route('skjd.index');
    }
}
