<?php

class api extends mainController {

    private $modal = null;

    public function landing() {
        echo 1;
    }

    public function __construct() {
        //false to don't check login, since no login in data collector anymore
        parent::__construct(false);
//        die('heree');
        $this->modal = new apiModel();
    }

    public function test() {
        self::successResponse();
    }

    public function product() {
//        if(!isset($_SERVER['HTTP_TOKEN']) || $_SERVER['HTTP_TOKEN'] == null){
//            self::badRequestResponse();
//        }
//        $token = $_SERVER['HTTP_TOKEN'];
//        $isValid = $this->modal->validateToken($token);
//        if(!$isValid){
//            self::unauthorizedResponse();
//        }
        try {
            $data = $this->modal->getProducts();
        } catch (Exception $e) {
            self::genericErrorResponse();
        }

        $responseData = array(
            "data" => $data
        );
        self::successResponse($responseData);
    }

    public function stock() {
//        if(!isset($_SERVER['HTTP_TOKEN']) || $_SERVER['HTTP_TOKEN'] == null){
//            self::badRequestResponse();
//        }
//        $token = $_SERVER['HTTP_TOKEN'];
//        $isValid = $this->modal->validateToken($token);
//        if(!$isValid){
//            self::unauthorizedResponse();
//        }
        try {
            $data = $this->modal->getStocks();
        } catch (Exception $e) {
            self::genericErrorResponse();
        }

        $responseData = array(
            "data" => $data
        );
        self::successResponse($responseData);
    }

    public function login() {
//        $user_name = "admin";
//        $password = "123456";
        $body = json_decode(file_get_contents('php://input'), true);
        if (!isset($body['username']) || $body['username'] == null) {
            self::badRequestResponse();
        }
        if (!isset($body['password']) || $body['password'] == null) {
            self::badRequestResponse();
        }
        $username = $body['username'];
        $password = $body['password'];
        try {
            $credentials = $this->modal->login($username, $password);
        } catch (Exception $e) {
            self::genericErrorResponse();
        }
        if ($credentials == null) {
            self::forbiddenResponse();
        }
        $responseData = array(
            "token" => $credentials['token'],
            "id" => $credentials['id']
        );
        self::successResponse($responseData);
    }

    public function syncfiles() {
//        if(!isset($_SERVER['HTTP_TOKEN']) || $_SERVER['HTTP_TOKEN'] == null){
//            self::badRequestResponse();
//        }
//        $token = $_SERVER['HTTP_TOKEN'];
//        $isValid = $this->modal->validateToken($token);
//        if(!$isValid){
//            self::unauthorizedResponse();
//        }
        //$data must include: file_name,stock_id,type_id,file_path
        if (!isset($_FILES['file']) || $_FILES['file'] == null) {
            self::badRequestResponse();
        }
//        die(print_r($_FILES['file']));
        $error = $_FILES['file']['error'];
        if ($error != UPLOAD_ERR_OK) {
            if ($error == UPLOAD_ERR_PARTIAL) {
                self::genericErrorResponse("File is corrupted");
            }
            if ($error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE) {
                self::genericErrorResponse("File exceeds maximum file size");
            }
            self::genericErrorResponse();
        }
        $filename = $_FILES['file']['tmp_name'];
        if (!is_resource($zip = zip_open($filename))) {
            self::genericErrorResponse("File format is incorrect");
        }
        $zip = new ZipArchive;
        if ($zip->open($filename) !== true) {
            self::genericErrorResponse("Failed to open zip folder");
        }

        //create temp app files if not exist
        if (!file_exists(tmpAppFilesPath))
            mkdir(tmpAppFilesPath, 0777, true);
        //before everything empty temp folder

        $filesInDirectory = null;
        if (glob(tmpAppFilesPath . '*') === false) {
            self::genericErrorResponse("Temporary folder not found");
        }
        $filesInDirectory = glob(tmpAppFilesPath . '*');
        foreach ($filesInDirectory as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
        //extract all files to tmp folder
        if ($zip->extractTo(tmpAppFilesPath) === false) {
            self::genericErrorResponse("Could not extract folder");
        }
        $zip->close();
        $filesInDirectory = glob(tmpAppFilesPath . '*');
        $filesNotUploaded = array();
        //check file name to get type
        foreach ($filesInDirectory as $newFile) {
            $type = null;
            $id = 4;
            $baseNameNewFile = basename($newFile);
            $fileParts = explode('-', $baseNameNewFile);
            if (count($fileParts) == 0) {
                $filesNotUploaded[] = $baseNameNewFile;
                continue;
            }
//            $id = $fileParts[0]; //no login for now
            if (strpos($baseNameNewFile, 'Adjustment') !== false) {
                $type = 2;
            } else if (strpos($baseNameNewFile, 'Invoice') !== false) {
                $type = 1;
            } else {
                $filesNotUploaded[] = $baseNameNewFile;
                continue;
            }

            //move file from tmp to app_files
            $i = 0;
            $new_file_name = appFilesPath . $baseNameNewFile;
            while (file_exists($new_file_name))
                $new_file_name = appFilesPath . ( ++$i) . '__' . $baseNameNewFile;
            if (rename($newFile, $new_file_name) === false) {
                $filesNotUploaded[] = pathinfo($new_file_name, PATHINFO_BASENAME);
                continue;
            }
            $data = array(
                "file_name" => pathinfo($new_file_name, PATHINFO_BASENAME),
                "type_id" => $type,
                "user_id" => $id
            );
            //save file to database
            $error = $this->modal->setData($data)->addFile();
            if ($error != null) {
                $filesNotUploaded[] = $newFile;
            }
        }
        $responseData = array(
            "message" => "Success",
            "files_not_uploaded" => $filesNotUploaded
        );
        self::successResponse($responseData);
    }

    private function successResponse($data = null) {
        header('HTTP/1.1 200');
        header('Content-Type: application/json charset=utf-8');
        if ($data == null) {
            $data = array(
                "message" => "Success."
            );
        }

        die(json_encode($data));
    }

    private function badRequestResponse() {
        header('HTTP/1.1 400');
        header('Content-Type: application/json charset=utf-8');
        $responseData = array(
            "message" => "Bad Request."
        );
        die(json_encode($responseData));
    }

    private function unauthorizedResponse() {
        header('HTTP/1.1 401');
        header('Content-Type: application/json charset=utf-8');
        $responseData = array(
            "message" => "Unauthorized."
        );
        die(json_encode($responseData));
    }

    private function forbiddenResponse() {
        header('HTTP/1.1 403');
        header('Content-Type: application/json charset=utf-8');
        $responseData = array(
            "message" => "Forbidden."
        );
        die(json_encode($responseData));
    }

    private function genericErrorResponse($message = null) {
        header('HTTP/1.1 508');
        header('Content-Type: application/json charset=utf-8');
        $responseData = array(
            "message" => $message != null ? $message : "Generic Error."
        );
        die(json_encode($responseData));
    }

}
