<?php

namespace Market\ZodacoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Market\ZodacoBundle\Entity\Products;
use Market\ZodacoBundle\Entity\Notifications;

class UploadController extends BaseController {

    public function indexAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $check = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$check) {
            $session->clear();
            return $this->redirect($this->generateUrl("login"));
        }

        $list = $em->getRepository('MarketZodacoBundle:Categories')->_getCatlist();

        $arrReturn = array('list' => $list);
        return $this->render('MarketZodacoBundle:Upload:index.html.php', $arrReturn);
    }

    public function formAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$checkUser) {
            $session->clear();
            return $this->redirect($this->generateUrl("login"));
        }

        $error = 0;
        $category = isset($_REQUEST["category"]) ? intval($_REQUEST["category"]) : 0;
        if ($category <= 0) {
            return $this->redirect($this->generateUrl("_homepage"));
        }

        $check = $em->getRepository('MarketZodacoBundle:Categories')->_getSublist($category);
        if (!$check) {
            return $this->redirect($this->generateUrl("upload"));
        }

        if ($request->getMethod() == 'POST') {
            $title = $request->request->get("title", "");
            $short_title = $request->request->get("short_title", "");
            $details = $request->request->get("details", "");
            $upanh = $request->request->get("upanh", "");
            $licon = $request->request->get("licon", "");
            $screenshot = $request->request->get("screenshot", "");
            $main_file = $request->request->get("main_file", "");
            $cid = (int) $request->request->get("cid", 0);
            $demoUrl = $request->request->get("demo_url", "");
            $videoUrl = $request->request->get("video_url", "");
            $tags = $request->request->get("tags", "");

            $price = floatval($request->request->get("price", 0));
            if ($price < 0) {
                $price = 0;
            }
            $price2 = floatval($request->request->get("price2", 0));
            if ($price2 < 0) {
                $price2 = 0;
            }
            $not_own = $request->request->get("not_own", 0);
            if ($not_own == "on") {
                $not_own = 1;
            } else {
                $not_own = 0;
            }
            $checkCid = $em->getRepository('MarketZodacoBundle:Categories')->findOneBy(array("mid" => $category, "id" => $cid));
            if ($title && $short_title && $details && $upanh && $licon && $screenshot && $main_file && $cid && $tags && $price && $not_own && $checkCid) {
                try {
                    $newProduct = new Products();
                    $newProduct->setActive(0)->setTitle($title)->setDetails($details)->setShortDetails($short_title);
                    $newProduct->setCategories($checkCid);
                    $newProduct->setDemoUrl($demoUrl)->setTrend(0)->setTags($tags)->setTotalRate(0)->setTotalSale(0);
                    $newProduct->setVideoUrl($videoUrl)->setTotalComment(0);
                    $newProduct->setNotOwn($not_own);
                    $newProduct->setUsers($checkUser);
                    $newProduct->setViews(0);
                    $newProduct->setFeature(0);
                    $newProduct->setFreeMonth(0);
                    $newProduct->setIcon($upanh)->setStatus(0);
                    $newProduct->setPreview($licon)->setUpdateIcon("")->setUpdateMainFile("")->setUpdatePreview("")->setUpdateScreenshots("")->setUpdateTitle("");
                    $newProduct->setMainFile($main_file)->setAverageRate(0);
                    $newProduct->setScreenshots($screenshot)->setPId($category)->setPrice($price)->setPricePlus($price2);
                    $a = new \Datetime();
                    $newProduct->setCreatedAt($a)->setVersionAt($a);
                    $newProduct->setUpdatedAt($a);

                    $em->persist($newProduct);

                    $em->getRepository('MarketZodacoBundle:Reports')->updateReport('c.products');

                    $content = $this->get('translator')->trans('Hi') . ' ' . $checkUser->getUsername() . ',<br>' .
                            $this->get('translator')->trans('Your work has successfully been submitted for review to the Zodaco Team.') . '<br>' .
                            $this->get('translator')->trans('In most cases, the items are truly inspiring and we are able to quickly review and publish them on the same day they are uploaded.') .
                            '<br><br>' .
                            $this->get('translator')->trans('Your product will be displayed on the marketplace as soon as approved.') . '<br>' .
                            $this->get('translator')->trans('You will receive a notification of approval by email.') . '<br><br>' .
                            $this->get('translator')->trans('Turn your portfolio pieces into earnings.') . '<br>http://www.' . $request->getHost();

                    $noti = new Notifications();
                    $noti->setEmail($checkUser->getEmail());
                    $noti->setReplyEmail('');
                    $noti->setTitle($this->get('translator')->trans("Work submitted to Zodaco Team"));
                    $noti->setContent($content);
                    $em->persist($noti);

                    $em->flush();
                    $session->get('done', 1);
                    return $this->redirect($this->generateUrl("my_products"));
                } catch (Exception $ex) {
                    $error = 1;
                }
            } else {
                $error = 1;
            }
        }

        $arrReturn = array(
            'check' => $check, "error" => $error
        );
        return $this->render('MarketZodacoBundle:Upload:form.html.php', $arrReturn);
    }

    public function imageAction(Request $request) {

        $tmp = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/web";

        $targetFolder = $tmp . '/uploads/tmp/';
        $arrType = array("image/jpeg", "image/png", "image/jpg");
        $allowedExts = array("png", "jpg", "jpeg");

        if (!empty($_FILES)) {
            $sizeUpload = isset($_POST["size"]) ? $_POST["size"] : "64-64";
            $sizeUpload = explode("-", $sizeUpload);
            if (count($sizeUpload) < 2) {
                echo json_encode(array('status' => 0, 'msg' => ''));
                die;
            }
            $maxsize = (int) $sizeUpload[0] * (int) $sizeUpload[1];
            $maxWidth = (int) $sizeUpload[0];
            $maxHeight = (int) $sizeUpload[1];

            $name = (isset($_POST['hash']) && is_numeric($_POST['hash']) && $_POST['hash'] > 0) ? $_POST['hash'] : time();
            $size = getimagesize($_FILES["images2"]['tmp_name']);
            if (!in_array($_FILES["images2"]["type"], $arrType)) {
                echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Invalid type')));
            } else if ($size[0] != $maxWidth || $size[1] != $maxHeight) {
                echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Invalid size!')));
            }  else {
                if ($_FILES["images2"]["error"] == UPLOAD_ERR_OK) {
                    $extension = strtolower(pathinfo($_FILES['images2']['name'], PATHINFO_EXTENSION));
                    if (in_array($extension, $allowedExts)) {
                        move_uploaded_file($_FILES["images2"]["tmp_name"], $targetFolder . sha1(md5($name)) . "." . $extension);
                        echo json_encode(array('status' => 1, 'title' => $_FILES['images2']['name'], 'name' => sha1(md5($name)) . "." . $extension, 'message' => $this->get('translator')->trans('Successfully')));
                    } else {
                        echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Invalid type')));
                    }
                } else {
                    echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Error!')));
                }
            }
        } else {
            echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Please choose file to upload')));
        }

        die;
    }

    public function fileAction(Request $request) {

        $tmp = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/web";

        $targetFolder = $tmp . '/uploads/tmp/';
        $arrType = "application/zip";
        $allowedExts = array("zip");

        if (!empty($_FILES)) {
            $type = isset($_POST["size"]) ? $_POST["size"] : "preview";
            if ($type == "preview") {
                $sizeUpload = (int) $this->container->getParameter('maxPreview');
            } else {
                $sizeUpload = (int) $this->container->getParameter('maxMain');
            }

            $name = (isset($_POST['hash']) && is_numeric($_POST['hash']) && $_POST['hash'] > 0) ? $_POST['hash'] : time();
            $size = round($_FILES["images2"]['size'] / (1024 * 1024));

            if ($_FILES["images2"]["type"] != $arrType) {
                echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Invalid type')));
            } else if ($size > $sizeUpload) {
                echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('File over size!')));
            } else {
                if ($_FILES["images2"]["error"] == UPLOAD_ERR_OK) {
                    $extension = strtolower(pathinfo($_FILES['images2']['name'], PATHINFO_EXTENSION));
                    if (in_array($extension, $allowedExts)) {
                        move_uploaded_file($_FILES["images2"]["tmp_name"], $targetFolder . sha1(md5($name)) . "." . $extension);
                        echo json_encode(array('status' => 1, 'title' => $_FILES['images2']['name'], 'name' => sha1(md5($name)) . "." . $extension, 'message' => $this->get('translator')->trans('Successfully!')));
                    } else {
                        echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Invalid type')));
                    }
                } else {
                    echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Error!')));
                }
            }
        } else {
            echo json_encode(array('status' => 0, 'message' => $this->get('translator')->trans('Please choose file to upload')));
        }

        die;
    }

}
