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

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

    public function uploadDocketNumbers() {
        try {
            if(empty($this->user_data->comp_id)) {
                throw new \Exception("Invalid Company ID");
            }
            if(empty($this->input['courier_id'])) {
                throw new \Exception("Please select courier");
            }
            if(empty($_FILES['docket_no_file'])) {
                throw new \Exception("Please select docket number csv file to upload");
            }
            
            $max_file_size = Main::getUploadMaxSize();
            if ($_FILES["docket_no_file"]["size"] > Main::getUploadMaxSize()) {
                throw new \Exception('File size should be less than ' . ($max_file_size/1024) . ' KB');
            }
            if (!in_array($_FILES["docket_no_file"]["type"], ['text/csv'])) {
                throw new \Exception('Only .csv 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 = 'docket_number' . '_' . time() . '.' . pathinfo($_FILES['docket_no_file']['name'], PATHINFO_EXTENSION);
            if(!move_uploaded_file($_FILES['docket_no_file']['tmp_name'], $uploadBasePath . $file_name)) {
                throw new \Exception("Error in uploading docket number file");
            }
            $docket_no_file_path = $uploadFolder . '/comp-' . $this->user_data->comp_id . '/' . $file_name;
            $data = ['docket_no_file_path'=>$docket_no_file_path, 'courier_id'=>$this->input['courier_id']];    
            
            $this->Kafkam->sendMessage("sanordo_save_docketno", ['comp_id'=>$this->user_data->comp_id, 'user_id'=>$this->user_data->id, 'courier_id'=>$this->input['courier_id'], 'file_path'=>$docket_no_file_path]);
            $this->sendResponse(array('code' => 200, 'message' => 'Docket Number file uploaded successfully.', 'data'=> null)); 
        } 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 saveDocketNo($comp_id, $user_id, $courier_id, $file_path) {
        try {
            if(file_exists($file_path)) {
                $handler = fopen($file_path, "r");
                $i = 0;
                while (($row = fgetcsv($handler, 10000, ",")) !== FALSE) {
                    $i++;
                    if($i==1)
                        continue;
                    $docket_no = trim($row[0]);
                    $table_name = $this->MasterModel->client_db_prefix.$comp_id . "." . $this->MasterModel->tables['courier_docketno'];
                    $rsp =  $this->MasterModel->fetchSingleData("SELECT * FROM $table_name WHERE docket_no=:docketno", [':docketno'=>$docket_no]);
                    if(empty($rsp['status'])) {
                        Logger::error($rsp['error'], ['File' => __FILE__, 'Line'=>__LINE__]);
                        continue;
                    } 
                    if(empty($rsp['data'])) {
                        Logger::error("Docket Number: $docket_no already exists", ['File' => __FILE__, 'Line'=>__LINE__]);
                        continue;
                    }
                    $data = [
                        'courier_id'    => $courier_id,
                        'docket_no'     => $docket_no,
                        'created_at'    => date('Y-m-d H:i:s'),
                        'cr_usr'        => $user_id
                    ];

                    $inrsp =  $this->MasterModel->insert($table_name, $data);
                    if(empty($inrsp)) {
                        Logger::error($inrsp['error'], ['File' => __FILE__, 'Line'=>__LINE__]);
                        continue;
                    }
                    if(!empty($inrsp['insert_id'])) {
                        Logger::debug("Docket Number: $docket_no inserted", ['File' => __FILE__, 'Line'=>__LINE__]);
                    } else {
                        Logger::error("Failed to insert Docket Number:$docket_no", ['File' => __FILE__, 'Line'=>__LINE__]);
                    }
                }
                echo "saveDocketNo executed\r\n";
            }
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            echo $e->getMessage();exit;
        }
    }
}
