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

class Order_model extends CI_Model
{
	protected $table = 'orders';

	public function find_by_code($code)
	{
		$this->db->select('o.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address, s.name as service_name, s.unit as service_unit, s.price as service_price');
		$this->db->from($this->table . ' o');
		$this->db->join('customers c', 'c.id = o.customer_id');
		$this->db->join('services s', 's.id = o.service_id');
		$this->db->where('o.code', $code);
		return $this->db->get()->row();
	}

	public function all_with_relations()
	{
		$this->db->select('o.*, c.name as customer_name, s.name as service_name, s.unit as service_unit, s.price as service_price');
		$this->db->from($this->table . ' o');
		$this->db->join('customers c', 'c.id = o.customer_id');
		$this->db->join('services s', 's.id = o.service_id');
		$this->db->order_by('o.id', 'DESC');
		return $this->db->get()->result();
	}

	public function find_with_relations($id)
	{
		$this->db->select('o.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address, s.name as service_name, s.unit as service_unit, s.price as service_price');
		$this->db->from($this->table . ' o');
		$this->db->join('customers c', 'c.id = o.customer_id');
		$this->db->join('services s', 's.id = o.service_id');
		$this->db->where('o.id', (int) $id);
		return $this->db->get()->row();
	}

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

	public function update($id, $data)
	{
		$data['updated_at'] = date('Y-m-d H:i:s');
		$this->db->where('id', (int) $id)->update($this->table, $data);
		return $this->db->affected_rows() >= 0;
	}

	public function delete($id)
	{
		$this->db->where('id', (int) $id)->delete($this->table);
		return $this->db->affected_rows() > 0;
	}

	public function generate_code()
	{
		$prefix = 'LDRY-' . 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);
	}

	public function refresh_paid_amount($order_id)
	{
		$order_id = (int) $order_id;
		$total_paid = $this->db
			->select_sum('amount')
			->get_where('payments', array('order_id' => $order_id))
			->row();

		$paid_amount = $total_paid && $total_paid->amount !== null ? (float) $total_paid->amount : 0.0;

		$this->db->where('id', $order_id)->update($this->table, array(
			'paid_amount' => $paid_amount,
			'updated_at' => date('Y-m-d H:i:s'),
		));
	}
}
