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

/**
 * Admin / Inquiries — contact messages and brand collaboration leads.
 */
#[\AllowDynamicProperties]
class Inquiries extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('inquiry_model', 'service_model'));
	}

	public function index()
	{
		$type   = $this->input->get('type', TRUE);
		$status = $this->input->get('status', TRUE);
		$search = $this->input->get('q', TRUE);

		$this->render('inquiries/index', array(
			'page_title' => 'Inquiries',
			'inquiries'  => $this->inquiry_model->filtered($type, $status, $search),
			'counts'     => $this->inquiry_model->status_counts(),
			'active'     => 'inquiries',
			'cur_type'   => $type,
			'cur_status' => $status,
			'cur_search' => $search,
		));
	}

	public function view($id)
	{
		$inq = $this->inquiry_model->get($id);
		if ( ! $inq) show_404();

		// Auto-advance brand-new inquiries to "reviewed" on first open.
		if ($inq['status'] === 'new')
		{
			$this->inquiry_model->set_status($id, 'reviewed');
			$inq['status'] = 'reviewed';
		}

		$service = $inq['service_id'] ? $this->service_model->get($inq['service_id']) : NULL;

		$this->render('inquiries/view', array(
			'page_title' => 'Inquiry — '.$inq['name'],
			'inq'        => $inq,
			'service'    => $service,
			'active'     => 'inquiries',
		));
	}

	public function status($id)
	{
		$inq = $this->inquiry_model->get($id);
		if ( ! $inq) show_404();

		$status = $this->input->post('status', TRUE);
		$notes  = $this->input->post('admin_notes', TRUE);
		$valid  = array('new', 'reviewed', 'converted', 'closed');

		if (in_array($status, $valid, TRUE))
		{
			$this->inquiry_model->set_status($id, $status, $notes);
			$this->log('Inquiry '.$status, $inq['name']);
			$this->session->set_flashdata('success', 'Inquiry updated.');
		}
		redirect('admin/inquiries/view/'.$id);
	}

	public function delete($id)
	{
		$inq = $this->inquiry_model->get($id);
		if ($inq)
		{
			$this->inquiry_model->delete($id);
			$this->log('Deleted inquiry', $inq['name']);
			$this->session->set_flashdata('success', 'Inquiry deleted.');
		}
		redirect('admin/inquiries');
	}

	/** Newsletter subscriber list + CSV export. */
	public function subscribers()
	{
		$subs = $this->inquiry_model->subscribers();

		if ($this->input->get('export') === 'csv')
		{
			$this->output
				->set_content_type('text/csv')
				->set_header('Content-Disposition: attachment; filename="subscribers-'.date('Y-m-d').'.csv"');
			$out = "Email,Subscribed On\n";
			foreach ($subs as $s)
			{
				$out .= '"'.$s['email'].'","'.$s['created_at']."\"\n";
			}
			$this->output->set_output($out);
			return;
		}

		$this->render('inquiries/subscribers', array(
			'page_title'  => 'Newsletter Subscribers',
			'subscribers' => $subs,
			'active'      => 'inquiries',
		));
	}
}
