<?php

namespace App\Controllers\Admin;
use App\Controllers\BaseController;

class ContactMessages extends BaseController
{
    private $myUser;
    private $Settingsmodel;
    private $model;

    public function __construct()
    {
        $this->myUser = service('auth')->getCurrentUser();
        $this->Settingsmodel = new \App\Models\GeneralSettingsModel;
        $this->model = new \App\Models\ContactMessageModel;
    }

    public function index()
    {
        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['title'] = 'البريد الصادر';

        $data['myUser'] = $this->myUser;
        $data['messages'] = $this->model->getMessagesByFolder('sent');
        $data['folder'] = 'sent';

        $data['page'] = view('Admin/contacts/sent', $data);

        return view('Admin/layouts/default', $data);
    }

    public function trash()
    {
        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['title'] = 'سلة المهملات';

        $data['myUser'] = $this->myUser;
        $data['messages'] = $this->model->getMessagesByFolder('trash');
        $data['folder'] = 'trash';

        $data['page'] = view('Admin/contacts/trash', $data);

        return view('Admin/layouts/default', $data);
    }

    public function view($id)
    {
        $mes_title = $this->model->getMessageById($id);
        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['title'] = $mes_title['subject'];

        $data['myUser'] = $this->myUser;
        $data['message'] = $this->model->getMessageById($id);
        if (empty($data['message'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('لايمكن العثور على الرسالة: ' . $id);
        }
        $this->model->markAsRead($id, 1);

        $data['page'] = view('Admin/contacts/view', $data);

        return view('Admin/layouts/default', $data);
    }

    public function compose()
    {
        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['title'] = 'رسالة جديدة';

        $data['myUser'] = $this->myUser;
        $data['page'] = view('Admin/contacts/compose', $data);

        return view('Admin/layouts/default', $data);
    }

	//--------------------------------------
    
    public function composeMessage()
    {

        $validation = \Config\Services::validation();
        $validation->setRules([
            'to' => [
                'label' => 'To',
                'rules' => 'required|valid_email',
                'errors' => [
                    'required' => 'الحقل - إلى - مطلوب',
                    'valid_email' => 'برجاء إدخال بريد صحيح في حقل إلى'
                ]
            ],
            'cc.*' => [
                'label' => 'Cc',
                'rules' => 'permit_empty|valid_emails',
                'errors' => [
                    'valid_emails' => 'برجاء إدخال بريد صحيح في حقل CC'
                ]
            ],
            'subject' => [
                'label' => 'Subject',
                'rules' => 'required',
                'errors' => [
                    'required' => 'برجاء إدخال موضوع'
                ]
            ],
            'message' => [
                'label' => 'Message',
                'rules' => 'required',
                'errors' => [
                    'required' => 'برجاء إدخال رسالة'
                ]
            ]
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $validation->getErrors());
        }

        $to = $this->request->getPost('to');
        $cc = $this->request->getPost('cc');
        $subject = $this->request->getPost('subject');
        $message = view('Admin/contacts/email_to_user',['message' => $this->request->getPost('message')]);

        $email = \Config\Services::email();
        $email->setTo($to);
        $email->setCC($cc);
        $email->setSubject($subject);
        $email->setMessage($message);

        if ($email->send()) {
            $data = [
                'name' => 'النظام - موقع الفندق',
                'email' => $to,
                'phone' => '000000000',
                'subject' =>  $subject,
                'message' => $message,
                'folder' => 'sent'
            ];
            $this->model->insertReply($data);
            return redirect()->to('dashboard/contact_messages/compose')->with('info', 'تم إرسال الرسالة بنجاح');
        } else {
            return redirect()->back()
                ->with('errors', $this->model->errors())
                ->with('warning', 'هناك خطأ ما')
                ->withInput();
        }

    }

    public function markAsRead($id)
    {
        $this->model->markAsRead($id, 1);
        return redirect()->to('dashboard/contact_messages/')->with('info', 'تم تحديد الرسالة كمقروءة');
    }

    public function markAsUnread($id)
    {
        $this->model->markAsUnread($id);
        return redirect()->to('dashboard/contact_messages')->with('info', 'تم تحديد الرسالة كغير مقروءة');
    }

    public function moveToTrash($id)
    {
        $this->model->moveToFolder($id, 'trash');
        return redirect()->back()->with('info', 'تم نقل الرسالة لسلة المهملات');
        ;
    }

    public function delete($id)
    {
        $message = $this->model->getMessageById($id);

        if (!$message) {
            return redirect()->back()->with('warning', 'لم يتم العثور على الرسالة');
        }

        $this->model->delete(['id' => $id]);
        return redirect()->back()->with('info', 'تم حذف الرسالة بنجاح');
    }

    public function emptyTrash()
    {
        $this->model->delete(null, true);
        return redirect()->to('dashboard/contact_messages/trash')->with('info', 'تم إفراغ سلة المهملات بنجاح');
    }
}