<?php

namespace App\Http\Controllers;

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

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

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

        $sktm = new Sktm;
        $sktm->user_id = auth()->user()->id;
        $sktm->keperluan = $request->get('keperluan');
        $sktm->scan_ktp = $request->file('scan_ktp')->storeAs('SKTM/ScanKTP', $ktp, 'public');  
        $sktm->scan_kk = $request->file('scan_kk')->storeAs('SKTM/ScanKK', $kk, 'public');  
        $sktm->status = 'BELUM DI ACC';
        $sktm->save();

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

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

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

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

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

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

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

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

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

    public function ktp($id)
    {
    	$sktm = Sktm::find($id);

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

    public function kk($id)
    {
    	$sktm = Sktm::find($id);

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

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

        $type = 'sktmaccstaff';
        $user = User::find($sktm->user_id);
        $lurah = User::role('lurah')->get(); 
        Notification::send($user, new SktmNotifications($user, $sktm, $type));
        Notification::send($lurah, new SktmNotifications($user, $sktm, $type));


        //Notification::send($user, new SktmNotifications($sktm,$type));

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

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

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

        $type = 'sktmacclurah';
        $user = User::find($sktm->user_id);
        $staff = User::role('staff')->get(); 
        Notification::send($user, new SktmNotifications($user, $sktm, $type));
        Notification::send($staff, new SktmNotifications($user, $sktm, $type));

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

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

        $type = 'sktmacccetak';
        $user = User::find($sktm->user_id);
        Notification::send($user, new SktmNotifications($user, $sktm, $type));

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

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

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

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

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