<?php

/**
 * Manage Product Overlogo Decorations - 
 *
 * PHP version 7.2
 *
 * @category  Product_Overlogo
 * @package   Overlogo_Settings
 * @author    Sanjeeb Kumar Dakhinaray <steve@imprintnext.com>
 * @copyright 2020-2021 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace App\Modules\OverLogo\Controllers;

use App\Modules\DecorationAreas\Models\PrintArea;
use App\Modules\PrintProfiles\Models as PrintProfileModels;
use App\Modules\Products\Models\AppUnit;
use App\Modules\Products\Models\AttributePriceRule;
use App\Modules\Products\Models\DecorationObjects;
use App\Modules\Products\Models\ProductSection;
use Illuminate\Database\Capsule\Manager as DB;
use ProductStoreSpace\Controllers\StoreProductsController;
use App\Modules\Products\Controllers\ProductConfiguratorController;
use App\Modules\OverLogo\Controllers\RenderImageController;

use App\Modules\OverLogo\Models\ProductOverlogoSetting;
use App\Modules\OverLogo\Models\ProductOverlogoSide;
use App\Modules\OverLogo\Models\ProductOverlogoDecorationSetting;
use App\Modules\OverLogo\Models\OverlogoImage;

/**
 * Product Decoration Controller
 *
 * @category                Product_Decoration
 * @package                 Product
 * @author                  Sanjeeb Ku. Dakhinaray <steve@imprintnext.com>
 * @license                 http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link                    http://inkxe-v10.inkxe.io/xetool/admin
 * @SuppressWarnings(PHPMD)
 */
class ProductsOverLogoController extends StoreProductsController
{

    public function removeOverlogoSession($request, $response, $args)
    {
        unset($_SESSION['client_logo']);
        return (1);
    }
    /**
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $storeId   Store Id
     * @param $browserId Browser Id
     *
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Overlogo Image
     */

    public function getLogoImage($request, $response, $args)
    {
        $uploadLogoDir = ASSETS_PATH_R . CONVERT_FOLDER;
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('No image found', 'error'),
        ];
        $browserId = to_int($args['browser_id']);
        $overLogoImageObj = new OverlogoImage();
        $overLogoImageSettingGet = $overLogoImageObj->where(
            'browser_id',
            $browserId
        )->orderBy('xe_id', 'desc');
        if ($overLogoImageSettingGet->count() > 0) {
            $overLogoImageSettingGet = $overLogoImageSettingGet->first()->toArray();
            $overlogoImage = $overLogoImageSettingGet['file_name'];
            $uploadLogoimg = $uploadLogoDir . $overlogoImage;
            $jsonResponse = [
                'status' => 1,
                'overlogo' => $uploadLogoimg,
            ];
        }
        return response(
            $response,
            ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }
    /**
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $storeId   Store Id
     * @param $product_id Product Id
     *
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Overlogo Sides with decoration detail
     */
    public function getProductOverlogo($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $productOverlogoData = [
            'status' => 0,
            'message' => message('Overlogo Data', 'error'),
            'id' => null,
            'sides' => [],
        ];
        if (isset($args['product_id']) && $args['product_id'] > 1) {
            $productKey = to_int($args['product_id']);

            $productOverlogoObj = new ProductOverlogoSetting();
            $productOverlogoSettingGet = $productOverlogoObj->where(
                'product_id',
                $productKey
            );
            if ($productOverlogoSettingGet->count() > 0) {
                $productOverlogoSettingGet = $productOverlogoSettingGet->first()->toArray();
                $overlogoSettingId = $productOverlogoSettingGet['xe_id'];
                $productOverlogoData = [];
            }
            $productOLsideDetails = $this->getOverlogoSideDetails($request, $response, $overlogoSettingId);
            if (!empty($productOLsideDetails)) {
                $productOverlogoData = [
                    'id' => $overlogoSettingId,
                    'sides' => $productOLsideDetails,
                    'status' => 1,
                ];
            }
            if (isset($args['is_internal']) && $args['is_internal'] == 1) {
                return $productOverlogoData;
            } else {
                return response(
                    $response,
                    ['data' => $productOverlogoData, 'status' => $serverStatusCode]
                );
            }
        } else {
            return response(
                $response,
                ['data' => $productOverlogoData, 'status' => $serverStatusCode]
            );
        }
    }
    /**
     * POST: Save Product Overlogo
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $storeId   Store Id
     * @param $product_id Product Id
     *
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Status and Overlogo Setting Id
     */
    public function saveProductOverlogo($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Overlogo Decoration Setting', 'error'),
        ];
        $jsonResponse = [];
        $allPostVars = $request->getParsedBody();

        $storeId = $allPostVars['store_id'] ? $allPostVars['store_id'] : 1;
        // Save Product Decorations
        $prodOverSettInsId = $this->saveOverlogoProductSetting(
            $request,
            $response,
            $allPostVars,
            $storeId
        );
        $jsonResponse = [
            'status' => 1,
            'id' => $prodOverSettInsId,
            'message' => message('Product Overlogo Decoration Setting', 'saved'),
        ];
        return response(
            $response,
            ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }
    /**
     * POST: Save Product Overlogo Product Setting
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $storeId   Store Id
     * @param $product_id Product Id
     *
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Overlogo Setting ID
     */
    protected function saveOverlogoProductSetting($request, $response, $allPostVars, $storeId)
    {
        // Processing for Table: product_overlogo_settings
        if (!empty($allPostVars['product_id'])) {
            $overlogoSettData = [
                'store_id' => $storeId,
                'product_id' => $allPostVars['product_id'],
                'is_overlogo' => 1,
            ];
            $overlogoSetting = new ProductOverlogoSetting($overlogoSettData);
            // Check old Record assign Overlogo setting ID
            $checkRecord = $overlogoSetting->where(
                ['product_id' => $allPostVars['product_id'], 'store_id' => $storeId]
            );
            if ($checkRecord->count() > 0) {
                $checkRecord = $checkRecord->first()->toArray();
                $overlogoSettingId = $checkRecord['xe_id'];
            } else {
                $overlogoSetting->save();
                $overlogoSettingId = $overlogoSetting->xe_id;
            }
        }
        // Save Ovelogo Decoration Sides
        $this->saveOverlogoDecorationSides($request, $response, $allPostVars, $overlogoSettingId);
        return $overlogoSettingId;
    }
    /**
     * POST: Save Product Overlogo Decoration Sides
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return 
     */
    public function saveOverlogoDecorationSides($request, $response, $allPostVars, $overlogoSettingId)
    {
        $ProductId = $allPostVars['product_id'];
        $storeId = $allPostVars['store_id'] ? $allPostVars['store_id'] : 1;
        $getStoreProduct = $this->getProducts(
            $request,
            $response,
            ['id' => $ProductId, 'store_id' => $storeId]
        );
        $imagePath = $getStoreProduct['products']['images']['0']['src'];
        list($width, $height) = !empty($imagePath) ? getimagesize($imagePath) : '';
        // Processing for Table: product_sides, product_decoration_settings
        $imageSides = $allPostVars['sides'];
        // Clean Old Record of Over Logo sides
        $productOverlogoSide = new ProductOverlogoSide();
        $checkSideRecords = $productOverlogoSide->where(
            ['product_setting_id' => $overlogoSettingId]
        );
        if ($checkSideRecords->count() > 0) {
            $checkSideRecords->delete();
        }
        // Clean Old Record of Over Logo sides Decoration
        $prodDecoSettInit = new ProductOverlogoDecorationSetting();
        $checkDecoRecords = $prodDecoSettInit->where(
            ['product_setting_id' => $overlogoSettingId]
        );
        if ($checkDecoRecords->count() > 0) {
            $checkDecoRecords->delete();
        }
        if (!empty($overlogoSettingId) && !empty($imageSides)) {
            foreach ($imageSides as $productSideData) {
                $productOverlogoSide = new ProductOverlogoSide(
                    [
                        'product_setting_id' => $overlogoSettingId,
                        'side_name' => $productSideData['name'],
                        'is_visible' => $productSideData['is_visible'] ? $productSideData['is_visible'] : 0
                    ]
                );
                $productOverlogoSide->save();
                $prodOLSideId = $productOverlogoSide->xe_id;
                foreach ($productSideData['logo_position'] as $prodSideKey => $productOLDecoSetting) {
                    $prodDecoSettRecord[$prodSideKey] = $productOLDecoSetting;
                    $prodDecoSettRecord[$prodSideKey]['product_setting_id'] = $overlogoSettingId;
                    $prodDecoSettRecord[$prodSideKey]['product_side_id'] = $prodOLSideId;
                    $prodDecoSettRecord[$prodSideKey]['print_area_id'] = 0;
                    $prodDecoSettRecord[$prodSideKey]['logo_position']
                        = isset($productSideData['logo_position'][$prodSideKey])
                        ? json_encode($productSideData['logo_position'][$prodSideKey], true)
                        : "{}";
                    $prodDecoSettRecord[$prodSideKey]['logo_position']
                        = isset($productSideData['logo_position'][$prodSideKey])
                        ? json_encode($productSideData['logo_position'][$prodSideKey], true)
                        : "{}";
                    $prodDecoSettRecord[$prodSideKey]['height'] = isset($height) ? $height : 1000;
                    $prodDecoSettRecord[$prodSideKey]['width'] = isset($width) ? $height : 1000;
                    $prodDecoSettInit = new ProductOverlogoDecorationSetting(
                        $prodDecoSettRecord[$prodSideKey]
                    );
                    $prodDecoSettInit->save();
                    $prodDecoSettInit->xe_id;
                }
            }
        }
    }
    /**
     * GET: Overlogo Side Detail
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $overlogoSettingId Overlogo Setting ID
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Overlogo sides with decoration in array
     */
    private function getOverlogoSideDetails($request, $response, $overlogoSettingId)
    {
        $productOverlogoSide = new ProductOverlogoSide();
        $checkSideRecords = $productOverlogoSide->where(
            ['product_setting_id' => $overlogoSettingId]
        );
        $productDecorationSettingData = array();
        if ($checkSideRecords->count() > 0) {
            $checkRecords = $checkSideRecords->get()->toArray();
            foreach ($checkRecords as $sideKey => $value) {
                $overlogoSideId = $value['xe_id'];
                $productOverlogoSideDeco = new ProductOverlogoDecorationSetting();
                $checkSideDecoRecords = $productOverlogoSideDeco->where(
                    ['product_side_id' => $overlogoSideId]
                );
                $side_deco_detail = array();
                if ($checkSideDecoRecords->count() > 0) {
                    $checkRecords = $checkSideDecoRecords->get()->toArray();
                    foreach ($checkRecords as $decoKey => $decoValue) {
                        $logoPositions = json_clean_decode($decoValue['logo_position'], true);
                        $side_deco_detail[$decoKey] = $logoPositions;
                        $height = $decoValue['height'];
                        $width = $decoValue['width'];
                    }
                    $productDecorationSettingData[$sideKey]['id'] = $value['xe_id'];
                    $productDecorationSettingData[$sideKey]['name'] = $value['side_name'];
                    $productDecorationSettingData[$sideKey]['logo_position'] = $side_deco_detail;
                    $productDecorationSettingData[$sideKey]['height'] = $height;
                    $productDecorationSettingData[$sideKey]['width'] = $width;
                }
            }
        }
        return ($productDecorationSettingData);
    }
    /**
     * POST: Overlogo Image
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Json of  removed_edges , removed_white , fill_outline concat with api
     */
    public function uploadLogoImage($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 1,
            'message' => message('Overlogo Image', 'error'),
        ];
        $uploadedLogo = $request->getUploadedFiles();
        if (array_key_exists('image', $uploadedLogo)) {
            $imageName = do_upload('image', path('abs', 'overlogo'), [], 'string');
            $new_file_name = (explode(".", $imageName));
            $outputFile = $new_file_name[0];
            $OverlogoPath = ASSETS_PATH_W . OVERLOGO_FOLDER;

            exec("convert " . $OverlogoPath . "{$imageName} -background white -flatten -alpha off -monochrome " . $OverlogoPath . "{$outputFile}.pnm && potrace --svg --flat " . $OverlogoPath . "{$outputFile}.pnm");
            file_get_contents($OverlogoPath . "{$outputFile}.svg");
            unlink($OverlogoPath . "{$outputFile}.pnm");
            unlink($OverlogoPath . "{$outputFile}.svg");
            $jsonResponse =  json_encode(array(
                'success' => true,
                'removed_edges' => BASE_URL . OVERLOGO_FOLDER . 'processlogo?action=removed_edges&image_name=' . $imageName . '&' . time(),
                'removed_white' => BASE_URL . OVERLOGO_FOLDER . 'processlogo?action=removed_white&image_name=' . $imageName . '&' . time(),
                'fill_outline' => BASE_URL . OVERLOGO_FOLDER . 'processlogo?action=fill_outline&image_name=' . $imageName . '&' . time(),
                'solid_image' => false
            ));
            return response(
                $response,
                ['data' => $jsonResponse, 'status' => $serverStatusCode]
            );
        } else {
            return response(
                $response,
                ['data' => $jsonResponse, 'status' => $serverStatusCode]
            );
        }
    }
    /**
     * GET: Uploaded Logo
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Converted image .
     */
    public function processLogo($request, $response, $args)
    {
        $action = $request->getQueryParam('action');
        $image_name = $request->getQueryParam('image_name');
        $OverlogoPath = ASSETS_PATH_W . OVERLOGO_FOLDER;

        if (isset($action) && isset($image_name)) {
            switch ($action) {
                case 'removed_edges':
                    $command = 'convert ' . $OverlogoPath . $image_name . ' -alpha set -bordercolor white -border 1 -fill none -fuzz 3% -draw "color 0,0 floodfill" -shave 1x1 PNG:-';
                    break;
                case 'removed_white':
                    $command = 'convert  ' . $OverlogoPath . $image_name . ' -fuzz 10% -transparent white PNG:-';
                    break;
                case 'fill_outline':
                    $command = 'convert \( ' . $OverlogoPath . $image_name . ' -trim +repage -bordercolor white -border 50 -fuzz 5% -fill none -draw "matte 0,0 floodfill" -alpha off -write mpr:img -alpha on -alpha extract -morphology dilate disk:20 -blur 0x1 -level 0x50% -write mpr:msk1 +delete \) \( mpr:msk1 -negate -fill white -opaque black -blur 0x10 -fill white -opaque white -write mpr:msk2 +delete \) \( mpr:msk1 -morphology edgein diamond:1 -negate -write mpr:edg +delete  \) mpr:img mpr:msk1 -alpha off -compose copy_opacity -composite mpr:msk2 -reverse -compose over -composite mpr:edg -compose multiply -composite -trim -alpha set -bordercolor white -border 1 -fill none -fuzz 3% -draw "color 0,0 floodfill" -shave 1x1 PNG:-';
                    break;
                default:
                    die('please select valid options');
            }
            header("HTTP/1.1 200 OK");
            header("Content-Type: image/jpeg");
            ob_end_clean();
            echo shell_exec($command);
            exit;
        }
    }
    /**
     * POST: Logo
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Json of converted logo .
     */
    public function saveUploadedLogo($request, $response, $args)
    {
        $uploadedLogo = $request->getUploadedFiles();
        if (array_key_exists('user_logo', $uploadedLogo)) {
            $imageName = do_upload('user_logo', path('abs', 'convert'), [], 'string');
            $jsonResponse = json_encode(array(
                'success' => false,
                'message' => 'Please upload image'
            ));

            $uploadLogoDir = ASSETS_PATH_W . CONVERT_FOLDER;
            $logoName = uniqid() . '.png';
            $logoPath = $uploadLogoDir . $logoName;
            $uploadedLogoPath = $uploadLogoDir . $imageName;
            list($logoWidth, $logoHeight) = getimagesize($uploadedLogoPath);
            $maxSize = max($logoHeight, $logoWidth);
            shell_exec("convert {$uploadedLogoPath} -background transparent -gravity center -extent {$maxSize}x{$maxSize}  {$logoPath}");
            create_thumb_aspect(
                $logoPath,
                "150_" . $logoName,
                $uploadLogoDir,
                [100]
            );
            create_thumb_aspect(
                $logoPath,
                "75_" . $logoName,
                $uploadLogoDir,
                [75]
            );
            unlink($uploadedLogoPath);

            $allPostPutVars = $request->getParsedBody();
            $browserId = $allPostPutVars['browser_id'];
            $overlogoImageData = [
                'browser_id' => $browserId,
                'file_name' => $logoName,
            ];
            $overlogoImageSetting = new OverlogoImage($overlogoImageData);
            $overlogoImageSetting->save();
            $_SESSION['client_logo'] = $logoName;
            $jsonResponse = json_encode(array(
                'success' => true,
                'image_url' => $logoName
            ));
        }
        return  $jsonResponse;
    }
    /**
     * Get: Converted Product image
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @author steve@imprintnext.com
     * @date   7 Sept 2021
     * @return Image product image with logo.
     */
    public function generateProductImage($request, $response, $args)
    {
        $pid = $request->getQueryParam('pid');
        $pImage = explode('_', $pid);
        $productId = $pImage[0];

        $args['product_id'] = $productId;
        $args['is_internal'] = 1;
        $OverlogoDetail = $this->getProductOverlogo($request, $response, $args);
        $logoPosition = $OverlogoDetail['sides'][0]['logo_position'];
        $rows = [
            'product_id' => $productId,
            'logo_position' => json_encode($logoPosition, true),
            'height' => $OverlogoDetail['sides'][0]['height'],
            'width' => $OverlogoDetail['sides'][0]['width'],
        ];
        new RenderImageController($rows);
    }
}
