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

/**
 * Admin / Services — manage creative service offerings.
 */
#[\AllowDynamicProperties]
class Services_admin extends Admin_Controller {

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

	public function index()
	{
		$this->render('services/index', array(
			'page_title' => 'Services',
			'services'   => $this->service_model->get_all(),
		));
	}

	public function create()
	{
		$this->render('services/form', array(
			'page_title' => 'Add Service',
			'service'    => $this->_blank(),
			'mode'       => 'create',
		));
	}

	public function edit($id)
	{
		$service = $this->service_model->get($id);
		if ( ! $service) show_404();
		$this->render('services/form', array(
			'page_title' => 'Edit Service',
			'service'    => $service,
			'mode'       => 'edit',
		));
	}

	public function save()
	{
		$id = (int) $this->input->post('id');

		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', 'Title', 'required|trim');

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

		// Build process steps JSON from repeater fields
		$steps = array();
		$titles = $this->input->post('step_title');
		$texts  = $this->input->post('step_text');
		if (is_array($titles))
		{
			foreach ($titles as $i => $t)
			{
				if (trim($t) === '') continue;
				$steps[] = array('title' => $t, 'text' => $texts[$i] ?? '');
			}
		}

		$title = $this->input->post('title', TRUE);
		$slug  = $this->input->post('slug', TRUE) ?: url_title($title, '-', TRUE);

		$data = array(
			'title'         => $title,
			'slug'          => $slug,
			'icon'          => $this->input->post('icon', TRUE),
			'summary'       => $this->input->post('summary', TRUE),
			'description'   => $this->input->post('description', TRUE),
			'for_who'       => $this->input->post('for_who', TRUE),
			'process_steps' => json_encode($steps),
			'cta_label'     => $this->input->post('cta_label', TRUE),
			'meta_title'    => $this->input->post('meta_title', TRUE),
			'meta_desc'     => $this->input->post('meta_desc', TRUE),
			'sort_order'    => (int) $this->input->post('sort_order'),
			'is_active'     => $this->input->post('is_active') ? 1 : 0,
		);

		if ( ! empty($_FILES['image']['name']))
		{
			$img = $this->_upload('image', 'media');
			if ($img) $data['image'] = $img;
		}

		if ($id)
		{
			$this->service_model->update($id, $data);
			$this->log('Updated service', $title);
			$msg = 'Service updated.';
		}
		else
		{
			$this->service_model->insert($data);
			$this->log('Created service', $title);
			$msg = 'Service created.';
		}

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

	public function delete($id)
	{
		$service = $this->service_model->get($id);
		if ($service)
		{
			$this->service_model->delete($id);
			$this->log('Deleted service', $service['title']);
			$this->session->set_flashdata('success', 'Service deleted.');
		}
		redirect('admin/services');
	}

	public function toggle($id)
	{
		$service = $this->service_model->get($id);
		if ($service)
		{
			$this->service_model->update($id, array('is_active' => $service['is_active'] ? 0 : 1));
		}
		redirect('admin/services');
	}

	private function _blank()
	{
		return array(
			'id' => 0, 'title' => '', 'slug' => '', 'icon' => 'sparkle',
			'summary' => '', 'description' => '', 'for_who' => '', 'image' => '',
			'process_steps' => '[]', 'cta_label' => 'Work With Us',
			'meta_title' => '', 'meta_desc' => '', 'sort_order' => 0, 'is_active' => 1,
		);
	}

	private function _upload($field, $folder, $types = 'jpg|jpeg|png|webp')
	{
		$config = array(
			'upload_path'   => FCPATH.'assets/uploads/'.$folder.'/',
			'allowed_types' => $types,
			'max_size'      => $this->config->item('upload_max_size') ?: 20480,
			'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;
	}
}
