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

/**
 * Admin / Media — central media library.
 */
#[\AllowDynamicProperties]
class Media extends Admin_Controller {

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

	public function index()
	{
		$folder = $this->input->get('folder', TRUE);

		$this->render('media/index', array(
			'page_title' => 'Media Library',
			'items'      => $this->media_model->filtered($folder),
			'folders'    => $this->media_model->folders(),
			'cur_folder' => $folder,
		));
	}

	/** Upload one or more files into the library. */
	public function upload_files()
	{
		$folder = $this->input->post('folder', TRUE) ?: 'media';
		$paths  = $this->uploader->files('files', $folder, 'jpg|jpeg|png|webp|gif|svg|pdf|mp4');

		foreach ($paths as $p)
		{
			$full = FCPATH.'assets/uploads/'.$p;
			$this->media_model->insert(array(
				'file_name' => basename($p),
				'file_path' => $p,
				'file_type' => pathinfo($p, PATHINFO_EXTENSION),
				'folder'    => $folder,
				'file_size' => is_file($full) ? filesize($full) : 0,
			));
		}

		$this->log('Uploaded media', count($paths).' file(s)');
		$this->session->set_flashdata('success', count($paths).' file(s) uploaded.');
		redirect('admin/media');
	}

	public function delete($id)
	{
		$item = $this->media_model->get($id);
		if ($item)
		{
			$this->uploader->remove($item['file_path']);
			$this->media_model->delete($id);
			$this->log('Deleted media', $item['file_name']);
			$this->session->set_flashdata('success', 'File deleted.');
		}
		redirect('admin/media');
	}
}
