<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Layanan_VerifikatorAddRequest;
use App\Http\Requests\Layanan_VerifikatorEditRequest;
use App\Models\Layanan_Verifikator;
use Illuminate\Http\Request;
use \PDF;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\LayananVerifikatorListExport;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Exception;
class Layanan_VerifikatorController extends Controller
{
	

	/**
     * List table records
	 * @param  \Illuminate\Http\Request
     * @param string $fieldname //filter records by a table field
     * @param string $fieldvalue //filter value
     * @return \Illuminate\View\View
     */
	function index(Request $request, $fieldname = null , $fieldvalue = null){
		$view = "pages.layanan_verifikator.list";
		$query = Layanan_Verifikator::query();
		$limit = $request->limit ?? 8;
		if($request->search){
			$search = trim($request->search);
			Layanan_Verifikator::search($query, $search); // search table records
		}
		if($request->orderby){
			$orderby = $request->orderby;
			$ordertype = ($request->ordertype ? $request->ordertype : "desc");
			$query->orderBy($orderby, $ordertype);
		}
		else{
			$query->orderBy("layanan_verifikator.created", "DESC");
			$query->orderBy("layanan_verifikator.id_jenis_layanan_verifikator", "ASC");
		}
		if($fieldname){
			$query->where($fieldname , $fieldvalue); //filter by a table field
		}
		// if request format is for export example:- product/index?export=pdf
		if($this->getExportFormat()){
			return $this->ExportList($query); // export current query
		}
		$records = $query->paginate($limit, Layanan_Verifikator::listFields());
		return $this->renderView($view, compact("records"));
	}
	

	/**
     * Import csv file data into a table 
     * @return data
     */
	function importdata(Request $request){
		$importSettings = config("upload.import");
		$maxFileSize = intval($importSettings["max_file_size"]) * 1000; //in kilobyte
		$validator = Validator::make($request->all(), 
			[
				"file" => "file|required|max:$maxFileSize|mimes:csv,txt",
			]
		);
		if ($validator->fails()) {
			return back()->withErrors($validator->errors());
		}
		$csvOptions = array(
			'fields' => '', //leave empty to use the first row as the columns
			'delimiter' => ',', 
			'quote' => '"'
		);
		$filePath = $request->file('file')->getRealPath();
		$modeldata = parse_csv_file($filePath, $csvOptions);
		Layanan_Verifikator::insert($modeldata);
		return $this->redirect(url()->previous(), "Data imported successfully");
	}
	

	/**
     * Select table record by ID
	 * @param string $rec_id
     * @return \Illuminate\View\View
     */
	function view($rec_id = null){
		$query = Layanan_Verifikator::query();
		$record = $query->findOrFail($rec_id, Layanan_Verifikator::viewFields());
		return $this->renderView("pages.layanan_verifikator.view", ["data" => $record]);
	}
	

	/**
     * Display form page
     * @return \Illuminate\View\View
     */
	function add(){
		return $this->renderView("pages.layanan_verifikator.add");
	}
	

	/**
     * Save form record to the table
     * @return \Illuminate\Http\Response
     */
	function store(Layanan_VerifikatorAddRequest $request){
		$modeldata = $this->normalizeFormData($request->validated());
		
		//save Layanan_Verifikator record
		$record = Layanan_Verifikator::create($modeldata);
		$rec_id = $record->id;
		return $this->redirect("layanan_verifikator", "Record added successfully");
	}
	

	/**
     * Update table record with form data
	 * @param string $rec_id //select record by table primary key
     * @return \Illuminate\View\View;
     */
	function edit(Layanan_VerifikatorEditRequest $request, $rec_id = null){
		$query = Layanan_Verifikator::query();
		$record = $query->findOrFail($rec_id, Layanan_Verifikator::editFields());
		if ($request->isMethod('post')) {
			$modeldata = $this->normalizeFormData($request->validated());
			$record->update($modeldata);
			return $this->redirect("layanan_verifikator", "Record updated successfully");
		}
		return $this->renderView("pages.layanan_verifikator.edit", ["data" => $record, "rec_id" => $rec_id]);
	}
	

	/**
     * Delete record from the database
	 * Support multi delete by separating record id by comma.
	 * @param  \Illuminate\Http\Request
	 * @param string $rec_id //can be separated by comma 
     * @return \Illuminate\Http\Response
     */
	function delete(Request $request, $rec_id = null){
		$arr_id = explode(",", $rec_id);
		$query = Layanan_Verifikator::query();
		$query->whereIn("id", $arr_id);
		$query->delete();
		$redirectUrl = $request->redirect ?? url()->previous();
		return $this->redirect($redirectUrl, "Record deleted successfully");
	}
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataVerifikatorNew(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananVerifikator = DB::table('jenis_layanan_verifikator')->select('id', 'layanan_verifikator')->get();
        $begin    = new \DateTime( "2023-01-01" );
        $end      = new \DateTime( "2023-02-18" );
        $interval = new \DateInterval('P1D');
        $period   = new \DatePeriod( $begin, $interval, $end );
        foreach( $period as $date ){
        if( $date->format('w') != 0 && $date->format('w') != 6){
        foreach($layananVerifikator as $data){
        $modeldata =  [
        'id_jenis_layanan_verifikator' => $data->id,
        'jumlah' => 0,
        'created' => $date->format("Y-m-d")
        ];
        DB::table('layanan_verifikator')->insert($modeldata);
        }
        }
        }
        return $this->redirect("layanan_verifikator", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataVerifikator(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananVerifikator = DB::table('jenis_layanan_verifikator')->select('id', 'layanan_verifikator')->get();
        foreach($layananVerifikator as $data){
        $modeldata =  [
        'id_jenis_layanan_verifikator' => $data->id,
        'jumlah' => 0,
        'created' => date_now()
        ];
        DB::table('layanan_verifikator')->insert($modeldata);
        }
    return $this->redirect("layanan_verifikator", "Record added successfully");
    }
	

	/**
     * Export table records to different format
	 * supported format:- PDF, CSV, EXCEL, HTML
	 * @param \Illuminate\Database\Eloquent\Model $query
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
	private function ExportList($query){
		ob_end_clean(); // clean any output to allow file download
		$filename = "ListLayanan_VerifikatorReport-" . date_now();
		$format = $this->getExportFormat();
		if($format == "print"){
			$records = $query->get(Layanan_Verifikator::exportListFields());
			return view("reports.layanan_verifikator-list", ["records" => $records]);
		}
		elseif($format == "pdf"){
			$records = $query->get(Layanan_Verifikator::exportListFields());
			$pdf = PDF::loadView("reports.layanan_verifikator-list", ["records" => $records]);
			return $pdf->download("$filename.pdf");
		}
		elseif($format == "csv"){
			return Excel::download(new LayananVerifikatorListExport($query), "$filename.csv", \Maatwebsite\Excel\Excel::CSV);
		}
		elseif($format == "excel"){
			return Excel::download(new LayananVerifikatorListExport($query), "$filename.xlsx", \Maatwebsite\Excel\Excel::XLSX);
		}
	}
}
