<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Layanan_Wa_PengaduanAddRequest;
use App\Http\Requests\Layanan_Wa_PengaduanEditRequest;
use App\Models\Layanan_Wa_Pengaduan;
use Illuminate\Http\Request;
use \PDF;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\LayananWaPengaduanListExport;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Exception;
class Layanan_Wa_PengaduanController 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_pengaduan.list";
		$query = Layanan_Wa_Pengaduan::query();
		$limit = $request->limit ?? 2;
		if($request->search){
			$search = trim($request->search);
			Layanan_Wa_Pengaduan::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_pengaduan.created", "DESC");
			$query->orderBy("layanan_wa_pengaduan.id_jenis_layanan_wa_pengaduan", "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_Pengaduan::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_Pengaduan::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_Pengaduan::query();
		$record = $query->findOrFail($rec_id, Layanan_Wa_Pengaduan::viewFields());
		return $this->renderView("pages.layanan_wa_pengaduan.view", ["data" => $record]);
	}
	

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

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