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

/**
 * Admin / Hero — manage homepage hero carousel slides.
 */
#[\AllowDynamicProperties]
class Hero extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('hero_model');
	}

	/** List all slides. */
	public function index()
	{
		$this->render('hero/index', array(
			'page_title' => 'Hero Slides',
			'slides'     => $this->hero_model->get_all(),
		));
	}

	/** New slide form. */
	public function create()
	{
		$this->render('hero/form', array(
			'page_title' => 'Add Hero Slide',
			'slide'      => $this->_blank(),
			'mode'       => 'create',
		));
	}

	/** Edit slide form. */
	public function edit($id)
	{
		$slide = $this->hero_model->get($id);
		if ( ! $slide) show_404();
		$this->render('hero/form', array(
			'page_title' => 'Edit Hero Slide',
			'slide'      => $slide,
			'mode'       => 'edit',
		));
	}

	/** Persist a slide (create or update). */
	public function save()
	{
		$id = (int) $this->input->post('id');

		$this->load->library('form_validation');
		$this->form_validation->set_rules('heading', 'Heading', 'required|trim');
		$this->form_validation->set_rules('media_type', 'Media Type', 'required');

		if ($this->form_validation->run() === FALSE)
		{
			$this->session->set_flashdata('error', strip_tags(validation_errors()));
			redirect($id ? 'admin/hero/edit/'.$id : 'admin/hero/create');
		}

		$data = array(
			'media_type' => $this->input->post('media_type', TRUE),
			'eyebrow'    => $this->input->post('eyebrow', TRUE),
			'heading'    => $this->input->post('heading', TRUE),
			'subheading' => $this->input->post('subheading', TRUE),
			'youtube_id' => youtube_id($this->input->post('youtube_id', TRUE)),
			'cta1_label' => $this->input->post('cta1_label', TRUE),
			'cta1_url'   => $this->input->post('cta1_url', TRUE),
			'cta2_label' => $this->input->post('cta2_label', TRUE),
			'cta2_url'   => $this->input->post('cta2_url', TRUE),
			'overlay'    => $this->input->post('overlay') ? 1 : 0,
			'sort_order' => (int) $this->input->post('sort_order'),
			'is_active'  => $this->input->post('is_active') ? 1 : 0,
		);

		// Background image upload
		if ( ! empty($_FILES['image']['name']))
		{
			$img = $this->_upload('image', 'hero');
			if ($img) $data['image'] = $img;
		}
		// Video file upload — uses the larger video size limit.
		if ( ! empty($_FILES['video_file']['name']))
		{
			$vid = $this->_upload(
				'video_file', 'hero', 'mp4|webm|mov',
				$this->config->item('upload_max_video') ?: 51200
			);
			if ($vid) $data['video_file'] = $vid;
		}

		if ($id)
		{
			$this->hero_model->update($id, $data);
			$this->log('Updated hero slide', $data['heading']);
			$msg = 'Hero slide updated.';
		}
		else
		{
			$id = $this->hero_model->insert($data);
			$this->log('Created hero slide', $data['heading']);
			$msg = 'Hero slide created.';
		}

		$this->session->set_flashdata('success', $msg);
		redirect('admin/hero');
	}

	/** Delete a slide. */
	public function delete($id)
	{
		$slide = $this->hero_model->get($id);
		if ($slide)
		{
			$this->hero_model->delete($id);
			$this->log('Deleted hero slide', $slide['heading']);
			$this->session->set_flashdata('success', 'Hero slide deleted.');
		}
		redirect('admin/hero');
	}

	/** Toggle active state. */
	public function toggle($id)
	{
		$slide = $this->hero_model->get($id);
		if ($slide)
		{
			$this->hero_model->update($id, array('is_active' => $slide['is_active'] ? 0 : 1));
		}
		redirect('admin/hero');
	}

	/* ---- helpers ---- */

	private function _blank()
	{
		return array(
			'id' => 0, 'media_type' => 'image', 'image' => '', 'video_file' => '',
			'youtube_id' => '', 'eyebrow' => '', 'heading' => '', 'subheading' => '',
			'cta1_label' => '', 'cta1_url' => '', 'cta2_label' => '', 'cta2_url' => '',
			'overlay' => 1, 'sort_order' => 0, 'is_active' => 1,
		);
	}

	private function _upload($field, $folder, $types = 'jpg|jpeg|png|webp', $max_size = NULL)
	{
		// Default to the image limit; callers pass a larger limit for video.
		if ($max_size === NULL)
		{
			$max_size = $this->config->item('upload_max_size') ?: 20480;
		}

		$config = array(
			'upload_path'   => FCPATH.'assets/uploads/'.$folder.'/',
			'allowed_types' => $types,
			'max_size'      => $max_size,
			'file_name'     => $folder.'-'.time().'-'.bin2hex(random_bytes(3)),
			'encrypt_name'  => FALSE,
		);
		$this->load->library('upload', $config);
		$this->upload->initialize($config);

		if ($this->upload->do_upload($field))
		{
			return $folder.'/'.$this->upload->data('file_name');
		}
		$this->session->set_flashdata('error', $this->upload->display_errors('', ''));
		return NULL;
	}
}
