<?php

namespace App\Http\Controllers;

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

class SkpdController 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;
            $skpd = Skpd::where('user_id', $id)->get();
        } else {
            $skpd = Skpd::all();
        }
        
        $pageConfigs = ['pageHeader' => true];
        $breadcrumbs = [
            ["link" => "/", "name" => "Home"],["name" => "Surat Keterangan Pindah Daerah"]
        ];
        return view('skpd.index',[
            'pageConfigs'=>$pageConfigs,
            'breadcrumbs'=>$breadcrumbs,
            'skpd' => $skpd
        ]);
    }

    /**
     * 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" => "/skpd", "name" => "Surat Keterangan Pindah Daerah"], ["name" => "Tambah SKPD"]
        ];
        return view('skpd.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',
            'tanggal_pindah' => 'required',
            'alasan' => '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;   

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

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

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

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

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

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

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

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

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

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

    public function ktp($id)
    {
    	$skpd = Skpd::find($id);

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

    public function kk($id)
    {
    	$skpd = Skpd::find($id);

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

    public function fotousaha($id)
    {
    	$skpd = Skpd::find($id);

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

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

        $type = 'skpdaccstaff';
        $user = User::find($skpd->user_id);
        $lurah = User::role('lurah')->get(); 
        Notification::send($user, new SkpdNotifications($user, $skpd, $type));
        Notification::send($lurah, new SkpdNotifications($user, $skpd, $type));

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

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

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

        $type = 'skpdacclurah';
        $user = User::find($skpd->user_id);
        $staff = User::role('staff')->get(); 
        Notification::send($user, new SkpdNotifications($user, $skpd, $type));
        Notification::send($staff, new SkpdNotifications($user, $skpd, $type));

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

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

        $type = 'skpdacccetak';
        $user = User::find($skpd->user_id);
        Notification::send($user, new SkpdNotifications($user, $skpd, $type));

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

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

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

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

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