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

/**
 * Home — homepage, newsletter, 404 handler.
 */
#[\AllowDynamicProperties]
class Home extends Public_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model(array(
			'hero_model', 'portfolio_model', 'talent_model',
			'event_model', 'testimonial_model',
		));
	}

	/** Homepage. */
	public function index()
	{
		$this->meta(array(
			'title'       => setting('site_name', 'Bloom Iris Agency').' — '.setting('tagline'),
			'description' => setting('meta_description'),
			'keywords'    => setting('meta_keywords'),
		));

		// Load stats directly from database to ensure they exist
		$stats = array();
		$stat_keys = array('stat_campaigns', 'stat_talent', 'stat_events', 'stat_brands');
		
		foreach ($stat_keys as $key) {
			// Try to get from settings first
			$value = setting($key);
			if (empty($value) || $value === '0') {
				// Fallback to default values
				$defaults = array(
					'stat_campaigns' => 120,
					'stat_talent' => 85,
					'stat_events' => 40,
					'stat_brands' => 60
				);
				$value = isset($defaults[$key]) ? $defaults[$key] : 0;
			}
			$stats[$key] = (int)$value;
		}

		$data = array(
			'hero_slides'  => $this->hero_model->active(),
			'partners'     => $this->partner_model->featured(),
			'services'     => $this->service_model->active(),
			'featured'     => $this->portfolio_model->featured(6),
			'talent'       => $this->talent_model->featured(8),
			'events'       => $this->event_model->upcoming(3),
			'testimonials' => $this->testimonial_model->featured(6),
			'stats'        => $stats, // Pass stats to view
		);

		$this->render('home/index', $data);
	}

	/** Newsletter subscription (AJAX or standard POST). */
	public function newsletter()
	{
		$this->load->model('inquiry_model');
		$email = $this->input->post('email', TRUE);

		$ok = FALSE; $message = 'Please enter a valid email address.';
		if ($email && filter_var($email, FILTER_VALIDATE_EMAIL))
		{
			$added = $this->inquiry_model->subscribe($email);
			$ok = TRUE;
			$message = $added
				? 'Thank you for subscribing to the Bloom Iris journal!'
				: 'You are already subscribed — thank you!';
		}

		if ($this->input->is_ajax_request())
		{
			return $this->output
				->set_content_type('application/json')
				->set_output(json_encode(array('status' => $ok, 'message' => $message)));
		}

		$this->session->set_flashdata($ok ? 'success' : 'error', $message);
		redirect($this->agent->referrer() ?: base_url());
	}

	/** Branded 404 page (set as 404_override in routes). */
	public function not_found()
	{
		$this->output->set_status_header(404);
		$this->meta(array('title' => 'Page Not Found — Bloom Iris Agency'));
		$this->render('errors/error_404', array());
	}
}