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

/**
 * Stay accommodators directory (Firestore: Accommodators).
 * Fields: name, phone, image, address, lat, lng — no Firebase Auth linkage.
 */
class Aoust_accommodator 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 — Accommodators';
		$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) {
			$ta = isset($a['timeStamp']) ? (int) $a['timeStamp'] : 0;
			$tb = isset($b['timeStamp']) ? (int) $b['timeStamp'] : 0;
			return $tb <=> $ta;
		});
		$data['accommodators'] = $list;
		$this->template->template_render('admin/accommodator/index', $data);
	}

	public function create()
	{
		$data['page_title'] = 'AOUST — Add Accommodator';
		$data['mode'] = 'create';
		$data['accommodator'] = $this->_empty_row();
		$this->template->template_render('admin/accommodator/form', $data);
	}

	public function store()
	{
		$payload = $this->_read_payload_from_post();
		if ($payload['name'] === '' || $payload['phone'] === '' || $payload['address'] === '') {
			$this->session->set_flashdata('warningmessage', 'Name, phone, and address are required.');
			redirect(base_url('aoust_accommodator/create'));
			return;
		}

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

		$nameSlug = $this->_slug($payload['name']);
		$payload['image'] = $this->_maybe_upload('image', 'accommodators/' . $docId . '/' . $nameSlug . '-photo');

		$ok = $this->common->adddatamodel('Accommodators', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Accommodator added.');
			redirect(base_url('aoust_accommodator'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to save.');
		redirect(base_url('aoust_accommodator/create'));
	}

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

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

		$payload = $this->_read_payload_from_post();
		if ($payload['name'] === '' || $payload['phone'] === '' || $payload['address'] === '') {
			$this->session->set_flashdata('warningmessage', 'Name, phone, and address are required.');
			redirect(base_url('aoust_accommodator/edit/' . rawurlencode($id)));
			return;
		}

		$payload['updatedAt'] = date('c');
		$nameSlug = $this->_slug($payload['name']);
		$newImage = $this->_maybe_upload('image', 'accommodators/' . $id . '/' . $nameSlug . '-photo');
		$payload['image'] = ($newImage !== '') ? $newImage : (isset($existing['image']) ? (string) $existing['image'] : '');

		$ok = $this->common->updatedatamodel('Accommodators', $id, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Accommodator updated.');
			redirect(base_url('aoust_accommodator'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to update.');
		redirect(base_url('aoust_accommodator/edit/' . rawurlencode($id)));
	}

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

	private function _empty_row()
	{
		return array(
			'id' => '',
			'name' => '',
			'phone' => '',
			'address' => '',
			'image' => '',
			'lat' => '',
			'lng' => '',
		);
	}

	private function _read_payload_from_post()
	{
		$latRaw = trim((string) $this->input->post('lat'));
		$lngRaw = trim((string) $this->input->post('lng'));
		return array(
			'name' => trim((string) $this->input->post('name')),
			'phone' => trim((string) $this->input->post('phone')),
			'address' => trim((string) $this->input->post('address')),
			'image' => '',
			'lat' => $latRaw === '' ? null : (float) $latRaw,
			'lng' => $lngRaw === '' ? null : (float) $lngRaw,
		);
	}

	private function _slug($s)
	{
		$s = strtolower(trim((string) $s));
		$s = preg_replace('/[^a-z0-9]+/', '-', $s);
		$s = trim($s, '-');
		return $s ?: 'accommodator';
	}

	private function _maybe_upload($field, $pathPrefix)
	{
		if (!isset($_FILES[$field]) || !is_array($_FILES[$field])) return '';
		if (!isset($_FILES[$field]['tmp_name']) || $_FILES[$field]['tmp_name'] === '') return '';
		if (!is_uploaded_file($_FILES[$field]['tmp_name'])) return '';

		$tmp = $_FILES[$field]['tmp_name'];
		$orig = isset($_FILES[$field]['name']) ? (string) $_FILES[$field]['name'] : '';
		$ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
		if ($ext === '') $ext = 'bin';
		$objectName = $pathPrefix . '-' . date('YmdHis') . '.' . $ext;

		try {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$bucket = $storage->getBucket();
			$bucket->upload(
				fopen($tmp, 'r'),
				array(
					'name' => $objectName,
					'predefinedAcl' => 'publicRead',
				)
			);
			return sprintf('https://storage.googleapis.com/%s/%s', $bucket->name(), $objectName);
		} catch (Exception $e) {
			return '';
		}
	}
}
