<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Program & Visa Info CRUD (Firestore collection: VisaPrograms)
 *
 * Structure:
 * - countryName (string)
 * - resourceLink (string, optional URL)
 * - program_overview (string)
 * - visa_eligibility (map)
 *    - visa_type
 *    - age_limit
 *    - language_requirement
 * - working_condition (map)
 *    - weekly_working_hour
 *    - pocket_money_stipend
 *    - vocationday_holiday
 * - insurance_benefit (map)
 *    - health_insurance
 *    - accident_insurance
 *    - additional_benefit
 * - userId, timeStamp, createdAt, updatedAt
 */
class Aoust_visa extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper(array('url', 'form'));
		$this->load->library('session');
		$this->load->database();

		if (!isset($this->session->userdata['session_data'])) {
			redirect(base_url('login'));
			return;
		}
	}

	public function index()
	{
		$data['page_title'] = 'AOUST — Program & Visa Info';
		$rows = $this->common->readdatafromcollectionwhereclause('VisaPrograms');
		$list = array();
		if (!empty($rows)) {
			foreach ($rows as $id => $r) {
				if (is_array($r)) {
					$r['id'] = $id;
					$list[] = $r;
				}
			}
		}
		usort($list, function ($a, $b) {
			$ta = isset($a['timeStamp']) ? (int) $a['timeStamp'] : 0;
			$tb = isset($b['timeStamp']) ? (int) $b['timeStamp'] : 0;
			return $tb <=> $ta;
		});
		$data['rows'] = $list;
		$this->template->template_render('admin/visa/index', $data);
	}

	public function create()
	{
		$data['page_title'] = 'AOUST — Add Program & Visa Info';
		$data['mode'] = 'create';
		$data['row'] = $this->_empty_row();
		$this->template->template_render('admin/visa/form', $data);
	}

	public function store()
	{
		$payload = $this->_read_payload_from_post();
		$errors = $this->_validate($payload);
		if (!empty($errors)) {
			$this->session->set_flashdata('warningmessage', implode(' ', $errors));
			redirect(base_url('aoust_visa/create'));
			return;
		}

		$docId = 'visa_' . uniqid();
		$payload['timeStamp'] = round(microtime(true) * 1000);
		$payload['createdAt'] = date('c');
		$payload['updatedAt'] = date('c');

		$ok = $this->common->adddatamodel('VisaPrograms', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Program & visa info created.');
			redirect(base_url('aoust_visa'));
			return;
		}

		$this->session->set_flashdata('warningmessage', 'Failed to create record.');
		redirect(base_url('aoust_visa/create'));
	}

	public function edit($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_visa'));
			return;
		}
		$row = $this->common->readdatadocument('VisaPrograms', $id);
		if (empty($row) || !is_array($row)) {
			$this->session->set_flashdata('warningmessage', 'Record not found.');
			redirect(base_url('aoust_visa'));
			return;
		}
		$row['id'] = $id;
		$data['page_title'] = 'AOUST — Edit Program & Visa Info';
		$data['mode'] = 'edit';
		$data['row'] = array_merge($this->_empty_row(), $row);
		$this->template->template_render('admin/visa/form', $data);
	}

	public function update($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_visa'));
			return;
		}
		$existing = $this->common->readdatadocument('VisaPrograms', $id);
		if (empty($existing) || !is_array($existing)) {
			$this->session->set_flashdata('warningmessage', 'Record not found.');
			redirect(base_url('aoust_visa'));
			return;
		}

		$payload = $this->_read_payload_from_post();
		$errors = $this->_validate($payload);
		if (!empty($errors)) {
			$this->session->set_flashdata('warningmessage', implode(' ', $errors));
			redirect(base_url('aoust_visa/edit/' . rawurlencode($id)));
			return;
		}
		$payload['updatedAt'] = date('c');

		$ok = $this->common->updatedatamodel('VisaPrograms', $id, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Program & visa info updated.');
			redirect(base_url('aoust_visa'));
			return;
		}

		$this->session->set_flashdata('warningmessage', 'Failed to update record.');
		redirect(base_url('aoust_visa/edit/' . rawurlencode($id)));
	}

	public function delete($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_visa'));
			return;
		}
		$this->common->deletedatamodel('VisaPrograms', $id);
		$this->session->set_flashdata('successmessage', 'Record deleted.');
		redirect(base_url('aoust_visa'));
	}

	private function _empty_row()
	{
		$sessiondata = $this->session->userdata['session_data'];
		$userId = isset($sessiondata['userId']) ? (string) $sessiondata['userId'] : '';
		return array(
			'id' => '',
			'countryName' => '',
			'continent' => '',
			'resourceLink' => '',
			'program_overview' => '',
			'visa_eligibility' => array(
				'visa_type' => '',
				'age_limit' => '',
				'language_requirement' => '',
			),
			'working_condition' => array(
				'weekly_working_hour' => '',
				'pocket_money_stipend' => '',
				'vocationday_holiday' => '',
			),
			'insurance_benefit' => array(
				'health_insurance' => '',
				'accident_insurance' => '',
				'additional_benefit' => '',
			),
			'userId' => $userId,
		);
	}

	private function _read_payload_from_post()
	{
		$sessiondata = $this->session->userdata['session_data'];
		$userId = isset($sessiondata['userId']) ? (string) $sessiondata['userId'] : '';
		$userIdPost = trim((string) $this->input->post('userId'));

		return array(
			'countryName' => trim((string) $this->input->post('countryName')),
			'continent' => trim((string) $this->input->post('continent')),
			'resourceLink' => trim((string) $this->input->post('resourceLink')),
			'program_overview' => trim((string) $this->input->post('program_overview')),
			'visa_eligibility' => array(
				'visa_type' => trim((string) $this->input->post('visa_type')),
				'age_limit' => trim((string) $this->input->post('age_limit')),
				'language_requirement' => trim((string) $this->input->post('language_requirement')),
			),
			'working_condition' => array(
				'weekly_working_hour' => trim((string) $this->input->post('weekly_working_hour')),
				'pocket_money_stipend' => trim((string) $this->input->post('pocket_money_stipend')),
				'vocationday_holiday' => trim((string) $this->input->post('vocationday_holiday')),
			),
			'insurance_benefit' => array(
				'health_insurance' => trim((string) $this->input->post('health_insurance')),
				'accident_insurance' => trim((string) $this->input->post('accident_insurance')),
				'additional_benefit' => trim((string) $this->input->post('additional_benefit')),
			),
			'userId' => $userIdPost !== '' ? $userIdPost : $userId,
		);
	}

	private function _validate($payload)
	{
		$errors = array();
		if (empty($payload['countryName'])) $errors[] = 'Country name is required.';
		if (empty($payload['program_overview'])) $errors[] = 'Program overview is required.';
		return $errors;
	}
}

