<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SettingModel;
use App\Models\ContactModel;
use App\Models\EmailModel;

class ContactMessage extends BaseController
{
    public function index()
    {
        $setting = new SettingModel();
        $contact = new ContactModel();
        $data['app_setting'] = $setting->get_application_setting();
        $data['all_message'] = $contact->get_all_message();
        echo view('admin/include/header', $data);
        echo view('admin/contact_message/all_message');
        echo view('admin/include/footer');
    }

    function delete_message($id)
    {
        $contact = new ContactModel();
        if($contact->delete_message($id))
        {
            session()->set('success', "Message Successfully Deleted");
            return redirect()->route('admin/contact_message');
        }
        else
        {
            session()->set('error', "Message Deleted Failed");
            return redirect()->route('admin/contact_message');
        } 
    }

    function send_email($id)
    {
        $contact = new ContactModel();
        $email = new EmailModel();
        $setting = new SettingModel();

        $del = $contact->get_message_by_id($id);
        $subject = $this->request->getVar('subject');
        $email_data['title'] = $this->request->getVar('subject');
        $email_data['content'] = $this->request->getVar('message');
        $email_data['app_setting'] = $setting->get_application_setting();
        $msg = view('email/send_email_template', $email_data);
        $email_id = $del->email;
        $data = $email->send_email($email_id, $subject, $msg, $mailType = 'html', $subject);
        if($data == 2)
        {
            $re_data['is_reply'] = 1;
            $contact->update_is_reply($re_data, $id);
            session()->set('success', "Email Successfully Send");
            return redirect()->to('admin/contact_message');
        }
        else
        {
            session()->set('error', 'Email Sending Failed. Please Check Server');
            return redirect()->to('admin/contact_message');
        }
        
        
    }
}
