<?php
/**
 * @copyright   Copyright (c) 2015 Multiple Image Upload. All rights reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.plugin.plugin');

/**
 * System - multipleimageupload Plugin
 *
 * @package     Joomla.Plugin
 * @subpakage   MultipleImageUpload.multipleimageupload
 */
class plgSystemmultipleimageupload extends JPlugin {

    /**
     * Constructor.
     *
     * @param   $subject
     * @param   array $config
     */
    function __construct(&$subject, $config = array()) {
        // call parent constructor
        parent::__construct($subject, $config);
    }
    function onBeforeRender()
    {


        $app = JFactory::getApplication()->input;
        $task = $app->get("task");

        $prid = JRequest::getVar('virtuemart_product_id');

        if ($prid == NULL)
        {
            $productid = 0;
        }
        else
        {

            if(is_array($prid)){

               $productid = $prid[0];
                   
            }else{

               $productid = $prid;
            }
        }



        $document = JFactory::getDocument();

        if (($app->get('option') == "com_virtuemart" && $app->get('view') == "product" && $app->get('task') == "add") ||
            ($app->get('option') == "com_virtuemart" && $app->get('view') == "product" && $app->get('task') == "edit"))
        {
            $document->addScript(JUri::root().'media/plg_multiimageupload/jquery.fileuploadmulti.min.js');
            $document->addStyleSheet(JUri::root().'media/plg_multiimageupload/uploadfilemulti.css');

            $document->addScriptDeclaration("
                jQuery(document).ready(function(){

                    jQuery('.selectimage').append('<div id=mulitplefileuploader>Upload</div><div id=status></div>');
                    var settings = {
                    url: 'index.php?option=com_ajax&plugin=multipleimageupload&control=multipleprimage&productid=".$productid."',
                    method: 'POST',
                    allowedTypes:'jpg,png,gif,doc,pdf,zip',
                    fileName: 'myfile',
                    multiple: true,
                        onSuccess:function(files,data,xhr)
                        {
                            jQuery('#status').html('<font color=green>Upload is Success</font>');

                        },
                        afterUploadAll:function()
                        {
                           location.reload();
                        },
                        onError: function(files,status,errMsg)
                        {

                            jQuery('#status').html('<font color=red>Upload is Failed</font>');
                        }
                    }
                    jQuery('#mulitplefileuploader').uploadFile(settings);

                });

                                            ");




                }
        }

        function onAfterRender()
        {
            $app = JFactory::getApplication()->input;
            $control = $app->get("control");
            $productid = $app->get("productid");


            if ($control == "multipleprimage")
                {
                    //If directory doesnot exists create it.
                    $path = '../images/virtuemart';
                    if(is_dir($path))
                    {   
                        $output_dir = JPATH_ROOT."/images/virtuemart/product/";
                        $imagepath = "images/virtuemart/product/";     
                    }
                    else
                    {
                        $output_dir = JPATH_ROOT."/images/stories/virtuemart/product/";
                        $imagepath = "images/stories/virtuemart/product/";
                    }
                
                    if(isset($_FILES["myfile"]))
                    {
                        $ret = array();

                        $error =$_FILES["myfile"]["error"];
                       {

                            if(!is_array($_FILES["myfile"]['name'])) //single file
                            {
                                $RandomNum   = time();
                                $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name']));
                                $ImageType      = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.
                                $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
                                $ImageExt       = str_replace('.','',$ImageExt);
                                $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
                                $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
                                move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $NewImageName);

                                $db = JFactory::getDbo();
                                // Create a new query object.
                                $query = $db->getQuery(true);

                                // Insert columns.
                                $columns = array('virtuemart_vendor_id', 'file_title', 'file_mimetype', 'file_type','file_url','published','created_on','modified_on','created_by','modified_by');

                                // Insert values.
                                $values = array(1, '"'.$_FILES['myfile']['name'].'"','"'.$_FILES['myfile']['type'].'"',"'product'",'"'.$imagepath. $NewImageName.'"',1,'"'.date('Y-m-d H:i:s').'"','"'.date('Y-m-d H:i:s').'"','"'.JFactory::getUser()->id.'"','"'.JFactory::getUser()->id.'"');

                                // Prepare the insert query.
                                $query
                                    ->insert($db->quoteName('#__virtuemart_medias'))
                                    ->columns($db->quoteName($columns))
                                    ->values(implode(',', $values));

                                // Set the query using our newly populated query object and execute it.
                                $db->setQuery($query);
                                $db->execute();
                                $getLastMediaid = $db->insertid();

                                //$productid
                                if ($productid != NULL)
                                {

                                    // Create a new query object.
                                        $query = $db->getQuery(true);

                                        // Select all records from the user profile table where key begins with "custom.".
                                        // SELECT MAX(ordering) FROM `jos_virtuemart_product_medias` where `virtuemart_product_id` = 1214
                                        // Order it by the ordering field.
                                        $query->select('MAX('.$db->quoteName('ordering').')');
                                        $query->from($db->quoteName('#__virtuemart_product_medias'));
                                        $query->where($db->quoteName('virtuemart_product_id') . ' LIKE '. $productid);


                                        // Reset the query using our newly populated query object.
                                        $db->setQuery($query);

                                        // Load the results as a list of stdClass objects (see later for more options on retrieving data).
                                        $ordering = $db->loadResult();
                                        $ordering = $ordering + 1;

                                        // Create a new query object.
                                        $query = $db->getQuery(true);

                                        // Insert columns.
                                        $columns = array('virtuemart_product_id', 'virtuemart_media_id', 'ordering');

                                        // Insert values.
                                        $values = array($productid,$getLastMediaid,$ordering);

                                        // Prepare the insert query.
                                        $query
                                            ->insert($db->quoteName('#__virtuemart_product_medias'))
                                            ->columns($db->quoteName($columns))
                                            ->values(implode(',', $values));

                                        // Set the query using our newly populated query object and execute it.
                                        $db->setQuery($query);
                                        $db->execute();

                                }

                                $ret[$fileName]= $output_dir.$NewImageName;

                            }
                            else
                            {

                                $fileCount = count($_FILES["myfile"]['name']);
                                for($i=0; $i < $fileCount; $i++)
                                {
                                    $RandomNum   = time();

                                    $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i]));
                                    $ImageType      = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.

                                    $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
                                    $ImageExt       = str_replace('.','',$ImageExt);
                                    $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
                                    $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

                                    $ret[$NewImageName]= $output_dir.$NewImageName;
                                    move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$NewImageName );
                                }
                            }
                        }

                        echo json_encode($ret);die;

                    }

                }

        }






}