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

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

    public function uploadPincode() {
        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['pin_code_file'])) {
                throw new \Exception("Please select Pincode csv file to upload");
            }
            
            $max_file_size = Main::getUploadMaxSize();
            if ($_FILES["pin_code_file"]["size"] > Main::getUploadMaxSize()) {
                throw new \Exception('File size should be less than ' . ($max_file_size/1024) . ' KB');
            }
            if (!in_array($_FILES["pin_code_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 = 'pin_code' . '_' . time() . '.' . pathinfo($_FILES['pin_code_file']['name'], PATHINFO_EXTENSION);
            if(!move_uploaded_file($_FILES['pin_code_file']['tmp_name'], $uploadBasePath . $file_name)) {
                throw new \Exception("Error in uploading docket number file");
            }
            $pin_code_file_path = $uploadFolder . '/comp-' . $this->user_data->comp_id . '/' . $file_name;
                
            $this->Kafkam->sendMessage("sanordo_save_servicable_pincodes", ['comp_id'=>$this->user_data->comp_id, 'user_id'=>$this->user_data->id, 'courier_id'=>$this->input['courier_id'], 'file_path'=>$pin_code_file_path]);
            $this->sendResponse(array('code' => 200, 'message' => 'Pincode 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 savePincode($comp_id, $user_id, $courier_id, $file_path) {
        try {
            if(file_exists($file_path)) {
                $handler = fopen($file_path, "r");
                $i = 0;
                $batch_data = [];
                while (($row = fgetcsv($handler, 10000, ",")) !== FALSE) {
                    $i++;
                    if($i==1)
                        continue;
                    $pincode = trim($row[0]);
                    $origin_area = trim($row[1]);
                    $process_code = trim($row[2]);
                    $batch_data[] = [
                        'courier_id'    => $courier_id,
                        'pin_code'      => trim($pincode),
                        'origin_area'   => trim($origin_area),
                        'process_code'  => trim($process_code),
                        'cr_usr'        => $user_id
                    ];
                }
                
                Logger::debug(json_encode($batch_data,JSON_PRETTY_PRINT), ['File' => __FILE__, 'Line'=>__LINE__]);
                if(!empty($batch_data)) {
                    $table_name = $this->MasterModel->client_db_prefix.$comp_id . "." . $this->MasterModel->tables['courier_pincode'];
                    $rsp =  $this->MasterModel->delete($table_name, ["courier_id"=>$courier_id], []);
                    if(empty($rsp['status'])) {
                        Logger::error($rsp['error'], ['File' => __FILE__, 'Line'=>__LINE__]);
                    } 
                    $inrsp =  $this->MasterModel->batchInsert($table_name, $batch_data);
                    if(empty($inrsp)) {
                        Logger::error($inrsp['error'], ['File' => __FILE__, 'Line'=>__LINE__]);
                    }
                } else {
                    Logger::error("Insert Data getting Blank", ['File' => __FILE__, 'Line'=>__LINE__]);
                }
                echo "savePincode executed\r\n";
            }
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            echo $e->getMessage();exit;
        }
    }
}
