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

/**
 * Admin / Pages — edit static content pages (currently the About page,
 * whose content is stored as structured JSON blocks).
 */
#[\AllowDynamicProperties]
class Pages_admin extends Admin_Controller {

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

	public function index()
	{
		$this->render('pages/index', array(
			'page_title' => 'Pages',
			'pages'      => $this->page_model->get_all(),
		));
	}

	public function edit($id)
	{
		$page = $this->page_model->get($id);
		if ( ! $page) show_404();
		$this->render('pages/form', array(
			'page_title' => 'Edit Page — '.$page['title'],
			'page'       => $page,
			'blocks'     => decode_json($page['blocks']),
		));
	}

	public function save()
	{
		$id = (int) $this->input->post('id');
		$page = $this->page_model->get($id);
		if ( ! $page) show_404();

		// Collect the structured blocks for the About page.
		$blocks = array(
			'origin'     => $this->input->post('origin', TRUE),
			'vision'     => $this->input->post('vision', TRUE),
			'mission'    => $this->input->post('mission', TRUE),
			'philosophy' => $this->input->post('philosophy', TRUE),
			'difference' => $this->input->post('difference', TRUE),
			'values'     => array_values(array_filter(
				(array) $this->input->post('values', TRUE),
				function ($v) { return trim($v) !== ''; }
			)),
		);

		$data = array(
			'title'      => $this->input->post('title', TRUE),
			'blocks'     => json_encode($blocks),
			'meta_title' => $this->input->post('meta_title', TRUE),
			'meta_desc'  => $this->input->post('meta_desc', TRUE),
		);

		$this->page_model->update($id, $data);
		$this->log('Updated page', $data['title']);
		$this->session->set_flashdata('success', 'Page updated.');
		redirect('admin/pages/edit/'.$id);
	}
}
