<?php
namespace App\Controllers\Client;
use App\Controllers\BaseController;
use App\Core\Service\Logger;
use App\Config\Main;
use App\Model\MasterModel;
use App\Core\Library\Mailer;

class BranchController extends BaseController
{
    private $MasterModel;
    private $Mailer;
    public function __construct() {
        parent::__construct();
        $this->MasterModel = new MasterModel();
        $this->Mailer = new Mailer();
    }

    public function uploadSignatureImage() {
        try {
            if(empty($this->user_data->comp_id)) {
                throw new \Exception("Invalid Company ID");
            }
            if(empty($_FILES['sign_img'])) {
                throw new \Exception("Please select logo to upload");
            }
            if(empty($this->input['branch_id'])) {
                throw new \Exception("Branch ID is required to upload signature");
            }
            $max_file_size = Main::getLogoUploadMaxSize();
            $allowed_file_types = Main::getAllowedLogoFileTypes();
            if ($_FILES["sign_img"]["size"] > Main::getLogoUploadMaxSize()) {
                throw new \Exception('File size should be less than ' . ($max_file_size/1024) . ' KB');
            }
            if (!in_array($_FILES["sign_img"]["type"], $allowed_file_types)) {
                throw new \Exception('Only ' . implode(", ", $allowed_file_types) . ' files are allowed.');
            }
            $uploadDir = Main::getUploadPath();
            $uploadFolder = Main::getUploadFolder();
            $uploadBasePath = $uploadDir . '/comp-' . $this->user_data->comp_id . '/';
            if (!is_dir($uploadBasePath)) {
                mkdir($uploadBasePath, 0755, true);
            }
            if (!is_dir($uploadBasePath)) {
                throw new \Exception("Upload path does not exist");
            }
            $file_name = 'branch_signature_' . $this->input['branch_id'] . '_' . time() . '.' . pathinfo($_FILES['sign_img']['name'], PATHINFO_EXTENSION);
            if(!move_uploaded_file($_FILES['sign_img']['tmp_name'], $uploadBasePath . $file_name)) {
                throw new \Exception("Error in uploading logo file");
            }
            $sign_img_path = $uploadFolder . '/comp-' . $this->user_data->comp_id . '/' . $file_name;
            $data = ['sign_img_path'=>$sign_img_path];    
            
            $dbname = 'sanordo_clientdb_' . $this->user_data->comp_id;
            $retData = $this->MasterModel->update("$dbname.".'branch_master', $data, ['branch_id' => $this->input['branch_id']]);
            if (!$retData['status']) {
                throw new \Exception($retData['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Signature uploaded successfully', 'data'=> ['sign_img'=>$sign_img_path])); 
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data'=> null));
        }
    }

    public function checkMailerSettings() {
        try {
            if(empty($this->user_data->comp_id)) {
                throw new \Exception("Invalid Company ID");
            }
            $rules = [
                'email_host'=> array('rules' => 'max_length[250]', 'label' => "Mailer Host"),
                'email_username' => array('rules' => 'max_length[250]|valid_email', 'label' => "Email username"),
                'email_password' => array('rules' => 'max_length[50]', 'label' => "Email password"),
                'email_port' => array('rules' => 'max_length[10]', 'label' => "Email port"),
            ];
            $validation = $this->validateReqData($rules, $this->input);            
            if(empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            $enable_ssl = !empty($this->input['is_ssl']) ? true : false;
            $verify_ssl = !empty($this->input['is_ssl']) ? true : false;
            $this->Mailer->configure($this->input['email_host'], $this->input['email_username'], $this->input['email_password'], $this->input['email_port'], $enable_ssl, $verify_ssl);
            $data = [
                'to'=>[['email_id'=>'vinod.kumar@sansoftwares.in', 'name'=>'Vinod'], ['email_id'=>'vinodkumarnsvk@gmail.com', 'name'=>'Vinod K']],
                'subject'=>'Test Mail',
                'body'=>'Client Branch Mailer Setting works'
            ];
            $resp = $this->Mailer->sendEmail($data);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Email Sent. Mailer Setting works', 'data'=> $resp));
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data'=> null));
        }
    }
}