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

/**
 * Stay requests (Firestore collection: Stay).
 * Pending: assign an accommodator, then approve or reject (SweetAlert + modal in view).
 */
class Aoust_stay extends CI_Controller
{
	const COLLECTION = 'StayRequest';

	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 — Stay Requests';
		$data['status_filter'] = strtolower(trim((string) $this->input->get('status'))) ?: 'all';

		$rows = $this->common->readdatafromcollectionwhereclause(self::COLLECTION);
		$list = array();
		if (!empty($rows)) {
			foreach ($rows as $id => $r) {
				if (is_array($r)) {
					$r['id'] = $id;
					$list[] = $r;
				}
			}
		}
		usort($list, function ($a, $b) {
			$ca = isset($a['checkIn']) ? (int) $a['checkIn'] : 0;
			$cb = isset($b['checkIn']) ? (int) $b['checkIn'] : 0;
			if ($ca !== $cb) {
				return $cb <=> $ca;
			}
			$ta = isset($a['createdAt']) ? (int) $a['createdAt'] : 0;
			$tb = isset($b['createdAt']) ? (int) $b['createdAt'] : 0;
			return $tb <=> $ta;
		});

		$filter = $data['status_filter'];
		if ($filter !== 'all' && in_array($filter, array('pending', 'approved', 'rejected'), true)) {
			$filtered = array();
			foreach ($list as $row) {
				if ($this->_norm_status_bucket($row) === $filter) {
					$filtered[] = $row;
				}
			}
			$list = $filtered;
		}

		$data['stays'] = $list;
		$data['accommodators'] = $this->_load_accommodators_for_select();
		$this->template->template_render('admin/stay/index', $data);
	}

	public function approve()
	{
		$stayId = trim((string) $this->input->post('stay_id'));
		$accId = trim((string) $this->input->post('accommodator_id'));
		if ($stayId === '' || $accId === '') {
			$this->session->set_flashdata('warningmessage', 'Stay and accommodator are required.');
			redirect(base_url('aoust_stay'));
			return;
		}

		$stay = $this->common->readdatadocument(self::COLLECTION, $stayId);
		if (empty($stay) || !is_array($stay)) {
			$this->session->set_flashdata('warningmessage', 'Stay request not found.');
			redirect(base_url('aoust_stay'));
			return;
		}
		if (!$this->_is_pending_row($stay)) {
			$this->session->set_flashdata('warningmessage', 'Only pending stays can be approved with an accommodator.');
			redirect(base_url('aoust_stay'));
			return;
		}

		$acc = $this->common->readdatadocument('Accommodators', $accId);
		if (empty($acc) || !is_array($acc)) {
			$this->session->set_flashdata('warningmessage', 'Accommodator not found.');
			redirect(base_url('aoust_stay'));
			return;
		}

		$name = isset($acc['name']) ? trim((string) $acc['name']) : '';
		$phone = isset($acc['phone']) ? trim((string) $acc['phone']) : '';
		$image = isset($acc['image']) ? trim((string) $acc['image']) : '';
		$address = isset($acc['address']) ? trim((string) $acc['address']) : '';
		$lat = isset($acc['lat']) && $acc['lat'] !== null && $acc['lat'] !== '' ? (float) $acc['lat'] : null;
		$lng = isset($acc['lng']) && $acc['lng'] !== null && $acc['lng'] !== '' ? (float) $acc['lng'] : null;

		$update = array(
			'accommodatorId' => $accId,
			'accommodatorName' => $name,
			'accommodatorNumber' => $phone,
			'accommodatorImage' => ($image !== '') ? $image : null,
			'accommodatorAddress' => $address,
			'lat' => $lat,
			'lon' => $lng,
			'status' => 'approved',
			'updatedAt' => round(microtime(true) * 1000),
		);

		try {
			$this->common->updatedatamodel(self::COLLECTION, $stayId, $update);
			$this->session->set_flashdata('successmessage', 'Stay approved and accommodator assigned.');
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Failed to update stay.');
		}
		redirect(base_url('aoust_stay'));
	}

	public function reject()
	{
		$stayId = trim((string) $this->input->post('stay_id'));
		if ($stayId === '') {
			$this->session->set_flashdata('warningmessage', 'Stay is required.');
			redirect(base_url('aoust_stay'));
			return;
		}

		$stay = $this->common->readdatadocument(self::COLLECTION, $stayId);
		if (empty($stay) || !is_array($stay)) {
			$this->session->set_flashdata('warningmessage', 'Stay request not found.');
			redirect(base_url('aoust_stay'));
			return;
		}
		if (!$this->_is_pending_row($stay)) {
			$this->session->set_flashdata('warningmessage', 'Only pending stays can be rejected.');
			redirect(base_url('aoust_stay'));
			return;
		}

		$update = array(
			'status' => 'rejected',
			'accommodatorId' => null,
			'accommodatorName' => null,
			'accommodatorNumber' => null,
			'accommodatorImage' => null,
			'accommodatorAddress' => null,
			'updatedAt' => round(microtime(true) * 1000),
		);

		try {
			$this->common->updatedatamodel(self::COLLECTION, $stayId, $update);
			$this->session->set_flashdata('successmessage', 'Stay rejected.');
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Failed to update stay.');
		}
		redirect(base_url('aoust_stay'));
	}

	private function _load_accommodators_for_select()
	{
		$rows = $this->common->readdatafromcollectionwhereclause('Accommodators');
		$list = array();
		if (!empty($rows)) {
			foreach ($rows as $id => $r) {
				if (is_array($r)) {
					$r['id'] = $id;
					$list[] = $r;
				}
			}
		}
		usort($list, function ($a, $b) {
			$na = isset($a['name']) ? strtolower((string) $a['name']) : '';
			$nb = isset($b['name']) ? strtolower((string) $b['name']) : '';
			return strcmp($na, $nb);
		});
		return $list;
	}

	/** For filters: denied counts as rejected. */
	private function _norm_status_bucket($row)
	{
		$s = isset($row['status']) ? strtolower(trim((string) $row['status'])) : '';
		if ($s === 'denied') return 'rejected';
		if ($s === 'pending' || $s === 'approved' || $s === 'rejected') return $s;
		return $s;
	}

	private function _is_pending_row($row)
	{
		$s = isset($row['status']) ? strtolower(trim((string) $row['status'])) : '';
		return $s === 'pending';
	}
}
