<?php

namespace Market\ZodacoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Market\ZodacoBundle\Entity\Notifications;
use Market\ZodacoBundle\Entity\Affiliate;

class UsersController extends BaseController {

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

        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");
        $checkw = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if ($checkw) {
            return $this->redirect($this->generateUrl("_user"));
        }
        //////////////////

        $error = null;
        $check = '';
        $checkName = '';

        if ($request->getMethod() == 'POST') {
            $first_name = $request->request->get("first_name", "");
            $last_name = $request->request->get("last_name", "");
            $password = $request->request->get("password", "");
            $email = $request->request->get("email", "");
            $user_name = $request->request->get("user_name", "");
            $bannedWords = $this->container->getParameter('bannedWords');
            $minCharacter = (int) $this->container->getParameter('minCharacter');

            if (!empty($first_name) && !empty($last_name) && !empty($user_name) && !empty($password) && filter_var($email, FILTER_VALIDATE_EMAIL) && !in_array($user_name, $bannedWords) && strlen($user_name) >= $minCharacter) {
                $check = $em->getRepository('MarketZodacoBundle:Users')->findOneByEmail($email);
                $checkName = $em->getRepository('MarketZodacoBundle:Users')->findOneByUsername($user_name);
                if (!$check && !$checkName) {
                    $a = new \Datetime();
                    $new_user = new \Market\ZodacoBundle\Entity\Users();
                    $new_user->setActive(1);
                    $new_user->setAdd1("");
                    $new_user->setAdd2("");
                    $new_user->setAvatar("");
                    $new_user->setCity("");
                    $new_user->setCountry("");
                    $new_user->setCover("");
                    $new_user->setDescription("");
                    $new_user->setEmailPayment("");
                    $new_user->setHead("");
                    $new_user->setMoney(0);
                    $new_user->setTotalSale(0);
                    $new_user->setSocial("");
                    $new_user->setSupper(0);
                    $new_user->setTotalFile(0);
                    $new_user->setFname($first_name);
                    $new_user->setUsername($user_name);
                    $new_user->setPassword(md5(sha1($password)));
                    $new_user->setEmail($email);
                    $new_user->setLname($last_name);
                    $new_user->setCreatedAt($a);
                    $new_user->setUpdatedAt($a);

                    $newL = $em->getRepository('MarketZodacoBundle:NewsLetters')->findOneByEmail($email);
                    if ($newL) {
                        $newL->setActive(1);
                    } else {
                        $newL = new \Market\ZodacoBundle\Entity\NewsLetters();
                        $newL->setEmail($email);
                        $newL->setActive(1);
                    }
                    $em->persist($newL);

                    $em->persist($new_user);


                    $content = $this->get('translator')->trans('Hi') . ' ' . $user_name . ',<br>' .
                            $this->get('translator')->trans('Thank you for joining Zodaco Marketplace, we hope you will contribute and get rewarded handsomely!') . '<br>' .
//                            $this->get('translator')->trans('You will have to specify a verified Paypal Account Name and Email in order to sell on Zodaco Marketplace.') . '<br><br>' .
                            $this->get('translator')->trans('If you have any question, please do not hesitate to contact us.') . '<br><br>' .
                            $this->get('translator')->trans('Zodaco Marketplace') . '<br>' .
                            'http://www.' . $request->getHost();


                    $sub = $this->get('translator')->trans('Welcome to Zodaco Marketplace');

                    $noti = new Notifications();
                    $noti->setEmail($email);
                    $noti->setReplyEmail('');
                    $noti->setTitle($sub);
                    $noti->setContent($content);
                    $em->persist($noti);
                    
                    //Add Ref
                    if($ref = $session->get('ref', "")){
                        $newRef = $em->getRepository('MarketZodacoBundle:Users')->findOneByUsername($ref);
                        if ($newRef && $new_user) {
                            $refAdd = new Affiliate();
                            $refAdd->setUserId($new_user->getId());
                            $refAdd->setRefId($newRef->getId());
                            $refAdd->setStatus(0);
                            $em->persist($refAdd);
                        }
                    }

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

                    $em->flush();
                    $session->set('username', $email);
                    $session->set('password', md5(sha1($password)));

                    return $this->redirect($this->generateUrl("_user"));
                }
            } else {
                $error = 1;
            }
        }

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

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

    public function loginAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");
        $checkw = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if ($checkw) {
            return $this->redirect($this->generateUrl("_user"));
        }
        //////////////////
        $error = null;
        if ($request->getMethod() == 'POST') {
            $password = $request->request->get("password", "");
            $user_name = $request->request->get("user_name", "");
            if (!empty($user_name) && !empty($password)) {
                $check = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("username" => $user_name, "password" => md5(sha1($password))));
                if ($check) {
                    $session->set('username', $check->getEmail());
                    $session->set('password', md5(sha1($password)));
                    return $this->redirect($this->generateUrl("_user"));
                } else {
                    $error = 1;
                }
            } else {
                $error = 1;
            }
        }
        $arr1 = array("error" => $error);
        return $this->render('MarketZodacoBundle:Users:login.html.php', $arr1);
    }

    public function logoutAction(Request $request) {
        $session = $request->getSession();
        $session->clear();
        return $this->redirect($this->generateUrl("_homepage"));
    }

    public function userMenuAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");
        $login = 0;
        $checkw = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if ($checkw) {
            $login = $checkw;
        }

        $arr1 = array("login" => $login);
        return $this->render('MarketZodacoBundle:Users:userMenu.html.php', $arr1);
    }

    public function leftMenuUserAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");
        $dashboard = $session->get('dashboard', "");
        $login = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));

        $arr1 = array("login" => $login, "dashboard" => $dashboard);
        return $this->render('MarketZodacoBundle:Users:leftMenuUser.html.php', $arr1);
    }

    public function profileAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $session->set("dashboard", "profile");

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

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

        if ($request->getMethod() == 'POST') {
            $first_name = $request->request->get("first_name", "");
            $last_name = $request->request->get("last_name", "");
            $add1 = $request->request->get("add1", "");
            $add2 = $request->request->get("add2", "");
            $city = $request->request->get("city", "");
            $country = $request->request->get("country", "");


            $login->setAdd1($add1);
            $login->setAdd2($add2);
            $login->setCity($city);
            $login->setCountry($country);
            if ($first_name) {
                $login->setFname($first_name);
            }
            if ($last_name) {
                $login->setLname($last_name);
            }
            $em->persist($login);
            $em->flush();
        }

        $arr1 = array("login" => $login);
        return $this->render('MarketZodacoBundle:Users:profile.html.php', $arr1);
    }

    public function emailAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $session->set("dashboard", "email");

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

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

        if ($request->getMethod() == 'POST') {
            $email = $request->request->get("email", "");


            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $login->setEmail($email);
            }
            $em->persist($login);
            $em->flush();
        }

        $arr1 = array("login" => $login);
        return $this->render('MarketZodacoBundle:Users:email.html.php', $arr1);
    }

    public function passwordAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $session->set("dashboard", "password");

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

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

        if ($request->getMethod() == 'POST') {
            $password = $request->request->get("password", "");
            $password2 = $request->request->get("password2", "");


            if ($password2 && md5(sha1($password)) == $login->getPassword()) {
                $login->setPassword(md5(sha1($password2)));
            }
            $em->persist($login);
            $em->flush();
        }

        $arr1 = array("login" => $login);
        return $this->render('MarketZodacoBundle:Users:password.html.php', $arr1);
    }

    public function informationAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $session->set("dashboard", "information");

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

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

        if ($request->getMethod() == 'POST') {
            $headline = $request->request->get("headline", "");
            $description = $request->request->get("description", "");

            $login->setHead($headline);
            $login->setDescription($description);

            $em->persist($login);
            $em->flush();
        }

        $arr1 = array("login" => $login);
        return $this->render('MarketZodacoBundle:Users:information.html.php', $arr1);
    }

    public function portfolioAction(Request $request, $title = null) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();

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

        $login = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password, 'active' => 1));
        
        $p = isset($_REQUEST['p']) ? $_REQUEST['p'] : 1;
        if (!$p || $p < 1) {
            $p = 1;
        }
        $limit = (int) $this->container->getParameter('limit');
        $user = $em->getRepository('MarketZodacoBundle:Users')->findOneByUsername($title);
        if (!$user) {
            return $this->redirect($this->generateUrl("_homepage"));
        }

        $total = $em->getRepository('MarketZodacoBundle:Products')->_getCountListByUser($user->getId());
        $list = $em->getRepository('MarketZodacoBundle:Products')->_getProListByUser($user->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;

        $error = 0;
        if ($request->getMethod() == 'POST') {
            $title = '['.$this->get('translator')->trans('Zodaco Marketplace').'] '.$this->get('translator')->trans('Email Contact');
            $details = $request->request->get("details", "");
            $email = $request->request->get("emm", "");
            if (filter_var($email, FILTER_VALIDATE_EMAIL) && $details) {
                try {
                    $noti = new Notifications();
                    $noti->setEmail($user->getEmail());
                    $noti->setReplyEmail($email);
                    $noti->setTitle($title);
                    $noti->setContent($details);
                    $em->persist($noti);
                    $em->flush();
                    $error = 2;
                } catch (\Exception $e) {
                    $error = 1;
                }
            } else {
                $error = 1;
            }
        }

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

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

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

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

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

        $p = isset($_REQUEST['p']) ? $_REQUEST['p'] : 1;
        if (!$p || $p < 1) {
            $p = 1;
        }
        $limit = (int) $this->container->getParameter('limit');

        $total = $em->getRepository('MarketZodacoBundle:Products')->_getCountMyProducts($login->getId());
        $list = $em->getRepository('MarketZodacoBundle:Products')->_getProMyProducts($login->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;

        $session->remove("done");

        $arr1 = array('list' => $list, 'page' => $pager2, "login" => $login, "done" => $done);
        return $this->render('MarketZodacoBundle:Users:my_products.html.php', $arr1);
    }

    public function edit_productsAction(Request $request, $id = 0) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();

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

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

        $product = $em->getRepository('MarketZodacoBundle:Products')->findOneBy(array("id" => (int) $id, "u_id" => $login->getId()));
        if (!$product) {
            throw new NotFoundHttpException("Not found");
        }
        if ($product->getActive() == 1 && $product->getStatus() != 1) {
            if ($request->getMethod() == 'POST') {
                $type = $request->request->get("type", 0);
                try {
                    $em->getConnection()->beginTransaction();
                    if ($type == 0) {
                        $short_title = $request->request->get("short_title", "");
                        $details = $request->request->get("details", "");
                        $demoUrl = $request->request->get("demo_url", "");
                        $videoUrl = $request->request->get("video_url", "");
                        if ($short_title) {
                            $product->setShortDetails($short_title);
                        }
                        if ($details) {
                            $product->setDetails($details);
                        }
                        $product->setDemoUrl($demoUrl);
                        $product->setVideoUrl($videoUrl);
                    } else {
                        $title = $request->request->get("title", "");
                        $upanh = $request->request->get("upanh", "");
                        $licon = $request->request->get("licon", "");
                        $screenshot = $request->request->get("screenshot", "");
                        $main_file = $request->request->get("main_file", "");

                        $b = 0;
                        $a = new \DateTime();
                        if ($title && $title != $product->getTitle()) {
                            $product->setUpdateTitle($title);
                            $b = 1;
                        }
                        if ($upanh) {
                            $product->setUpdateIcon($upanh);
                            $b = 1;
                        }
                        if ($licon) {
                            $product->setUpdatePreview($licon);
                            $b = 1;
                        }
                        if ($main_file) {
                            $product->setUpdateMainFile($main_file);
                            $b = 1;
                        }
                        if ($screenshot) {
                            $product->setUpdateScreenshots($screenshot);
                            $b = 1;
                        }
                        if ($b == 1) {
                            $product->setVersionAt($a);
                            $product->setStatus(1);
                            $session->set('done', 1);
                        } else {
                            $error = 1;
                        }
                    }

                    $content = $this->get('translator')->trans('Dear') . ' ' . $product->getUsers()->getUsername() . ',<br><br>' .
                            $this->get('translator')->trans('We have received your update for') . ' "' . $product->getTitle() . '". ' . $this->get('translator')->trans('Your updated product is now under review process and you will be notified as soon as our review team has reviewed your product.') . '<br><br>' .
                            $this->get('translator')->trans('When, and if approved, your old product will be automatically replaced with the new release.') . '<br><br>' .
//                            $this->get('translator')->trans('Enjoy author with Zodaco Marketplace!') . '<br><br>' .
                            $this->get('translator')->trans('Regards,') . '<br>' .
                            $this->get('translator')->trans('Zodaco Marketplace') . '<br>' .
                            'http://www.' . $request->getHost();


                    $sub = $this->get('translator')->trans('Your product has been updated');

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



                    $em->persist($product);
                    $em->flush();
                    $em->getConnection()->commit();
                    return $this->redirect($this->generateUrl("my_products"));
                } catch (Exception $ex) {
                    $em->getConnection()->rollback();
                    $session->remove('done');
                    $error = 1;
                }
            }
        } else {
            return $this->redirect($this->generateUrl("_homepage"));
        }

        $arr1 = array('product' => $product, "error" => $error);
        return $this->render('MarketZodacoBundle:Upload:edit.html.php', $arr1);
    }

}
