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

/**
 * Inquiry_model — contact + brand collaboration leads, and newsletter subs.
 */
#[\AllowDynamicProperties]
class Inquiry_model extends MY_Model {

	protected $table = 'inquiries';
	protected $order_by = 'created_at DESC';
	protected $primary_key = 'id';

	// Override insert to add timestamps if needed
	public function insert($data)
	{
		// Add timestamps if not set
		if (!isset($data['created_at'])) {
			$data['created_at'] = date('Y-m-d H:i:s');
		}
		if (!isset($data['updated_at'])) {
			$data['updated_at'] = date('Y-m-d H:i:s');
		}
		
		return parent::insert($data);
	}

	// Override update to update timestamp
	public function update($id, $data)
	{
		$data['updated_at'] = date('Y-m-d H:i:s');
		return parent::update($id, $data);
	}

	/** Inquiries filtered by type/status with optional search. */
	public function filtered($type = NULL, $status = NULL, $search = NULL, $limit = NULL, $offset = 0)
	{
		if ($type)   $this->db->where('type', $type);
		if ($status) $this->db->where('status', $status);
		if ($search)
		{
			$this->db->group_start()
				->like('name', $search)
				->or_like('email', $search)
				->or_like('company', $search)
				->or_like('subject', $search)
				->group_end();
		}
		$this->db->order_by($this->order_by);
		if ($limit) $this->db->limit($limit, $offset);
		return $this->db->get($this->table)->result_array();
	}

	/** Count inquiries per pipeline status. */
	public function status_counts()
	{
		$rows = $this->db->select('status, COUNT(*) AS total')
			->group_by('status')->get($this->table)->result_array();
		$out = array('new' => 0, 'reviewed' => 0, 'converted' => 0, 'closed' => 0);
		foreach ($rows as $r) $out[$r['status']] = $r['total'];
		return $out;
	}

	/** Move an inquiry along the pipeline. */
	public function set_status($id, $status, $notes = NULL)
	{
		$data = array('status' => $status);
		if ($notes !== NULL) $data['admin_notes'] = $notes;
		return $this->update($id, $data);
	}

	/* ---- Newsletter subscribers ---- */

	/** Add a newsletter subscriber (ignores duplicates). */
	public function subscribe($email)
	{
		$exists = $this->db->where('email', $email)
			->count_all_results('subscribers');
		if ($exists) return FALSE;
		$this->db->insert('subscribers', array(
			'email' => $email, 
			'is_active' => 1,
			'created_at' => date('Y-m-d H:i:s'),
		));
		return TRUE;
	}

	/** All active subscribers. */
	public function subscribers()
	{
		return $this->db->where('is_active', 1)
			->order_by('created_at DESC')
			->get('subscribers')->result_array();
	}
}