<?php

if (!defined('BASEPATH')) {
	exit('No direct script access allowed');
}

class Announcements extends Client_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('announcements_model');
	}

	public function view_announcements_details($id = null)
	{
		$announcement = $this->findClientAnnouncement($id);
		if (empty($announcement)) {
			set_message('error', lang('no_record_found'));
			redirect('client/dashboard');
		}

		$this->announcements_model->_table_name = 'tbl_announcements';
		$this->announcements_model->_primary_key = 'announcements_id';
		$this->announcements_model->save(array('view_status' => '1'), $announcement->announcements_id);

		$data['title'] = lang('announcements_details');
		$data['breadcrumbs'] = lang('announcements');
		$data['page'] = lang('announcements');
		$data['page_title'] = lang('announcements_details');
		$data['page_description'] = 'Published notice details and shared files.';
		$data['announcements_details'] = $announcement;

		$this->render('client/announcements/announcements_details', $data);
	}

	public function announcements_details($id = null)
	{
		redirect('client/announcements/view_announcements_details/' . (int) $id);
	}

	public function download_files($id = null, $key = null)
	{
		$announcement = $this->findClientAnnouncement($id);
		if (empty($announcement)) {
			set_message('error', lang('no_record_found'));
			redirect('client/dashboard');
		}

		$attachments = json_decode($announcement->attachment);
		$values = array_values((array) $attachments);
		if (!isset($values[$key]) || empty($values[$key])) {
			set_message('error', lang('operation_failed'));
			redirect('client/announcements/view_announcements_details/' . $announcement->announcements_id);
		}

		$file = $values[$key];
		$path = $file->path ?? '';
		if ($path === '' || !file_exists('./' . $path)) {
			set_message('error', lang('operation_failed'));
			redirect('client/announcements/view_announcements_details/' . $announcement->announcements_id);
		}

		$this->load->helper('download');
		$data = file_get_contents('./' . $path);
		force_download($file->fileName, $data);
	}

	private function findClientAnnouncement($id)
	{
		$id = (int) $id;
		if ($id <= 0) {
			return null;
		}

		$this->announcements_model->_table_name = 'tbl_announcements';
		$this->announcements_model->_order_by = 'announcements_id';
		$announcement = $this->announcements_model->get_by(array(
			'announcements_id' => $id,
			'status' => 'published',
			'all_client' => 1,
		), true);

		return !empty($announcement) ? $announcement : null;
	}
}
