<?php

include_once("../public/config.php");
include("../public/include_dao.php");
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Onlinestoresetting
require_once('../models/dao/OnlinestoresettingDAO.class.php');
require_once('../models/dto/Onlinestoresetting.class.php');
require_once('../models/mysql/OnlinestoresettingMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinestoresettingMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

/* ======================

  Controller Name :- productController

  OPERTATION in Controller


  ======================== */

//here the global templates
//$smarty->display("header.html");
//here goes the instances and general variables
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//
$onlineStoreSetting = new Onlinestoresetting();
$onlineStoreSettingDAO = new OnlinestoresettingMySqlDAO();
$onlineStoreSettingEX = new OnlinestoresettingMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//check and use the condition that suite this action
//$started_at = microtime(true);

if (empty($do)) {
    //here the permssion check
    //$started_at = microtime(true);
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $onlineStoreSetting = $onlineStoreSettingDAO->load(1);
    $joinConditionWithStore = '';
    if ($onlineStoreSetting->availableStores != "") {
        $joinConditionWithStore = " and storeid in ($onlineStoreSetting->availableStores) ";
    }
    ####2-add normal products
    $count = 0;
    $start = 0;
    $limit = 50;
    $end = $start + $limit;
    $all_products_count = $productExt->getProductsCountForCURLNormal('', $joinConditionWithStore);
    for ($i = $start; $i <= $all_products_count->productId; $i+=$limit) {
        $allproduct = $productExt->queryAllOrderedLimitedSimpleForCurlNormal($start, $limit, '', $joinConditionWithStore);
        foreach ($allproduct as $value) {
            $parcodeString = useSpecializedParcodeDigits($value->productId, $Programsettingdata->specializedParcodeDigits);
            if (!empty($parcodeString) && !empty($value->logo) && $value->logo != "." && $value->logo != "no image") {
                addParcodeToImage($value->logo, $parcodeString, "../views/default/images/product_image/", "../views/default/images/product_image2/");
                $count++;
            }
        }

        //
        $start += $limit;
        $end += $limit;
    }


//    echo 'Cool, that only took ' . (microtime(true) - $started_at) . ' seconds!';

    echo "<span style='color:green'> DONE. </span><br/>";
    print_r("<pre>");
    echo "<div style='border:1px solid green;margin-right:60%'><span style='color:green'> no of products images recreated : " . $count . " </span><br/>";
    print_r("</pre>");
}
/* ---------------------------------------------- */

function addParcodeToImage($imageName, $parcode, $targetDir, $targetDirDestination) {
    global $hosturl;

    $statusMsg = '';
    if (!empty($parcode) && !empty($imageName) && $imageName != "." && $imageName != "no image") {
        // Path configuration
        //$targetDir;$watermarkImagePath//this is comming from user
        ####get parcode image
        $parcodeImageURL = $hosturl . "/library/barcode2/barcode.php?text=$parcode&codetype=code128&size=30&print=true&sizefactor=1.1";
        $parcodeImageName = $targetDirDestination . md5(uniqid(mt_rand(), true)) . '.png';
        file_put_contents($parcodeImageName, file_get_contents($parcodeImageURL));
        $watermarkImagePath = $parcodeImageName;
        ####get product image
        ##if its new image upload it instead of file get and put contents use this
        // Upload file to the server
//        if (move_uploaded_file($_FILES[$hiddenFileName]["tmp_name"], $targetFilePathNewName)) {
//        } else {
//            $statusMsg = "Sorry, there was an error uploading your file.";
//        }
        // File upload path
        $imageName_basename = basename($imageName);
        $targetFilePath = $targetDirDestination . $imageName_basename;
        $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
        // Allow certain file formats//needed for image copy function
        $allowTypes = array('jpg', 'png', 'jpeg');
        $extentionChange = 0;
        if (in_array($fileType, $allowTypes)) {
            $theImageURL = $hosturl . "/views/default/images/product_image/$imageName";
            $theImageName = $targetDirDestination . $imageName;
            file_put_contents($theImageName, file_get_contents($theImageURL));
        } else {
            //$statusMsg = 'Sorry, only JPG, JPEG, and PNG files are allowed to upload.';
            $extentionChange = 1;
            $theImageURL = $hosturl . "/views/default/images/product_image/$imageName";
            $theImageName = $targetDirDestination . md5(uniqid(mt_rand(), true)) . '.png'; //create random name with png extention
            file_put_contents($theImageName, file_get_contents($theImageURL));
        }
        // Load the stamp and the photo to apply the watermark to
        $watermarkImg = imagecreatefrompng($watermarkImagePath);
        switch ($fileType) {
            case 'jpg':
                $im = imagecreatefromjpeg($theImageName);
                break;
            case 'jpeg':
                $im = imagecreatefromjpeg($theImageName);
                break;
            case 'png':
                $im = imagecreatefrompng($theImageName);
                break;
            default:
                $im = imagecreatefromjpeg($theImageName);
        }

        // Set the margins for the watermark
        $marge_right = 0;
        $marge_bottom = 0;

        // Get the height/width of the watermark image
        $sx = imagesx($watermarkImg);
        $sy = imagesy($watermarkImg);

        // Copy the watermark image onto our photo using the margin offsets and
        // the photo width to calculate the positioning of the watermark.
        imagecopy($im, $watermarkImg, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg));

        // Save image and free memory
        imagepng($im, $theImageName);
        imagedestroy($im);
        if (file_exists($parcodeImageName)) {
            unlink($parcodeImageName);
        }
        if ($extentionChange == 1) {
            $image = $targetDirDestination . $imageName;
            file_put_contents($image, file_get_contents($theImageName));
            if (file_exists($theImageName)) {
                unlink($theImageName);
            }
            $theImageName = $image;
        }

        if (file_exists($theImageName)) {
            $statusMsg = "The image with watermark has been uploaded successfully.";
        } else {
            $statusMsg = "Image upload failed, please try again.";
        }
    }
    return array($statusMsg, $theImageName);
}

function useSpecializedParcodeDigits($productId, $specializedParcodeDigits) {
    $preDigits = '';
    if (strlen($productId) != $specializedParcodeDigits) {
        $noDigitsLeft = $specializedParcodeDigits - strlen($productId);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits.='0';
        }
    }
    $newParcode = 'i' . $preDigits . $productId;
    return $newParcode

    ;
}

?>