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

class Outlets extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->require_login();
		$this->load->model('Outlet_model', 'outlets');
	}

	public function index()
	{
		$this->render('outlets/index', array(
			'title' => 'Outlet',
			'rows' => $this->outlets->all(FALSE),
		));
	}

	public function create()
	{
		$this->_set_rules();
		if ($this->input->method(TRUE) === 'POST' && $this->form_validation->run()) {
			$this->outlets->create($this->_payload());
			$this->session->set_flashdata('success', 'Outlet berhasil ditambahkan.');
			redirect('outlets');
		}

		$this->render('outlets/form', array(
			'title' => 'Tambah Outlet',
			'mode' => 'create',
			'row' => null,
		));
	}

	public function edit($id)
	{
		$row = $this->outlets->find($id);
		if (!$row) {
			show_404();
		}

		$this->_set_rules();
		if ($this->input->method(TRUE) === 'POST' && $this->form_validation->run()) {
			$this->outlets->update($id, $this->_payload());
			$this->session->set_flashdata('success', 'Outlet berhasil diubah.');
			redirect('outlets');
		}

		$this->render('outlets/form', array(
			'title' => 'Edit Outlet',
			'mode' => 'edit',
			'row' => $row,
		));
	}

	public function delete($id)
	{
		if ($this->input->method(TRUE) !== 'POST') {
			show_error('Metode tidak diizinkan', 405);
		}
		$this->outlets->delete($id);
		$this->session->set_flashdata('success', 'Outlet berhasil dihapus.');
		redirect('outlets');
	}

	private function _set_rules()
	{
		$this->form_validation->set_rules('name', 'Nama outlet', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('address', 'Alamat', 'trim|max_length[255]');
		$this->form_validation->set_rules('hours', 'Jam buka', 'trim|max_length[60]');
		$this->form_validation->set_rules('phone', 'Telepon', 'trim|max_length[30]');
		$this->form_validation->set_rules('whatsapp', 'WhatsApp', 'trim|max_length[30]');
		$this->form_validation->set_rules('notes', 'Catatan', 'trim|max_length[255]');
		$this->form_validation->set_rules('map_url', 'URL Maps Embed', 'trim|max_length[5000]|callback__validate_map_url');
		$this->form_validation->set_rules('is_active', 'Aktif', 'required|in_list[0,1]');
	}

	public function _validate_map_url($value)
	{
		$value = trim((string) $value);
		if ($value === '') {
			return TRUE;
		}

		// Allow iframe tags
		if (strpos($value, '<iframe') !== FALSE && strpos($value, 'google.com/maps') !== FALSE) {
			return TRUE;
		}

		$ok = preg_match('#^https?://(www\\.)?google\\.[a-z.]+/maps#i', $value)
			|| preg_match('#^https?://maps\\.google\\.[a-z.]+/maps#i', $value);

		if (!$ok) {
			$this->form_validation->set_message('_validate_map_url', 'Map URL harus berupa link Google Maps (embed) atau tag iframe.');
			return FALSE;
		}

		return TRUE;
	}

	private function _payload()
	{
		return array(
			'name' => $this->input->post('name', TRUE),
			'address' => $this->input->post('address', TRUE),
			'hours' => $this->input->post('hours', TRUE),
			'phone' => $this->input->post('phone', TRUE),
			'whatsapp' => $this->input->post('whatsapp', TRUE),
			'notes' => $this->input->post('notes', TRUE),
			'map_url' => $this->_process_map_url($this->input->post('map_url', TRUE)),
			'is_active' => (int) $this->input->post('is_active', TRUE),
		);
	}

	private function _process_map_url($url)
	{
		$url = trim((string) $url);
		if (empty($url)) {
			return '';
		}

		// Jika user paste full iframe code
		if (preg_match('/src="([^"]+)"/', $url, $matches)) {
			$url = $matches[1];
		}

		// Jika sudah format embed, biarkan
		if (strpos($url, 'output=embed') !== FALSE || strpos($url, '/maps/embed') !== FALSE) {
			return $url;
		}

		// Coba ambil koordinat dari URL @lat,long
		// Contoh: .../@-4.9734737,105.5029794,15z...
		if (preg_match('/@(-?\d+\.\d+),(-?\d+\.\d+)/', $url, $matches)) {
			$lat = $matches[1];
			$long = $matches[2];
			return "https://www.google.com/maps?q={$lat},{$long}&output=embed";
		}

		// Coba ambil dari parameter q=
		if (preg_match('/[?&]q=([^&]+)/', $url, $matches)) {
			// Sudah ada query location, tinggal tambah output=embed
			if (strpos($url, 'output=embed') === FALSE) {
				$sep = (strpos($url, '?') !== FALSE) ? '&' : '?';
				return $url . $sep . 'output=embed';
			}
		}

		return $url;
	}
}

