<?php namespace App\Controllers;

use \App\Models\BiodataModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class BiodataAdmin extends BaseController
{
	public function index()
	{
		$model = new BiodataModel();
		
		// Get search parameter
		$search = $this->request->getGet('search');
		
		// Get filter parameters
		$filter_jenis_kelamin = $this->request->getGet('filter_jenis_kelamin');
		
		// Get sorting parameters
		$sort_by = $this->request->getGet('sort_by') ?? 'nama';
		$sort_order = $this->request->getGet('sort_order') ?? 'ASC';
		
		// Apply search
		if (!empty($search)) {
			$model->groupStart()
				->like('nama', $search)
				->orLike('alamat', $search)
				->orLike('email', $search)
				->groupEnd();
		}
		
		// Apply filter
		if (!empty($filter_jenis_kelamin)) {
			$model->where('jenis_kelamin', $filter_jenis_kelamin);
		}
		
		// Apply sorting
		$model->orderBy($sort_by, $sort_order);
		
		$data = [
			'biodata' => $model->paginate(10),
			'pager' => $model->pager,
			'search' => $search,
			'filter_jenis_kelamin' => $filter_jenis_kelamin,
			'sort_by' => $sort_by,
			'sort_order' => $sort_order,
		];
		
		echo view('admin/admin_list_biodata', $data);
	}

	//--------------------------------------------------------------------------

	public function preview($id)
	{
		$model = new BiodataModel();
		$data['biodata'] = $model->where('id', $id)->first();
		
		if(!$data['biodata']){
			throw PageNotFoundException::forPageNotFound();
		}
		echo view('admin/admin_view_biodata', $data);
	}

	//--------------------------------------------------------------------------

	public function create()
	{
		// lakukan validasi
		$validation =  \Config\Services::validation();
		$validation->setRules([
			'nama' => 'required'
		]);
		$isDataValid = $validation->withRequest($this->request)->run();

		// jika data valid, simpan ke database
		if($isDataValid){
			$model = new BiodataModel();
			
			// Handle file upload for foto_profil
			$foto_profil = '';
			$fileFoto = $this->request->getFile('foto_profil');
			if ($fileFoto && $fileFoto->isValid() && !$fileFoto->hasMoved()) {
				$newName = $fileFoto->getRandomName();
				$fileFoto->move(WRITEPATH . '../public/uploads/', $newName);
				$foto_profil = 'uploads/' . $newName;
			}
			
			$model->insert([
				"nama" => $this->request->getPost('nama'),
				"alamat" => $this->request->getPost('alamat'),
				"tempat_lahir" => $this->request->getPost('tempat_lahir'),
				"tanggal_lahir" => $this->request->getPost('tanggal_lahir'),
				"jenis_kelamin" => $this->request->getPost('jenis_kelamin'),
				"agama" => $this->request->getPost('agama'),
				"no_hp" => $this->request->getPost('no_hp'),
				"email" => $this->request->getPost('email'),
				"foto_profil" => $foto_profil,
				"deskripsi" => $this->request->getPost('deskripsi')
			]);
			return redirect('admin/biodata');
		}
		
		// tampilkan form create
		echo view('admin/admin_create_biodata');
	}

	//--------------------------------------------------------------------------

	public function edit($id)
	{
		// ambil data yang akan diedit
		$model = new BiodataModel();
		$data['biodata'] = $model->where('id', $id)->first();
		
		// lakukan validasi data
		$validation =  \Config\Services::validation();
		$validation->setRules([
			'id' => 'required',
			'nama' => 'required'
		]);
		$isDataValid = $validation->withRequest($this->request)->run();
		
		// jika data valid, maka simpan ke database
		if($isDataValid){
			$updateData = [
				"nama" => $this->request->getPost('nama'),
				"alamat" => $this->request->getPost('alamat'),
				"tempat_lahir" => $this->request->getPost('tempat_lahir'),
				"tanggal_lahir" => $this->request->getPost('tanggal_lahir'),
				"jenis_kelamin" => $this->request->getPost('jenis_kelamin'),
				"agama" => $this->request->getPost('agama'),
				"no_hp" => $this->request->getPost('no_hp'),
				"email" => $this->request->getPost('email'),
				"deskripsi" => $this->request->getPost('deskripsi')
			];
			
			// Handle file upload for foto_profil
			$fileFoto = $this->request->getFile('foto_profil');
			if ($fileFoto && $fileFoto->isValid() && !$fileFoto->hasMoved()) {
				// Delete old foto if exists
				if (!empty($data['biodata']['foto_profil'])) {
					$oldFile = WRITEPATH . '../public/' . $data['biodata']['foto_profil'];
					if (file_exists($oldFile)) {
						unlink($oldFile);
					}
				}
				$newName = $fileFoto->getRandomName();
				$fileFoto->move(WRITEPATH . '../public/uploads/', $newName);
				$updateData['foto_profil'] = 'uploads/' . $newName;
			}
			
			$model->update($id, $updateData);
			return redirect('admin/biodata');
		}

		// tampilkan form edit
		echo view('admin/admin_edit_biodata', $data);
	}

	//--------------------------------------------------------------------------

	public function delete($id){
		$model = new BiodataModel();
		$biodata = $model->where('id', $id)->first();
		
		// Delete file if exist
		if (!empty($biodata['foto_profil'])) {
			$file = WRITEPATH . '../public/' . $biodata['foto_profil'];
			if (file_exists($file)) {
				unlink($file);
			}
		}
		
		$model->delete($id);
		return redirect()->to(base_url('admin/biodata'));
	}
}

