<?php

namespace App\Http\Controllers;

use App\Skbpm;
use App\User;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Notifications\SkbpmNotifications;
use Illuminate\Support\Facades\Notification;
use Spatie\Permission\Traits\HasRoles;
use Carbon\Carbon;

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

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

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

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

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

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

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

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

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

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

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

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

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

    public function ktp($id)
    {
    	$skbpm = Skbpm::find($id);

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

    public function kk($id)
    {
    	$skbpm = Skbpm::find($id);

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

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

        $type = 'skbpmaccstaff';
        $user = User::find($skbpm->user_id);
        $lurah = User::role('lurah')->get(); 
        Notification::send($user, new SkbpmNotifications($user, $skbpm, $type));
        Notification::send($lurah, new SkbpmNotifications($user, $skbpm, $type));

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

    public function acclurah(Skbpm $skbpm, $id)
    {
        //
        $skbpm = Skbpm::findOrFail($id);
        $skbpm->status = 'SUDAH ACC LURAH';
        $skbpm->tanggal = Carbon::now()->isoFormat('D MMMM Y');
        $skbpm->save();

        $type = 'skbpmacclurah';
        $user = User::find($skbpm->user_id);
        $staff = User::role('staff')->get(); 
        Notification::send($user, new SkbpmNotifications($user, $skbpm, $type));
        Notification::send($staff, new SkbpmNotifications($user, $skbpm, $type));

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

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

        $type = 'skbpmacccetak';
        $user = User::find($skbpm->user_id);
        Notification::send($user, new SkbpmNotifications($user, $skbpm, $type));
        return redirect()->route('skbpm.index');
    }

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

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

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

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