<?php

namespace App\Http\Controllers;

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $provinces = \Indonesia::allProvinces();
        $pageConfigs = ['pageHeader' => true];
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["link" => "/skmb", "name" => "Surat Keterangan Tidak Berada Ditempat"], ["name" => "Tambah SKMB"]
        ];
        return view('skmb.create',[
            'pageConfigs'=>$pageConfigs,
            'breadcrumbs'=>$breadcrumbs,
            'provinces'=>$provinces,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $request->validate([
            'alamat' => 'required|string|max:255',
            'rt' => 'required',
            'rw' => 'required',
            'desa_kelurahan' => 'required',
            'kecamatan' => 'required',
            'kabupaten_kota' => 'required',
            'provinsi' => 'required',
            'kode_pos' => 'required',
            '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;   

        $skmb = new Skmb;
        $skmb->user_id = auth()->user()->id;
        $skmb->alamat = $request->get('alamat');
        $skmb->rt = $request->get('rt');
        $skmb->rw = $request->get('rw');
        $skmb->desa_kelurahan = $request->get('desa_kelurahan');
        $skmb->kecamatan = $request->get('kecamatan');
        $skmb->kabupaten_kota = $request->get('kabupaten_kota');
        $skmb->provinsi = $request->get('provinsi');
        $skmb->kode_pos = $request->get('kode_pos');
        $skmb->scan_ktp = $request->file('scan_ktp')->storeAs('SKMB/ScanKTP', $ktp, 'public');  
        $skmb->scan_kk = $request->file('scan_kk')->storeAs('SKMB/ScanKK', $kk, 'public');  
        $skmb->status = 'BELUM DI ACC';
        $skmb->save();

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

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

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

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Skmb  $skmb
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $skmb = Skmb::findOrFail($id);
        $provinces = \Indonesia::findProvince($skmb->provinsi);
        $cities = \Indonesia::findCity($skmb->kabupaten_kota);
        $districts = \Indonesia::findDistrict($skmb->kecamatan);
        $villages = \Indonesia::findVillage($skmb->desa_kelurahan);
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["link" => "/skmb", "name" => "Surat Keterangan Tidak Berada Ditempat"], ["name" => "Edit SKMB"]
        ];
        $pageConfigs = ['pageHeader' => true];

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

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

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

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

    public function ktp($id)
    {
    	$skmb = Skmb::find($id);

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

    public function kk($id)
    {
    	$skmb = Skmb::find($id);

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

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

        $type = 'skmbaccstaff';
        $user = User::find($skmb->user_id);
        $lurah = User::role('lurah')->get(); 
        Notification::send($user, new SkmbNotifications($user, $skmb, $type));
        Notification::send($lurah, new SkmbNotifications($user, $skmb, $type));


        //Notification::send($user, new SkmbNotifications($skmb,$type));

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

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

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

        $type = 'skmbacclurah';
        $user = User::find($skmb->user_id);
        $staff = User::role('staff')->get(); 
        Notification::send($user, new SkmbNotifications($user, $skmb, $type));
        Notification::send($staff, new SkmbNotifications($user, $skmb, $type));

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

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

        $type = 'skmbacccetak';
        $user = User::find($skmb->user_id);
        Notification::send($user, new SkmbNotifications($user, $skmb, $type));

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

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

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

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

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