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

class News extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
        $this->load->model('common');
        $this->load->helper(array('form', 'url', 'string'));
        $this->load->library('form_validation');
        $this->load->library('session');
    }

    public function index()
    {
        $data['newslist'] = $this->news_model->getall_news();
        $this->template->template_render('news_management', $data);
    }

    public function addnews()
    {
        $this->template->template_render('addnews');
    }

    public function insertnews()
    {
        $post = $this->input->post();
        $post['newsDate']=strtotime($post['newsDate'])*1000;
        $post['isActive'] = true;
        
        $response = $this->news_model->add_news($post);
        if ($response) {
            $this->session->set_flashdata('successmessage', 'New news added successfully');
            redirect('news');
        } else {
            $errormsg = 'Error! Something went wrong.';
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect('news/addnews');
        }
    }

    public function editnews()
    {
        $newsId = $this->uri->segment(3);
        $data['newsId'] = $newsId;
        $data['news'] = $this->news_model->get_newsdetails($newsId);

        $this->template->template_render('addnews', $data);
    }

    public function updatenews()
    {
        $da = $this->input->post();
        $da['newsDate']=strtotime($da['newsDate'])*1000;

        
        
        $response = $this->news_model->update_news($da);
        if ($response) {
            $this->session->set_flashdata('successmessage', 'News has been updated successfully');
        } else {
            $this->session->set_flashdata('warningmessage', 'Something wrong, Please try again later');
        }

        redirect(base_url() . 'news');
    }

    public function remove()
    {
        $id = $this->uri->segment(3);
        
        $response = $this->news_model->delete_news($id);
        if ($response) {
            $this->session->set_flashdata('successmessage', 'News deleted successfully');
        } else {
            $this->session->set_flashdata('warningmessage', 'System Error: Please try again later');
        }
        
        redirect($_SERVER['HTTP_REFERER']);
    }
}
