<?php

namespace manager\controllers;


use dektrium\user\models\Profile;
use dektrium\user\models\User;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;


class UserexController extends BaseController
{

	public static $story_dir = 'images/users';
    /**
     * Displays a single User model.
     * @param int $id id
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionIndex($id)
    {
        $model = $this->findModel($id);

        if ($model && $this->request->isPost ) {
			$name = $_FILES['User']['tmp_name']['photo'];
			if (is_uploaded_file($name)) {
				$post = \Yii::$app->request->post();
				$pcut = isset($post['cropping'])?$post['cropping']:false;
				$file_tmp = \Yii::getAlias('@webroot').'/'.static::$story_dir."/".basename($name);
				if( move_uploaded_file($_FILES['User']['tmp_name']['photo'], $file_tmp) ){

					list($width, $height) = getimagesize($file_tmp);
					if( $pcut ){
						$cut = ['x'=>round($pcut['x']), 'y'=>round($pcut['y']), 'w'=>round($pcut['width']), 'h'=>round($pcut['height'])];

						$name = basename($id."_sm.jpg");
						$cutfile = \Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
						$this->generateImageCrop($file_tmp, $cutfile, 128, 128, $cut, ['sharpen' => 10]);

						$name = basename($id."_norm.jpg");
						$cutfile = \Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
						$this->generateImageCrop($file_tmp, $cutfile, 256, 256, $cut, ['sharpen' => 5]);
					}
					unlink($file_tmp);
				}
			}
            return $this->redirect(['/user/admin/index']);
        }

        return $this->render('view', [
            'model' => $this->findModel($id), 'obj' => $this
        ]);
    }

    public function generateImageCrop( $ifile, $ofile, $ww, $hh, $param )
    {
		// to do add rotate, etc
		extract( $param );
		list($width, $height) = getimagesize($ifile);
		$addp = '';
		if( strrpos($ofile, '.webp') == strlen($ofile) - strlen('.webp') )
		{
			$addp = " -background '#FFFFFF' -alpha off -strip Plane -quality 88 -define webp:method=6 "; //-interlace
		}
		if(isset($sharpen))
		{
			$addp = $addp." -sharpen ".$sharpen;
		}
		$addp .= " -quality 80";
		umask(0113);
		exec("convert -define jpeg:size=".$width."x".$height."+0+0 $ifile -crop ".$w."x".$h."+".$x."+".$y." -thumbnail ".$ww."x".$hh."^ $addp -gravity center $ofile" );
    }

    /**
     * Finds the Authors model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param int $id id
     * @return Authors the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne(['id' => $id])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
