<?php
namespace App\Controllers\Client;
use App\Controllers\BaseController;
use App\Core\Service\Logger;
use App\Model\AdminClientModel;
use App\Config\Main;
use App\Library\Utilities;
class ClientController extends BaseController
{
    private $AdminClientModel;
    public function __construct() {
        parent::__construct();
        $this->AdminClientModel = new AdminClientModel();
    }

    public function getWebhook()
    {
        try {
            $url = '';
            $urlarr = Main::WebhookURLs();
            if ($this->input['type'] == 'COURIER') {
                if (!empty($this->input['courier'])) {
                    if (!empty($urlarr[$this->input['courier']])) {
                        $url = $urlarr[$this->input['courier']];
                    }
                }
            } else if ($this->input['type'] == 'PAYMENT') {
                if (!empty($this->input['gateway'])) {
                    if (!empty($urlarr[$this->input['gateway']])) {
                        $url = $urlarr[$this->input['gateway']];
                    }
                }
            } else if ($this->input['type'] == 'SHOPIFY') {
                $url = $urlarr['shopify'];
            }
            $resp = $this->AdminClientModel->getClientData($this->user_data->comp_id);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            if(empty($resp['data'])) {
                throw new \Exception("Client settings not found");
            }
            $webhook = !empty($url) ? $url . '?token=' . $resp['data']['access_token'] : "";
            $this->sendResponse(array('code' => 200, 'message' => '', 'webhook' => $webhook));
        } 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 getAccessToken() {
        try {
            $resp = $this->AdminClientModel->getClientData($this->user_data->comp_id);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            if(empty($resp['data'])) {
                throw new \Exception("Client settings not found");
            }
            $this->sendResponse(array('code' => 200, 'message' => null, 'data'=> ['access_token'=>$resp['data']['access_token']])); 
        } 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 generateAccessToken() {
        try {
            $token = Utilities::getClientToken();
            if(empty($token['status'])) {
                throw new \Exception($token['error']);
            }
            $data = ['setting_type'=>'access_token', 'access_token'=>$token['data']];
            $resp = $this->AdminClientModel->editClientSettings($this->user_data->comp_id, $data);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Access token generated successfully', 'data'=> ['access_token'=>$token['data']])); 
        } 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 getClientSettings() {
        try {
            $resp = $this->AdminClientModel->getClientData($this->user_data->comp_id);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            if(empty($resp['data'])) {
                throw new \Exception("Company settings not found");
            }
            
            unset($resp['data']['password']);
            $this->sendResponse(array('code' => 200, 'message' => null, 'data'=> $resp['data'])); 
        } 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 updateClientSettings() {
        try {
            if(empty($this->input['id']) || $this->input['id'] != $this->user_data->comp_id) {
                throw new \Exception("Invalid Company ID");
            }
            $resp = $this->AdminClientModel->editClientSettings($this->user_data->comp_id, $this->input);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $resp = $this->AdminClientModel->getClientData($this->user_data->comp_id);
            $this->sendResponse(array('code' => 200, 'message' => 'Company settings updated successfully', 'data'=> $resp['data'])); 
        } 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 uploadClientLogo() {
        try {
            if(empty($this->user_data->comp_id)) {
                throw new \Exception("Invalid Company ID");
            }
            if(empty($_FILES['logo_img'])) {
                throw new \Exception("Please select logo to upload");
            }
            $max_file_size = Main::getLogoUploadMaxSize();
            $allowed_file_types = Main::getAllowedLogoFileTypes();
            if ($_FILES["logo_img"]["size"] > Main::getLogoUploadMaxSize()) {
                throw new \Exception('File size should be less than ' . ($max_file_size/1024) . ' KB');
            }
            if (!in_array($_FILES["logo_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 = 'client_log_' . $this->user_data->comp_id . '_' . time() . '.' . pathinfo($_FILES['logo_img']['name'], PATHINFO_EXTENSION);
            if(!move_uploaded_file($_FILES['logo_img']['tmp_name'], $uploadBasePath . $file_name)) {
                throw new \Exception("Error in uploading logo file");
            }
            $logo_img_path = $uploadFolder . '/comp-' . $this->user_data->comp_id . '/' . $file_name;
            $data = ['logo_img'=>$logo_img_path, 'setting_type'=>'logo'];    
            $resp = $this->AdminClientModel->editClientSettings($this->user_data->comp_id, $data);
            if(empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Company logo uploaded successfully', 'data'=> ['logo_img'=>$logo_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));
        }
    }
}