<?php

namespace App\Http\Controllers;

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

class SkdController 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;
            $skd = Skd::where('user_id', $id)->get();
        } else {
            $skd = Skd::all();
        }

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $pageConfigs = ['pageHeader' => true];
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["link" => "/skd", "name" => "Surat Keterangan Domisili"], ["name" => "Tambah SKD"]
        ];
        return view('skd.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([
            '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;   

        $skd = new Skd;
        $skd->user_id = auth()->user()->id;
        $skd->scan_ktp = $request->file('scan_ktp')->storeAs('SKD/ScanKTP', $ktp, 'public');  
        $skd->scan_kk = $request->file('scan_kk')->storeAs('SKD/ScanKK', $kk, 'public');  
        $skd->status = 'BELUM DI ACC';
        $skd->save();

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

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

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

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

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

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

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

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

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

    public function ktp($id)
    {
    	$skd = Skd::find($id);

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

    public function kk($id)
    {
    	$skd = Skd::find($id);

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

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

        $type = 'skdaccstaff';
        $user = User::find($skd->user_id);
        $lurah = User::role('lurah')->get(); 
        Notification::send($user, new SkdNotifications($user, $skd, $type));
        Notification::send($lurah, new SkdNotifications($user, $skd, $type));

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

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

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

        $type = 'skdacclurah';
        $user = User::find($skd->user_id);
        $staff = User::role('staff')->get(); 
        Notification::send($user, new SkdNotifications($user, $skd, $type));
        Notification::send($staff, new SkdNotifications($user, $skd, $type));

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

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

        $type = 'skdacccetak';
        $user = User::find($skd->user_id);
        Notification::send($user, new SkdNotifications($user, $skd, $type));

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

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

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

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

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