<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Layanan_KecamatanAddRequest;
use App\Http\Requests\Layanan_KecamatanEditRequest;
use App\Models\Layanan_Kecamatan;
use Illuminate\Http\Request;
use \PDF;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\LayananKecamatanListExport;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Exception;
class Layanan_KecamatanController 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_kecamatan.list";
		$query = Layanan_Kecamatan::query();
		$limit = $request->limit ?? 19;
		if($request->search){
			$search = trim($request->search);
			Layanan_Kecamatan::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_kecamatan.created", "DESC");
			$query->orderBy("layanan_kecamatan.id_kecamatan", "ASC");
			$query->orderBy("layanan_kecamatan.id_jenis_layanan_kecamatan", "ASC");
		}
		if($fieldname){
			$query->where($fieldname , $fieldvalue); //filter by a table field
		}
		if($request->layanan_kecamatan_created){
			$vals = explode("-to-",$request->layanan_kecamatan_created);
			$fromDate = $vals[0] ?? null;
			$toDate = $vals[1] ?? null;
			if($fromDate && $toDate){
				$query->whereRaw("layanan_kecamatan.created BETWEEN ? AND ?", [$fromDate, $toDate]);
			}
			elseif($fromDate){
				$query->whereRaw("layanan_kecamatan.created >= ?", [$fromDate]);
			}
			elseif($toDate){
				$query->whereRaw("layanan_kecamatan.created <= ?", [$toDate]);
			}
		}
		if($request->layanan_kecamatan_id_kecamatan){
			$val = $request->layanan_kecamatan_id_kecamatan;
			$query->where(DB::raw("layanan_kecamatan.id_kecamatan"), "=", $val);
		}
		// 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_Kecamatan::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_Kecamatan::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_Kecamatan::query();
		$record = $query->findOrFail($rec_id, Layanan_Kecamatan::viewFields());
		return $this->renderView("pages.layanan_kecamatan.view", ["data" => $record]);
	}
	

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

	/**
     * Save form record to the table
     * @return \Illuminate\Http\Response
     */
	function store(Layanan_KecamatanAddRequest $request){
		$modeldata = $this->normalizeFormData($request->validated());
		
		//save Layanan_Kecamatan record
		$record = Layanan_Kecamatan::create($modeldata);
		$rec_id = $record->id;
		return $this->redirect("layanan_kecamatan", "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_KecamatanEditRequest $request, $rec_id = null){
		$query = Layanan_Kecamatan::query();
		$record = $query->findOrFail($rec_id, Layanan_Kecamatan::editFields());
		if ($request->isMethod('post')) {
			$modeldata = $this->normalizeFormData($request->validated());
			$record->update($modeldata);
			return $this->redirect("layanan_kecamatan", "Record updated successfully");
		}
		return $this->renderView("pages.layanan_kecamatan.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_Kecamatan::query();
		$query->whereIn("id", $arr_id);
		$query->delete();
		$redirectUrl = $request->redirect ?? url()->previous();
		return $this->redirect($redirectUrl, "Record deleted successfully");
	}
	

	/**
     * 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 customchart(Request $request, $fieldname = null , $fieldvalue = null){
		$view = "pages.layanan_kecamatan.customchart";
		$query = Layanan_Kecamatan::query();
		$limit = $request->limit ?? 10;
		if($request->search){
			$search = trim($request->search);
			Layanan_Kecamatan::search($query, $search); // search table records
		}
		$orderby = $request->orderby ?? "layanan_kecamatan.id";
		$ordertype = $request->ordertype ?? "desc";
		$query->orderBy($orderby, $ordertype);
		if($fieldname){
			$query->where($fieldname , $fieldvalue); //filter by a table field
		}
		$records = $query->paginate($limit, Layanan_Kecamatan::customchartFields());
		return $this->renderView($view, compact("records"));
	}
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDensel(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 1, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => date_now()
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDentim(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 2, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => date_now()
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDenbar(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 3, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => date_now()
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDenut(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 4, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => date_now()
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDenselNew(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        $begin    = new \DateTime( "2023-01-01" );
        $end      = new \DateTime( "2023-02-18" );
        $interval = new \DateInterval('P1D');
        $period   = new \DatePeriod( $begin, $interval, $end );
        //for($i = $begin; $i <= $end; $i->modify('+1 day')){
        foreach( $period as $date ){
        if( $date->format('w') != 0 && $date->format('w') != 6){
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 1, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => $date->format("Y-m-d")
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        }
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDentimNew(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        $begin    = new \DateTime( "2023-01-01" );
        $end      = new \DateTime( "2023-02-18" );
        $interval = new \DateInterval('P1D');
        $period   = new \DatePeriod( $begin, $interval, $end );
        //for($i = $begin; $i <= $end; $i->modify('+1 day')){
        foreach( $period as $date ){
        if( $date->format('w') != 0 && $date->format('w') != 6){
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 2, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => $date->format("Y-m-d")
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        }
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDenbarNew(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        $begin    = new \DateTime( "2023-01-01" );
        $end      = new \DateTime( "2023-02-18" );
        $interval = new \DateInterval('P1D');
        $period   = new \DatePeriod( $begin, $interval, $end );
        //for($i = $begin; $i <= $end; $i->modify('+1 day')){
        foreach( $period as $date ){
        if( $date->format('w') != 0 && $date->format('w') != 6){
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 3, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => $date->format("Y-m-d")
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        }
        }
        return $this->redirect("layanan_kecamatan", "Record added successfully");
    }
    /**
     * Endpoint action
     * @return \Illuminate\Http\Response
     */
    public function fillDataDenutNew(Request $request){
        setlocale(LC_ALL, 'id-ID', 'id_ID');
        $layananKecamatan = DB::table('jenis_layanan_kecamatan')->select('id', 'layanan_kecamatan')->get();
        $begin    = new \DateTime( "2023-01-01" );
        $end      = new \DateTime( "2023-02-18" );
        $interval = new \DateInterval('P1D');
        $period   = new \DatePeriod( $begin, $interval, $end );
        //for($i = $begin; $i <= $end; $i->modify('+1 day')){
        foreach( $period as $date ){
        if( $date->format('w') != 0 && $date->format('w') != 6){
        foreach($layananKecamatan as $data){
        $modeldata =  [
        'id_kecamatan' => 4, 
        'id_jenis_layanan_kecamatan' => $data->id,
        'jumlah' => 0,
        'created' => $date->format("Y-m-d")
        ];
        DB::table('layanan_kecamatan')->insert($modeldata);
        }
        }
        }
        return $this->redirect("layanan_kecamatan", "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_KecamatanReport-" . date_now();
		$format = $this->getExportFormat();
		if($format == "print"){
			$records = $query->get(Layanan_Kecamatan::exportListFields());
			return view("reports.layanan_kecamatan-list", ["records" => $records]);
		}
		elseif($format == "pdf"){
			$records = $query->get(Layanan_Kecamatan::exportListFields());
			$pdf = PDF::loadView("reports.layanan_kecamatan-list", ["records" => $records]);
			return $pdf->download("$filename.pdf");
		}
		elseif($format == "csv"){
			return Excel::download(new LayananKecamatanListExport($query), "$filename.csv", \Maatwebsite\Excel\Excel::CSV);
		}
		elseif($format == "excel"){
			return Excel::download(new LayananKecamatanListExport($query), "$filename.xlsx", \Maatwebsite\Excel\Excel::XLSX);
		}
	}
}
