<?php
/**
 * AdminModel
 * 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 = AdminText::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 = AdminText::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'));
            }
        }
    }
}
