<?php

namespace Market\ZodacoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Market\ZodacoBundle\Entity\HistoriesBought;
use Market\ZodacoBundle\Entity\HistoriesSell;
use Market\ZodacoBundle\Entity\Notifications;

class DefaultController extends BaseController {

    public function indexAction(Request $request) {
        return $this->render('MarketZodacoBundle:Default:index.html.php', array());
    }

    public function indexFakeAction(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));

        $list = $em->getRepository('MarketZodacoBundle:Categories')->_getCatlist();
        $arr_0 = array();
        if ($list) {
            foreach ($list as $key => $value) {
                $tmp = $em->getRepository('MarketZodacoBundle:Products')->_getFeatureByParent($value->getId(), 4);
                if ($tmp) {
                    $arr_0[$value->getId()] = $tmp;
                } else {
                    $arr_0[$value->getId()] = 0;
                }
            }
        }
        $arr = $arr_0;

        $arr1 = array('feature' => $arr, 'list' => $list, "check" => $check);

        return $this->render('MarketZodacoBundle:Default:indexFake.html.php', $arr1);
    }

    public function leftCategoriesAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $list = $em->getRepository('MarketZodacoBundle:Categories')->_getCatlist();
        foreach ($list as $key => $value) {
            $tmp = $em->getRepository('MarketZodacoBundle:Categories')->_getSublistShow($value->getId());
            if ($tmp) {
                $arr_0[$value->getId()] = $tmp;
            } else {
                $arr_0[$value->getId()] = 0;
            }
        }
        $arr = $arr_0;

        $session = $request->getSession();
        $category = (int) $session->get("category");
        $arr1 = array('subCat' => $arr, 'list' => $list, "category" => $category);

        return $this->render('MarketZodacoBundle:Default:leftCategories.html.php', $arr1);
    }

    public function categoriesAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();
        $id = (int) $id;
        $session = $request->getSession();
        $session->set("category", $id);

        $p = isset($_REQUEST['p']) ? (int) $_REQUEST['p'] : 1;
        if (!$p || $p < 1) {
            $p = 1;
        }
        $limit = (int) $this->container->getParameter('limit');
        $cat = $em->getRepository('MarketZodacoBundle:Categories')->findOneById($id);
        if (!$cat) {
            return $this->redirect($this->generateUrl("_homepage"));
        }
        if ($cat->getMid() == 0) {
            $pid = 1;
        } else {
            $pid = 0;
        }
        $total = $em->getRepository('MarketZodacoBundle:Products')->_getCountListByCat($pid, $id);
        $list = $em->getRepository('MarketZodacoBundle:Products')->_getProListByCat($pid, $id, $p, $limit);

        $pager2 = array();
        $pager2['PreviousPage'] = ($p > 1) ? ($p - 1) : $p;
        $pager2['NextPage'] = (ceil($total / $limit) > $p) ? ($p + 1) : $p;
        $pager2['LastPage'] = ceil($total / $limit);
        $pager2['Page'] = $p;



        $arr1 = array('list' => $list, 'page' => $pager2, 'cat' => $cat);

        return $this->render('MarketZodacoBundle:Default:categories.html.php', $arr1);
    }

    public function menuAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $arr_0 = array();
        $list = $em->getRepository('MarketZodacoBundle:Categories')->_getCatlist();
        foreach ($list as $key => $value) {
            $tmp = $em->getRepository('MarketZodacoBundle:Categories')->_getSublistShow($value->getId());
            if ($tmp) {
                $arr_0[$value->getId()] = $tmp;
            } else {
                $arr_0[$value->getId()] = 0;
            }
        }
        $arr = $arr_0;

        $arr1 = array('arr' => $arr, 'list' => $list);

        return $this->render('MarketZodacoBundle:Default:menu.html.php', $arr1);
    }

    public function productsAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();
        $id = (int) $id;

        $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();
        }

        $product = $em->getRepository('MarketZodacoBundle:Products')->findOneById($id);
        if (!$product || $product->getActive() != 1) {
            return $this->redirect($this->generateUrl("_homepage"));
        }

        if ($request->getMethod() == 'POST') {
            $licensetype = (int) $request->request->get("licensetype", 0);
            if (!$check) {
                return $this->redirect($this->generateUrl("login"));
            }

            if ($check->getId() == $product->getUsers()->getId() || $licensetype < 0) {
                return $this->redirect($this->generateUrl("_homepage"));
            }

            $cart = array();
            if ($licensetype == 0) {
                $cart["type"] = 0;
            } else {
                $cart["type"] = 1;
            }
            $cart["id"] = $product->getId();

            $session->set('cart', $cart);

            return $this->redirect($this->generateUrl("cart"));
        } else {
            $product->setViews($product->getViews() + 1);
            $em->persist($product);
            $em->flush();
        }

        $arr1 = array("product" => $product, "login" => $check);

        return $this->render('MarketZodacoBundle:Default:products.html.php', $arr1);
    }

    public function cartAction(Request $request) {
        $em = $this->getDoctrine()->getManager();

        $session = $request->getSession();

        $username = $session->get('username', "");
        $password = $session->get('password', "");
        $cart = $session->get('cart', "");

        $check = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$check) {
            $session->remove("username");
            $session->remove("password");
            return $this->redirect($this->generateUrl("login"));
        }
        if (!$cart || !isset($cart["id"]) || !isset($cart["type"])) {
            $session->remove("cart");
            return $this->redirect($this->generateUrl("_homepage"));
        }

        $id = (int) $cart["id"];
        $type = (int) $cart["type"];

        $product = $em->getRepository('MarketZodacoBundle:Products')->findOneById($id);
        if (!$product || $product->getActive() != 1) {
            $session->remove("cart");
            return $this->redirect($this->generateUrl("_homepage"));
        }
        $error = 0;

        if ($request->getMethod() == 'POST') {
            $seller_id = $product->getUsers()->getId();
            if ($check->getId() == $seller_id) {
                $session->remove("cart");
                return $this->redirect($this->generateUrl("_homepage"));
            }

            if ($type == 0) {
                $price = $product->getPrice();
            } else {
                $price = $product->getPricePlus();
            }

            if (floatval($check->getMoney()) < floatval($price)) {
                return $this->redirect($this->generateUrl("deposit"));
            }

            try {
                $em->getConnection()->beginTransaction();
                $a = new \DateTime();

                $rate = floatval($this->container->getParameter('netMoney'));
                $netMoney = round($price * $rate, 2);

                $bought = new HistoriesBought();
                $bought->setCreatedAt($a)->setUpdatedAt($a)->setDatas("")->setPId($product->getId())->setStatus(1)->setTitle($product->getTitle())->setUserId($check->getId());

                $sell = new HistoriesSell();
                $sell->setPrice($price)->setNetMoney($netMoney)->setCreatedAt($a)->setUpdatedAt($a)->setDatas("")->setPId($product->getId())->setStatus(1)->setTitle($product->getTitle())->setUserId($seller_id);

                $product->setTotalSale($product->getTotalSale() + 1);

                $seller = $em->getRepository('MarketZodacoBundle:Users')->findOneById($seller_id);
                $seller->setTotalSale($seller->getTotalSale() + 1);
                $seller->setMoney($seller->getMoney() + $netMoney);

                $check->setMoney($check->getMoney() - $price);
                
                //Pay for ref
                $checkRef = $em->getRepository('MarketZodacoBundle:Affiliate')->findOneBy(array('user_id' => $check->getId(), 'status' => 0));
                if($checkRef){
                    $payRef = $em->getRepository('MarketZodacoBundle:Users')->findOneById($checkRef->getRefId());
                    if($payRef){
                        $rateRef = floatval($this->container->getParameter('rateRef'));
                        $refMoney = round($netMoney * $rateRef, 2);
                        
                        $payRef->setMoney($payRef->getMoney() + $refMoney);
                        
                        $earnRef = new HistoriesSell();
                        $earnRef->setPrice($refMoney)->setNetMoney($refMoney)->setCreatedAt($a)->setUpdatedAt($a)->setDatas("")->setPId(0)->setStatus(1)->setTitle("Ref Earn")->setUserId($checkRef->getRefId());

                        $checkRef->setStatus(1);
                        
                        $em->persist($checkRef);
                        $em->persist($earnRef);
                        $em->persist($payRef);
                    }
                }

                $url = $this->generateUrl('sale', array(), true);

                $sub = $this->get('translator')->trans("Your product has been purchased!");
                $content = $this->get('translator')->trans('Congratulations') . ' ' . $product->getUsers()->getUsername() . '!<br><br>' .
                        $this->get('translator')->trans('A user has just purchased your item') . ' "' . $product->getTitle() . '".<br>' .
                        $this->get('translator')->trans('For this purchase you earned') . ' $' . $netMoney . '.<br><br>' .
                        $this->get('translator')->trans('Please notice that you can track your sales by visiting') . ' ' . $url . '<br><br>' .
                        $this->get('translator')->trans('Sincerely') . ',<br>' .
                        $this->get('translator')->trans('Zodaco Marketplace') . '<br>http://www.' . $request->getHost();

                $noti = new Notifications();
                $noti->setEmail($product->getUsers()->getEmail());
                    $noti->setReplyEmail('');
                $noti->setTitle($sub);
                $noti->setContent($content);
                $em->persist($noti);

                $em->persist($bought);
                $em->persist($sell);
                $em->persist($product);
                $em->persist($seller);

                $em->flush();
                $em->getConnection()->commit();

                $session->remove("cart");

                return $this->redirect($this->generateUrl("download"));
            } catch (\Exception $e) {
                $error = 1;
                $em->getConnection()->rollback();
            }
        }

        $arr1 = array("product" => $product, "check" => $check, "type" => $type, "error" => $error);

        return $this->render('MarketZodacoBundle:Default:cart.html.php', $arr1);
    }

    public function downloadAction(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 = "";
        $limit = (int) $this->container->getParameter('limit');
        $p = isset($_REQUEST['p']) ? (int) $_REQUEST['p'] : 1;
        if (!$p || $p < 1) {
            $p = 1;
        }

        $total = $em->getRepository('MarketZodacoBundle:HistoriesBought')->_getCountListByUser($check->getId());
        if ($total > 0) {
            $list = $em->getRepository('MarketZodacoBundle:HistoriesBought')->_getProListByUser($check->getId(), $p, $limit);
        }

        $pager2 = array();
        $pager2['PreviousPage'] = ($p > 1) ? ($p - 1) : $p;
        $pager2['NextPage'] = (ceil($total / $limit) > $p) ? ($p + 1) : $p;
        $pager2['LastPage'] = ceil($total / $limit);
        $pager2['Page'] = $p;

        $arr1 = array("list" => $list, "check" => $check, "page" => $pager2);

        return $this->render('MarketZodacoBundle:Default:download.html.php', $arr1);
    }

    public function getFileAction(Request $request, $id = 0, $title = null) {
        $session = $request->getSession();

        $em = $this->getDoctrine()->getManager();

        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $check = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$check) {
            echo "NONE";
            die;
        }

        $id = (int) $id;

        $product = $em->getRepository('MarketZodacoBundle:Products')->findOneById($id);
        if (!$product) {
            echo "NONE";
            die;
        }

        $userBuy = $em->getRepository('MarketZodacoBundle:HistoriesBought')->findOneBy(array("p_id" => $product->getId(), "status" => 1, "user_id" => $check->getId()));
        if (!$userBuy) {
            echo "NONE";
            die;
        }

        $video = $product->getMainFile();
        $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/items/";
        $fFile = $path . $video;
        $fileZ = filesize($fFile);

        $fileName = \Market\ZodacoBundle\System::_reString($product->getTitle()) . ".zip";

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Length: " . $fileZ . ";");
        header("Content-Disposition: attachment; filename=$fileName");
        header("Content-Type: application/octet-stream; ");
        header("Content-Transfer-Encoding: binary");

        echo readfile($fFile);
        die;
    }

    public function saleAction(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 = "";
        $limit = (int) $this->container->getParameter('limit');
        $p = isset($_REQUEST['p']) ? (int) $_REQUEST['p'] : 1;
        if (!$p || $p < 1) {
            $p = 1;
        }

        $total = $em->getRepository('MarketZodacoBundle:HistoriesSell')->_getCountListByUser($check->getId());
        if ($total > 0) {
            $list = $em->getRepository('MarketZodacoBundle:HistoriesSell')->_getProListByUser($check->getId(), $p, $limit);
        }

        $pager2 = array();
        $pager2['PreviousPage'] = ($p > 1) ? ($p - 1) : $p;
        $pager2['NextPage'] = (ceil($total / $limit) > $p) ? ($p + 1) : $p;
        $pager2['LastPage'] = ceil($total / $limit);
        $pager2['Page'] = $p;

        $arr1 = array("list" => $list, "check" => $check, "page" => $pager2);

        return $this->render('MarketZodacoBundle:Default:sale.html.php', $arr1);
    }

    public function searchAction(Request $request) {
        $em = $this->getDoctrine()->getManager();

        $s = isset($_REQUEST['s']) ? $_REQUEST['s'] : "";
        $p = isset($_REQUEST['p']) ? (int) $_REQUEST['p'] : 1;
        if (!$p || $p < 1) {
            $p = 1;
        }

        $limit = (int) $this->container->getParameter('limit');
        if ($s) {
            $total = $em->getRepository('MarketZodacoBundle:Products')->_getCountSearch($s);
            $list = $em->getRepository('MarketZodacoBundle:Products')->_getProSearch($s, $p, $limit);
        } else {
            $total = 0;
            $list = "";
        }

        $pager2 = array();
        $pager2['PreviousPage'] = ($p > 1) ? ($p - 1) : $p;
        $pager2['NextPage'] = (ceil($total / $limit) > $p) ? ($p + 1) : $p;
        $pager2['LastPage'] = ceil($total / $limit);
        $pager2['Page'] = $p;

        $arr1 = array('list' => $list, 'page' => $pager2, "s" => $s);

        return $this->render('MarketZodacoBundle:Default:search.html.php', $arr1);
    }

    public function commentAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();
        $id = (int) $id;

        $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();
        }

        $product = $em->getRepository('MarketZodacoBundle:Products')->findOneById($id);
        if (!$product || $product->getActive() != 1) {
            return $this->redirect($this->generateUrl("_homepage"));
        }

        if ($request->getMethod() == 'POST') {
            $licensetype = (int) $request->request->get("licensetype", 0);
            if (!$check) {
                return $this->redirect($this->generateUrl("login"));
            }

            if ($check->getId() == $product->getUsers()->getId() || $licensetype < 0) {
                return $this->redirect($this->generateUrl("_homepage"));
            }

            $cart = array();
            if ($licensetype == 0) {
                $cart["type"] = 0;
            } else {
                $cart["type"] = 1;
            }
            $cart["id"] = $product->getId();

            $session->set('cart', $cart);

            return $this->redirect($this->generateUrl("cart"));
        } else {
            $product->setViews($product->getViews() + 1);
            $em->persist($product);
            $em->flush();
        }

        $arr1 = array("product" => $product, "login" => $check);

        return $this->render('MarketZodacoBundle:Default:comment.html.php', $arr1);
    }

}
