<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Layanan_Wa_Pengelola_SistemAddRequest;
use App\Http\Requests\Layanan_Wa_Pengelola_SistemEditRequest;
use App\Models\Layanan_Wa_Pengelola_Sistem;
use Illuminate\Http\Request;
use \PDF;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\LayananWaPengelolaSistemListExport;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Exception;
class Layanan_Wa_Pengelola_SistemController 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_wa_pengelola_sistem.list";
		$query = Layanan_Wa_Pengelola_Sistem::query();
		$limit = $request->limit ?? 3;
		if($request->search){
			$search = trim($request->search);
			Layanan_Wa_Pengelola_Sistem::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_wa_pengelola_sistem.created", "DESC");
			$query->orderBy("layanan_wa_pengelola_sistem.id_jenis_layanan_wa_pengelola_sistem", "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_Wa_Pengelola_Sistem::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_Wa_Pengelola_Sistem::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_Wa_Pengelola_Sistem::query();
		$record = $query->findOrFail($rec_id, Layanan_Wa_Pengelola_Sistem::viewFields());
		return $this->renderView("pages.layanan_wa_pengelola_sistem.view", ["data" => $record]);
	}
	

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

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