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

class Email_Notification_Settings extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        if ($this->session->userdata('validated') != true) {
            redirect('login');
        }
        $this->load->helper('url');
        $this->load->model('Email_Notification_Settings_Model', 'ens_model');
    }

    public function index()
    {
        $data['page_title']   = 'Email Notification Settings | CMS';
        $data['page_heading'] = 'Email Notification Settings';
        $data['main_content'] = 'email_notification_settings';
        $data['controller']   = base_url('email-notification-settings');
        $data['settings']     = $this->ens_model->get_all();
        $this->load->view('main_content', $data);
    }

    public function update()
    {
        header('Content-Type: application/json');

        $id         = (int) $this->input->post('id');
        $form_name  = $this->input->post('form_name');
        $department = $this->input->post('department');
        $from_email = $this->input->post('from_email');
        $to_emails  = $this->input->post('to_emails');

        if (!$id || empty($to_emails)) {
            echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
            return;
        }

        $data = [
            'form_name'  => $form_name,
            'department' => $department,
            'from_email' => $from_email,
            'to_emails'  => $to_emails,
        ];

        $affected = $this->ens_model->update($id, $data);

        if ($affected !== false) {
            echo json_encode(['status' => 'success', 'message' => 'Settings updated successfully']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to update']);
        }
    }
}
