<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Layanan_GsdAddRequest;
use App\Http\Requests\Layanan_GsdEditRequest;
use App\Models\Layanan_Gsd;
use Illuminate\Http\Request;
use \PDF;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\LayananGsdListExport;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Exception;
class Layanan_GsdController 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_gsd.list";
		$query = Layanan_Gsd::query();
		$limit = $request->limit ?? 20;
		if($request->search){
			$search = trim($request->search);
			Layanan_Gsd::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_gsd.created", "DESC");
			$query->orderBy("layanan_gsd.id_jenis_layanan_gsd", "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_Gsd::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_Gsd::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_Gsd::query();
		$record = $query->findOrFail($rec_id, Layanan_Gsd::viewFields());
		return $this->renderView("pages.layanan_gsd.view", ["data" => $record]);
	}
	

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

	/**
     * Save form record to the table
     * @return \Illuminate\Http\Response
     */
	function store(Layanan_GsdAddRequest $request){
		$modeldata = $this->normalizeFormData($request->validated());
		
		//save Layanan_Gsd record
		$record = Layanan_Gsd::create($modeldata);
		$rec_id = $record->id;
		return $this->redirect("layanan_gsd", "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_GsdEditRequest $request, $rec_id = null){
		$query = Layanan_Gsd::query();
		$record = $query->findOrFail($rec_id, Layanan_Gsd::editFields());
		if ($request->isMethod('post')) {
			$modeldata = $this->normalizeFormData($request->validated());
			$record->update($modeldata);
			return $this->redirect("layanan_gsd", "Record updated successfully");
		}
		return $this->renderView("pages.layanan_gsd.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_Gsd::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 fillDataGSDNew(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananGSD = DB::table('jenis_layanan_gsd')->select('id', 'layanan_gsd')->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($layananGSD as $data){
        $modeldata =  [
        'id_jenis_layanan_gsd' => $data->id,
        'jumlah' => 0,
        'created' => $date->format("Y-m-d")
        ];
        DB::table('layanan_gsd')->insert($modeldata);
        }
        }
        }
return $this->redirect("layanan_gsd", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataGSD(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananGSD = DB::table('jenis_layanan_gsd')->select('id', 'layanan_gsd')->get();
        foreach($layananGSD as $data){
        $modeldata =  [
        'id_jenis_layanan_gsd' => $data->id,
        'jumlah' => 0,
        'created' => date_now()
        ];
        DB::table('layanan_gsd')->insert($modeldata);
        }
    return $this->redirect("layanan_gsd", "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_GsdReport-" . date_now();
		$format = $this->getExportFormat();
		if($format == "print"){
			$records = $query->get(Layanan_Gsd::exportListFields());
			return view("reports.layanan_gsd-list", ["records" => $records]);
		}
		elseif($format == "pdf"){
			$records = $query->get(Layanan_Gsd::exportListFields());
			$pdf = PDF::loadView("reports.layanan_gsd-list", ["records" => $records]);
			return $pdf->download("$filename.pdf");
		}
		elseif($format == "csv"){
			return Excel::download(new LayananGsdListExport($query), "$filename.csv", \Maatwebsite\Excel\Excel::CSV);
		}
		elseif($format == "excel"){
			return Excel::download(new LayananGsdListExport($query), "$filename.xlsx", \Maatwebsite\Excel\Excel::XLSX);
		}
	}
}
