<?php
    require("./models/project_model.php");
    require("./entities/project_entity.php");
    require("./models/category_model.php");
    require("./entities/category_entity.php");
    require("./models/image_model.php");
    require("./entities/image_entity.php");
    require("./models/user_model.php");
    require("./entities/user_entity.php");
    require("mother_controller.php");
    use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\Exception;
	use PHPMailer\PHPMailer\SMTP;

    /**
     * Le controler des Project
     * @author Yasser & Laura
     */
    class ProjectCtrl extends MotherCtrl{

        /**
         * Fonction d'affichage de la page d'acceuil
         */

        public function home(){


			 $intCategory = 0; 
			if (!empty($_GET['filter_cat'])) {
				$intCategory = (int) $_GET['filter_cat'];
			}

			$boolOld = false;
			if (!empty($_GET['filter_old']) && $_GET['filter_old'] == 'true') {
				$boolOld = true;
			}
            
            $objProjectModel 	= new ProjectModel;
            $arrProject		    = $objProjectModel->findAll(0,'',0,0,'','','',$intCategory,$boolOld);
            $arrProjectToDisplay = array();
            foreach($arrProject as $arrDetProject){
                $objProject = new Project;
                $objProject->hydrate($arrDetProject);
                $arrProjectToDisplay[] = $objProject;
            }

            $this->_arrData['arrProjectToDisplay']  = $arrProjectToDisplay;
			$this->_display("home");

        }

        /**
         * Fonction d'affichage de la barre de recherche
         */
        public function search(){

            //Récupérer les informations du formulaire
                $strKeywords 	= $_POST['keywords']??'';
                $intAuthor		= $_POST['author']??0;
                $intPeriod		= $_POST['period']??0;
                $strDate		= $_POST['date']??'';
                $strStartDate	= $_POST['startdate']??'';
                $strEndDate		= $_POST['enddate']??'';
                $intCategory	= $_POST['category']??0;

            // Récupération des projets
            $objProjectModel    = new ProjectModel;
            $arrProject         = $objProjectModel->findAll(intAuthor:$intAuthor, intPeriod:$intPeriod, strDate:$strDate, 
							    strKeywords:$strKeywords, strStartDate:$strStartDate, strEndDate:$strEndDate, intCategory:$intCategory);
            $arrProjectToDisplay    = array(); 

            foreach($arrProject as $arrDetProject){
                $objProject = new Project;
                $objProject->hydrate($arrDetProject);
                $arrProjectToDisplay[]  = $objProject;
            }
        
            // Récupération des utilisateurs
            $objUserModel   = new UserModel;
            $arrUser        = $objUserModel->findAllUsers();

            // Récupération des catégories
            $objCategoryModel   = new CategoryModel;
            $arrCategory        = $objCategoryModel->findAllCategory();

            $this->_arrData['arrProjectToDisplay']  = $arrProjectToDisplay;
            $this->_arrData['arrCategory']  = $arrCategory;
            $this->_arrData['arrProject']  = $arrProject;
            $this->_arrData['arrUser']  = $arrUser;


        
        
            $this->_display("search");
        }

        /**
         * Fonction d'affichage de la page projet
         */
        public function project (){

            $objProjectModel 	= new ProjectModel;
            $arrProject		    = $objProjectModel->findAll(4);
            $arrProjectToDisplay = array();
            foreach($arrProject as $arrDetProject){
                $objProject = new Project;
                $objProject->hydrate($arrDetProject);
                $arrProjectToDisplay[] = $objProject;
            }

            $objImageModel 	    = new ImageModel;
            $arrImage		    = $objImageModel->findAllImage(4);
            $arrImageToDisplay = array();
            foreach($arrImage as $arrDetImage){
                $objImage = new Image;
                $objImage->hydrate($arrDetImage);
                $arrImageToDisplay[] = $objImage;
            }
                    //Variable data
	        $_SESSION['title'] = $_POST['titleProject']??"";
	        $_SESSION['description'] = $_POST['descProject']??"";
	        $_SESSION['content'] = $_POST['textProject']??"";
	        $_SESSION['thumbnail'] = $_FILES['imageThumbnail']['name']??"";
	        $_SESSION['status'] = 'en_attente';
			$_SESSION['user_id'] = $_SESSION['user']['user_id'];


	        $objProject = new Project();

	        /**
	        * Créer par Besnik le GOAT et l'autre GOAT de Guillaume
	        * 
	        * @return bool pour savoir si le fichier existe,
	        * puis déplace vers le fichier uploads avec les images projet des utilisateurs
	        * Communication avec la BDD 
	        */
	        if (($_SESSION['thumbnail'] != null)){
	        	$strDest = "";
	        	if ((count($_FILES) > 0) && ($_FILES['imageProject']['error'] != 4)){
	        		$strDest = 'uploads/projects/'.$_FILES['imageProject']['name'];
	        		move_uploaded_file($_FILES['imageProject']['tmp_name'], $strDest);
	        	}
	        }

	        /** En cas d'appuis sur le bouton d'envoie ou celui de remettre a plus tard
	         * 1. Changement de status
	         * 2. Hydratation avec les informations récupéré de l'utilisateur
	         * 3. Envoie des données à la BDD
	         */
	        if (isset($_POST['sendMessage'])) {
	        	$_SESSION['status'] = 'publié';
	        	$objProject->hydrate($_SESSION);
	        	$objProject->setThumbnail($strDest);
				var_dump($strDest);
				var_dump($objProject);
	        	$objProjectModel->insert($objProject);

	        } else if (isset($_POST['toContinue'])) {
	        	$objProject->hydrate($_SESSION);
	        		$objProject->setThumbnail($strDest);
	        	$objProjectModel->insert($objProject);
	        }

	        var_dump($_SESSION);
	        var_dump($objProject);
            $this->_arrData['arrProjectToDiplay']  = $arrProjectToDisplay;
            $this->_arrData['arrImageToDiplay']  = $arrImageToDisplay;
           
            $this->_display("project");
        }


        public function display() {
			$intId = $_GET['id'] ?? null;

			if ($intId) {
				$objProjectModel = new ProjectModel();
				$arrProject = $objProjectModel->findOne((int)$intId);

				if ($arrProject) {
					$objProject = new Project();
					$objProject->hydrate($arrProject);
                    
                    $this->_arrData["objProject"] = $objProject;
					$this->_display("project_display");
				} else {
					header("Location: index.php?ctrl=project&action=home");
					exit;
				}
			} else {
				header("Location: index.php?ctrl=project&action=home");
				exit;
			}
		}
		
		public function sendEmail(){
			if (count($_POST) > 0) {

				$projectId = (int)($_POST['project_id'] ?? 0);
				$toEmail   = trim($_POST['to_email'] ?? '');

				if ($projectId <= 0 || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
					header("Location: index.php?ctrl=project&action=display&id=".$projectId."&mail=fail");
					exit;
				}

				$objProjectModel = new ProjectModel();
				$arrProject = $objProjectModel->findOne($projectId);

				if (!$arrProject) {
					header("Location: index.php?ctrl=project&action=home");
					exit;
				}

				$objProject = new Project();
				$objProject->hydrate($arrProject);



				$objMail = new PHPMailer(); // Nouvel objet Mail
				$objMail->IsSMTP();
				$objMail->Mailer      = "smtp";
				$objMail->CharSet     = PHPMailer::CHARSET_UTF8;

				$objMail->SMTPDebug   = 0;


				$objMail->SMTPAuth    = TRUE;
				$objMail->SMTPSecure  = "tls";
				$objMail->Port        = 587;
				$objMail->Host        = "smtp.gmail.com";
				$objMail->Username    = "projet.folliow@gmail.com";
				$objMail->Password    = "dqnw mqbu cwvg enbp";

				$objMail->IsHTML(true);

				
				$objMail->setFrom('projet.folliow@gmail.com', 'Projet Folliow');


				// Destinataire
				$objMail->addAddress($toEmail);

				// Mail
				$objMail->Subject = "Projet : " . $objProject->getTitle();

				$url = "http://localhost/projet_php/public/index.php?ctrl=project&action=display&id=" . $projectId;

				$objMail->Body =
					"<h3>" . $objProject->getTitle() . "</h3>" .
					"<p>" . $objProject->getDescription() . "</p>" .
					"<p><a href='" . $url . "'>Voir le projet</a></p>";

				// Envoi + redirection
				if ($objMail->Send()) {
					header("Location: index.php?ctrl=project&action=display&id=".$projectId."&mail=ok");
				} else {
					// Pour debug si besoin: echo $objMail->ErrorInfo; exit;
					header("Location: index.php?ctrl=project&action=display&id=".$projectId."&mail=fail");
				}
				exit;
			}

			header("Location: index.php?ctrl=project&action=home");
			exit;
		}
		
		public function accept(){

			//Récupéré l'id dans l'url
			$intId = $_GET['id'];

			//Je créer un nouveau model pour exec la commande SQL
			$objProjectModel = new ProjectModel;
			$objProjectModel->accept($intId);

			//Redirection vers la page 
			header("Location: index.php");
			exit;
		}

		public function refuse(){

			//Récupéré l'id dans l'url
			$intId = $_GET['id'];

			//Je créer un nouveau model pour exec la commande SQL
			$objProjectModel = new ProjectModel;
			$objProjectModel->refuse($intId);

			//Redirection vers la page 
			header("Location: index.php");
			exit;
		}

		public function delete(){

			//Récupéré l'id dans l'url
			$intId = $_GET['id'];

			//Je créer un nouveau model pour exec la commande SQL
			$objProjectModel = new ProjectModel;
			$objProjectModel->delete($intId);

			//Redirection vers la page 
			header("Location: index.php");
			exit;
		}
    }