<?php
/**
 * UploadModel
 * Handles everything about Uploads.
 */
class UploadModel
{
    public static function processHeaderImage($profile_id)
    {
        $header_array = array('header_big'    => array('width'  => 1360,
                                                       'height' => 500),
                              'header_medium' => array('width'  => 950,
                                                       'height' => 350),
                              'header_small'  => array('width'  => 543,
                                                       'height' => 200));
        $result = self::imageUpload('profiles',$profile_id,$header_array);
        if ($result['success'] == true) {
            if (UserProfileModel::saveImage($profile_id,'company_header_path',$result['imagePath'])) {
                header("HTTP/1.1 200 OK");
                echo "upload successful";
            } else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "error while saving in db!";
            }
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            if (isset($result['error'])) {
                echo $result['error'];
            } else {
                echo "something went wrong";
            }
        }
    }

    public static function processOfferImage($offer_id)
    {
        $header_array = array('offer_big'    => array('width'  => 990,
                                                      'height' => 500),
                              'offer_medium' => array('width'  => 594,
                                                      'height' => 300),
                              'offer_small'  => array('width'  => 396,
                                                      'height' => 200));
        $result = self::imageUpload('offer',$offer_id,$header_array);
        if ($result['success'] == true) {
            if (OfferModel::saveImage($offer_id,$result['imagePath'])) {
                header("HTTP/1.1 200 OK");
                echo "upload successful";
            } else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "error while saving in db!";
            }
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            if (isset($result['error'])) {
                echo $result['error'];
            } else {
                echo "something went wrong";
            }
        }
    }

    public static function processLogoImage($profile_id)
    {
        $logo_array   = array('logo_big'    =>  array('width'  => 500,
                                                      'height' => 500),
                              'logo_medium' =>  array('width'  => 200,
                                                      'height' => 200),
                              'logo_small'  =>  array('width'  => 30,
                                                      'height' => 30));
        $result = self::imageUpload('profiles',$profile_id,$logo_array);
        if ($result['success'] == true) {
            if (UserProfileModel::saveImage($profile_id,'company_logo_path',$result['imagePath'])) {
                header("HTTP/1.1 200 OK");
                echo "upload successful";
            } else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "error while saving in db!";
            }
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            if (isset($result['error'])) {
                echo $result['error'];
            } else {
                echo "something went wrong";
            }
        }
    }

    public static function imageUpload($type,$id,$dimensions_array)
    {
        $ds = DIRECTORY_SEPARATOR;

        if ($id == 'platform') {
            $imageFolder = $type . $ds;
        } else {
            $imageFolder = $type . $ds . date('Y') . $ds . $id . $ds;
        }
        $storeFolder = Config::get('PATH_UPLOADS') . $imageFolder;
        if (!is_dir($storeFolder)) {
            if (mkdir($storeFolder, 0755, true)) {
                chmod($storeFolder, 0755);
            }
        }

        if (!empty($_FILES)) {
            set_error_handler(function ($errno, $errstr) {
                if ($errno == 2) {
                    $errstr = Text::get('FEEDBACK_IMAGE_UPLOAD_FAILED');
                }
                throw new Exception($errstr, $errno);
            }, E_WARNING);
            $tempFile = $_FILES['file']['tmp_name'];
            $fileName = $_FILES['file']['name'];
            require Config::get('PATH_LIBS') . 'SimpleImage.php';
            ini_set('memory_limit','128M');
            $number = 0;
            try {
                $img = new SimpleImage($tempFile);
                $ext = $img->get_original_info()['format'];
                foreach ($dimensions_array as $image_name => $dimensions) {
                    if ($image_name == 'platform_logo') {
                        $img->thumbnail($dimensions['width'], $dimensions['height'])
                            ->save($storeFolder.'logo.png');
                    } else if ($img->thumbnail($dimensions['width'], $dimensions['height'])
                            ->save($storeFolder.$image_name.'.'.$ext)) {
                        $number++;
                    }
                }
            } catch(Exception $e) {
                $errorMsg = $e->getMessage();
                if ($errorMsg == 'invalidImage') {
                    $errorMsg = Text::get('FEEDBACK_IMAGE_UPLOAD_INVALID');
                }
                $result['error'] = $errorMsg;
                $ext = '';
            }
        }
        restore_error_handler();
        $result['imagePath'] = $imageFolder.':.'.$ext;
        if ($number >= 3) {
            $result['success'] = true;
        } else {
            $result['success'] = false;
        }
        return $result;
    }

    public static function deleteImage($type,$id)
    {
        switch ($type) {
            case 'offerimage':
                OfferModel::checkOwnership($id);
                $offer = OfferModel::getOffer($id);
                $paths['offer'] = $offer->image;
                $returnpath = 'offers/edit/'.$id;
                OfferModel::updateOffer('image','',$id);
                break;
            case 'headerimage':
                UserProfileModel::checkOwnership($id);
                $profile = UserProfileModel::getUserProfile($id);
                $paths['header'] = $profile->company_header_path;
                $returnpath = 'profiles/edit/'.$id;
                UserProfileModel::updateUserProfile('company_header_path','',$id);
                break;
            case 'logoimage':
                UserProfileModel::checkOwnership($id);
                $profile = UserProfileModel::getUserProfile($id);
                $paths['logo'] = $profile->company_logo_path;
                $returnpath = 'profiles/edit/'.$id;
                UserProfileModel::updateUserProfile('company_logo_path','',$id);
                break;
            case 'platformlogo':
                Auth::checkForSuperAdmin();
                $paths['platformlogo'] = Config::getFromDB('MarketLogo');
                $returnpath = 'admin/settings';
                AdminModel::updateSettings('MarketLogo','value_text','');
                break;
            case 'platformheader':
                Auth::checkForSuperAdmin();
                $paths['header'] = Config::getFromDB('MarketHeader');
                $returnpath = 'admin/settings';
                AdminModel::updateSettings('MarketHeader','value_text','');
                break;
            case 'platformbackground':
                Auth::checkForSuperAdmin();
                $paths['background'] = Config::getFromDB('MarketBackground');
                $returnpath = 'admin/settings';
                AdminModel::updateSettings('MarketBackground','value_text','');
                break;
        }
        self::deleteImages($paths);
        return $returnpath;
    }

    public static function deleteImages($paths, $feedback = true)
    {
        $upload_path = Config::get('PATH_UPLOADS');
        $i = 0;
        foreach ($paths as $type => $path) {
            $img = explode(':', $path);
            switch ($type) {
                case 'offer':
                    $images = array('offer_big', 'offer_medium', 'offer_small');
                    break;
                case 'header':
                    $images = array('header_big', 'header_medium', 'header_small');
                    break;
                case 'logo':
                    $images = array('logo_big', 'logo_medium', 'logo_small');
                    break;
                case 'platformlogo':
                    $images = array('logo_big', 'logo_medium', 'logo_small','logo');
                    break;
                case 'background':
                    $images = array('background_big', 'background_medium', 'background_small');
                    break;
            }
            foreach ($images as $image) {
                $curimage = $upload_path.$img[0].$image.$img[1];
                if (file_exists($curimage)) {
                    unlink($curimage);
                }
                $folder_path = $img[0];
            }
            $i++;
        }
        if ($i > 0 && is_dir($upload_path.$folder_path)) {
            if (!in_array($type,array('header','logo','platformlogo','background'))) {
                rmdir($upload_path.$folder_path);
            }
            if ($feedback === true) {
                Session::add('feedback_positive', Text::get('FEEDBACK_IMAGE_DELETED'));
            }
        }
    }

    public static function uploadFiles($data)
    {
        if (Session::userIsLoggedIn() && Session::userIsAdmin()) {
            $prefix = Config::get('DB_PREFIX');
            $tableName = Plugin::getConfig('imgedit', 'database')['name'];
            $database = DatabaseFactory::getFactory()->getConnection();

            $name = substr($data["name"], 0, strpos($data["name"], "."));
            $name = Helper::slugify($name);

            $sql = "SELECT id FROM ".$prefix.$tableName." WHERE name = :img_name";
            $query = $database->prepare($sql);
            $query->bindParam(':img_name', $name, PDO::PARAM_STR);
            $query->execute();
            $no = $query->rowCount();
            if ($no > 0) {
                $name = $name.'_'.($no + 1);
            }

            if ($data['img_small'] != '') {
                $status1 = self::makeImage('small',
                                           $data['img_small'],
                                           $name,
                                           $data['type']);
            }
            if ($status1 == true && $data['img_medium'] != '') {
                $status2 = self::makeImage('medium',
                                           $data['img_medium'],
                                           $name,
                                           $data['type']);
            }
            if ($status2 == true && $data['img_big'] != '') {
                $status3 = self::makeImage('big',
                                           $data['img_big'],
                                           $name,
                                           $data['type']);
            }
            if ($status3 == true && $data['img_original'] != '') {
                $status4 = self::makeImage('original',
                                           $data['img_original'],
                                           $name,
                                           $data['type']);
            }

            if ($status3 == true || $status4 == true) {
                $userid = Session::get('user_id');

                $sql = "INSERT INTO ".$prefix.$tableName."
                            (name,
                             created,
                             type,
                             alt,
                             title,
                             tags,
                             userid)
                        VALUES
                            (:img_name,
                             NOW(),
                             :img_type,
                             :img_alt,
                             :img_title,
                             :img_tags,
                             :img_userid)";
                $query = $database->prepare($sql);
                $query->bindParam(':img_name',  $name,          PDO::PARAM_STR);
                $query->bindParam(':img_type',  $data['type'],  PDO::PARAM_STR);
                $query->bindParam(':img_alt',   $data['alt'],   PDO::PARAM_STR);
                $query->bindParam(':img_title', $data['title'], PDO::PARAM_STR);
                $query->bindParam(':img_tags',  $data['tags'],  PDO::PARAM_STR);
                $query->bindParam(':img_userid',$userid,        PDO::PARAM_INT);
                if ($query->execute() && $query->rowCount() == 1) {
                    return array(
                        'status'    => 'success',
                        'name'      => $name,
                        'message'   => '');
                } else {
                    return array(
                        'status'    => 'error',
                        'name'      => $name,
                        'message'   => 'could not save image to db');
                }
            } else {
                return array(
                    'status'    => 'error',
                    'message'   => '');
            }
        } else {
             return array(
                    'status'    => 'error',
                    'message'   => '');
        }
    }

    public static function makeImage($area, $img, $name, $type)
    {
        $base_path = Config::get('PATH_UPLOADS').'upload/';
        $year = date('Y');
        $week = date('W');
        if ($type == 'jpg' || $type == 'jpeg') {
            $ending = $type;
            $img = str_replace('data:image/jpeg;base64,', '', $img);
            $img = str_replace(' ', '+', $img);
        }

        $path = $base_path.$area.'/'.$year.'/'.$week.'/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        $data = base64_decode($img);
        $file = $path . $name . '.' . $ending;
        $success = file_put_contents($file, $data);

        return $success;
    }

}
