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

class Reservation_model extends CI_Model
{
	protected $table = 'reservations';

	public function create($data)
	{
		$data['created_at'] = date('Y-m-d H:i:s');
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}

	public function find_by_code($code)
	{
		$this->db->select('r.*, s.name as service_name, s.unit as service_unit, s.price as service_price');
		$this->db->from($this->table . ' r');
		$this->db->join('services s', 's.id = r.service_id', 'left');
		$this->db->where('r.code', $code);
		return $this->db->get()->row();
	}

	public function generate_code()
	{
		$prefix = 'RSV-' . date('Ymd') . '-';
		$this->db->like('code', $prefix, 'after');
		$this->db->order_by('id', 'DESC');
		$row = $this->db->get($this->table, 1)->row();

		$seq = 1;
		if ($row && isset($row->code)) {
			$parts = explode('-', $row->code);
			$last = (int) end($parts);
			$seq = $last + 1;
		}

		return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
	}
}

