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

class Home extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('Service_model', 'services');
		$this->load->model('Reservation_model', 'reservations');
		$this->load->model('Order_model', 'orders');
		$this->load->model('Outlet_model', 'outlets');
		$this->load->model('Page_model', 'pages');
	}

	public function index()
	{
		$this->load->view('public/home', array(
			'title' => 'Beranda',
			'services' => $this->services->all(),
		));
	}

	public function reserve()
	{
		if ($this->input->method(TRUE) !== 'POST') {
			redirect('beranda');
		}

		$this->form_validation->set_rules('name', 'Nama', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('address', 'Alamat', 'trim|max_length[255]');
		$this->form_validation->set_rules('whatsapp', 'Whatsapp', 'trim|max_length[30]');
		$this->form_validation->set_rules('service_id', 'Layanan', 'trim|integer');
		$this->form_validation->set_rules('pickup_date', 'Tanggal penjemputan', 'trim');
		$this->form_validation->set_rules('pickup_time', 'Jam penjemputan', 'trim');
		$this->form_validation->set_rules('notes', 'Catatan', 'trim|max_length[255]');

		if (!$this->form_validation->run()) {
			$this->session->set_flashdata('error', validation_errors());
			redirect('beranda#reservasi');
		}

		$service_id = $this->input->post('service_id', TRUE);
		$service_id = $service_id ? (int) $service_id : null;
		$service = $this->services->find($service_id);

		if (!$service) {
			$this->session->set_flashdata('error', 'Layanan tidak ditemukan');
			redirect('beranda#reservasi');
		}

		// Handle Customer
		$this->load->model('Customer_model', 'customers');
		$phone = $this->input->post('whatsapp', TRUE);
		$customer = $this->customers->find_by_phone($phone);
		
		if ($customer) {
			$customer_id = $customer->id;
		} else {
			$customer_id = $this->customers->create(array(
				'name' => $this->input->post('name', TRUE),
				'phone' => $phone,
				'address' => $this->input->post('address', TRUE),
			));
		}

		// Create Order
		$code = $this->orders->generate_code();
		$this->orders->create(array(
			'code' => $code,
			'customer_id' => $customer_id,
			'service_id' => $service_id,
			'qty' => 1, // Default qty 1, admin will update real qty
			'pickup_date' => $this->input->post('pickup_date', TRUE) ?: null,
			'due_date' => null, // Admin will set due date
			'status' => 'baru',
			'notes' => $this->input->post('notes', TRUE) . ' (Waktu jemput: ' . $this->input->post('pickup_time', TRUE) . ')',
			'total' => $service->price, // Temporary total
			'paid_amount' => 0,
		));

		$this->session->set_flashdata('success', 'Reservasi berhasil dibuat. Kode order: <strong>' . html_escape($code) . '</strong>');
		redirect('struk?code=' . rawurlencode($code));
	}

	public function status()
	{
		$code = trim((string) $this->input->get('code', TRUE));
		$result = null;
		$type = null;

		if ($code !== '') {
			$result = $this->orders->find_by_code($code);
			$type = $result ? 'order' : null;

			if (!$result) {
				$result = $this->reservations->find_by_code($code);
				$type = $result ? 'reservation' : null;
			}
		}

		$this->load->view('public/status', array(
			'title' => 'Cek Status Cucianmu',
			'code' => $code,
			'type' => $type,
			'result' => $result,
		));
	}

	public function receipt()
	{
		$code = trim((string) $this->input->get('code', TRUE));
		$result = null;
		$type = null;

		if ($code !== '') {
			$result = $this->orders->find_by_code($code);
			$type = $result ? 'order' : null;

			if (!$result) {
				$result = $this->reservations->find_by_code($code);
				$type = $result ? 'reservation' : null;
			}
		}

		$this->load->view('public/receipt', array(
			'title' => 'Struk',
			'code' => $code,
			'type' => $type,
			'result' => $result,
		));
	}

	public function receipt_download()
	{
		$code = trim((string) $this->input->get('code', TRUE));
		if ($code === '') {
			redirect('struk');
		}

		$result = $this->orders->find_by_code($code);
		$type = $result ? 'order' : null;

		if (!$result) {
			$result = $this->reservations->find_by_code($code);
			$type = $result ? 'reservation' : null;
		}

		if (!$result) {
			show_404();
		}

		$html = $this->load->view('public/receipt_pdf', array(
			'title' => 'Struk ' . $code,
			'code' => $code,
			'type' => $type,
			'result' => $result,
		), TRUE);

		$options = new \Dompdf\Options();
		$options->set('isRemoteEnabled', FALSE);
		$options->set('isHtml5ParserEnabled', TRUE);

		$dompdf = new \Dompdf\Dompdf($options);
		$dompdf->loadHtml($html, 'UTF-8');
		$dompdf->setPaper('A4', 'portrait');
		$dompdf->render();

		$filename = 'struk-' . preg_replace('/[^A-Za-z0-9\\-_.]/', '_', $code) . '.pdf';
		$pdf = $dompdf->output();

		$this->output->set_content_type('application/pdf');
		$this->output->set_header('Content-Disposition: attachment; filename="' . $filename . '"');
		$this->output->set_output($pdf);
	}

	public function outlet()
	{
		$outlets = $this->outlets->all(TRUE);
		$map_url = 'https://www.google.com/maps?q=Jakarta&output=embed';
		foreach ($outlets as $o) {
			if (isset($o->map_url) && $o->map_url) {
				$map_url = $o->map_url;
				break;
			}
		}

		$this->load->view('public/outlet', array(
			'title' => 'Outlet',
			'outlets' => $outlets,
			'map_url' => $map_url,
		));
	}

	public function kemitraan()
	{
		$this->load->view('public/kemitraan', array('title' => 'Kemitraan'));
	}

	public function terms()
	{
		$page = null;
		if ($this->db->table_exists('pages')) {
			$page = $this->pages->find_by_slug('terms');
		}

		$this->load->view('public/terms', array(
			'title' => $page ? $page->title : 'Syarat & Ketentuan',
			'page' => $page,
		));
	}
}
