<?php

namespace App\Models;

use CodeIgniter\Model;
use CodeIgniter\I18n\Time;

class EmailsModel extends Model
{
    protected $table = 'emails';
    protected $primaryKey = 'id';

    protected $allowedFields = ['client_id', 'subject', 'body', 'sent_at', 'send_to', 'send_cc', 'send_bcc', 'campaign_id', 'status', 'email_type', 'attachments'];

    protected $returnType     = 'array';
    protected $useTimestamps  = true;
    protected $useSoftDeletes = true;

    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    public function getAll()
    {
        $builder = $this->db->table('emails');
        $builder->where('deleted_at', null);
        $result = $builder->get()->getResult();
        return $result;
    }

    //Call Client Emails
    public function getClientEmails($client)
    {
        $builder = $this->db->table('emails as em');
        $builder->select('em.*,c.fname, c.lname, co.name as company_name, co.tel as company_telephone,');
        $builder->join('customer as c', 'c.id=em.client_id');
        $builder->join('company as co', 'co.customer_id=c.id');
        $builder->where('em.deleted_at', null);
        $builder->where('em.client_id', $client);
        $builder->where('em.is_active', '1');
        $builder->orderBy('em.created_at', 'DESC');
        $result = $builder->get()->getResult();
        return $result;
    }

    public function getSingleClientEmail($id)
    {
        $builder = $this->db->table('emails as em');
        $builder->select('em.*,c.fname, c.lname, co.name as company_name, co.tel as company_telephone,');
        $builder->join('customer as c', 'c.id=em.client_id');
        $builder->join('company as co', 'co.customer_id=c.id');
        $builder->where('em.id', $id);
        $result = $builder->get()->getRow();
        return $result;
    }

}