<?php

namespace Apps\Shop\Helper;

use Core\Core\Request;
use Core\Utility\Date\Date;

use Apps\Shop\Helper\CartHelper;
use Apps\Shop\Entity\ShopCommand;
use Apps\Shop\Entity\ShopCommandLine;
use Apps\Shop\Entity\ShopBill;
use Apps\Shop\Widget\DetailCommandForm\DetailCommandForm;

class CommandHelper{

    /***
     * Brouillon
     */
    const DRAFT  = 1;
    
    /***
     * Valider en attente de Paiement
     */
    const VALID = 2;
    
    /**
     * Payé
     */
    const PAID = 3;
    
    /**
     * DELETE
     */
    const DELETE = 99;
    
    
    /***
     * Crée la commande a partir du panier en sessions
     */
    public static function CreateCommand($core , $data = "", $statut = self::VALID, $name =""){
       
        $cart = CartHelper::GetCart();
        
        $command = new ShopCommand($core);
        $commandExist = $command->Find("CartId = '" .$cart->id."'" );
        
        if(count($commandExist) > 0 ){
          $commandId = $commandExist[0]->IdEntite;  
        } else {
            
            $command->Name->Value = $cart->id;
            $command->CartId->Value = $cart->id ;
            $command->UserId->Value = $core->User->IdEntite;
            $command->Status->Value = $statut;
            $command->DateCreated->Value = Date::Now();
            $command->Total->Value = 1;

            $command->Adress->Value = json_encode(array("address"=> $data["Address"], 
                                                        "zipCode"=> $data["ZipCode"] , 
                                                        "city" => $data["City"]));
            
            $command->AdressFacturation->Value = json_encode(array("address"=> $data["AddressFacturation"], 
                                                        "zipCode"=> $data["ZipCodeFacturation"] , 
                                                        "city" => $data["CityFacturation"]));
           
            
            $command->Save();
            
            $commandId = $core->Db->GetInsertedId();
        }
        
        foreach($cart->lines as $line){
            
            $commandLine = new ShopCommandLine($core);
            
            $lineExist = $commandLine->Find("CommandId = " . $commandId . " AND EntityName='".$line->entityName."' AND EntityId ='".$line->entityId."'");
            
            if(count($lineExist) > 0){
                $commandLine = $lineExist[0];
            }
          
            $commandLine->CommandId->Value = $commandId;
            $commandLine->EntityName->Value = $line->entityName ?? "ShopProduct";
            $commandLine->EntityId->Value = $line->IdEntite;
            $commandLine->Quantity->Value = 1;
            $commandLine->Price->Value = $line->Price;

            
            $commandLine->Save();
        }
        
         Request::SetSession("Cart", null);
         
         return $core->GetCode("Shop.CommandCreated");
    }
    
    /***
     * Crée une commande d'un forfait
     */
    public static function CreateCommandeProduct($core, $productId)
    {       
          $product = new \Apps\Shop\Entity\Product($core);
          $product->GetById($productId);
        
          $command = new Command($core);
          $command->Name->Value = $product->Libelle->Value;
          $command->UserId->Value = $core->User->IdEntite;
          $command->Status->Value = self::PAID;
          $command->DateCreated->Value = Date::Now();
          $command->Save();
          
          $commandId = $core->Db->GetInsertedId();
          
          $commandLine = new CommandLine($core);
          $commandLine->CommandId->Value = $commandId;
          $commandLine->EntityName->Value = "Apps\\\Shop\\\Entity\\\Product";
          $commandLine->EntityId->Value = $productId;
          $commandLine->Quantity->Value = 1;
          $commandLine->Price->Value = $product->Price->Value;
         
          $commandLine->Save();
          
          $core->User->AddSolde($product->Code->Value);
    }
   
    /****
     * Créee une commande d'une Api
     */
    public static function CreateCommandApi($core , $data = "", $userId){

        echo $userId;

        $command = new ShopCommand($core);

        $command->Name->Value = 999;
        $command->CartId->Value = 999;
        $command->UserId->Value = $userId;
        $command->Status->Value = self::DRAFT;
        $command->DateCreated->Value = Date::Now();
        $command->Total->Value = 1;
        $command->Adress->Value = $data["address"];
        $command->AdressFacturation->Value = $command->Adress->Value;
        
        $command->Save();
        
        $commandId = $core->Db->GetInsertedId();
     

        foreach(json_decode($data["cart"]) as $line){
            
            $commandLine = new ShopCommandLine($core);
            
            $commandLine->CommandId->Value = $commandId;
            $commandLine->EntityName->Value = "ShopProduct";
            $commandLine->EntityId->Value = $line->productId;
            $commandLine->Quantity->Value = $line->quantity;
            $commandLine->Price->Value = $line->price;
            $commandLine->Data->Value = "";
            
            $commandLine->Save();
        }

        return true;
    }


    /***
     * On crée le commandes a partir de la session
     */
    public static function Exist($core, $cartId){
        
    }
    
    /***
     * On met a jour la commande à partir du panier 
     * Au cas ou l'utilisatur à fait plusieurs allers/retours
     */
    public static function UpdateCommand($core, $data){
   
        $detailCommandForm = new DetailCommandForm($core, $data, false);
        
        if($detailCommandForm->Validate($data)){
       
            $command = new ShopCommand($core);
            $command->GetById($data["Id"]);

            $detailCommandForm->Populate($command);
       
            $command->Save();

           return $detailCommandForm->Success(array("message"=> $core->GetCode("Shop.CommandUpdated")));

        } else {
            return $detailCommandForm->Error();
        }
    }
    
    /***
     * Passe la commande en status validé
     */
    public static function setCommandValidate($core){
        
        $cart = CartHelper::GetCart();
        $total = CartHelper::GetTotalCart();
        
        if($cart != null){
            
            $command = new Command($core);
            $currentCommand = $command->Find("CartId = '" .$cart->id."'" );

            $currentCommand[0]->Status->Value = self::PAID;
            $currentCommand[0]->Save();

            //On retire le solde de l'utilisateur
            $core->User->RemoveSolde($total);
            
             //On ajoute les soldes pour tous les autres utilisateurs
             foreach($cart->lines as $line){
                 
                $price =  $line->price;
                $itineraireId = $line->entityId;
                 
                $itineraire = new \Apps\CarnetDeVoyage\Entity\Itineraire($core);
                $itineraire->GetById($itineraireId);
                
                $user = new \Core\Entity\User\User($core);
                $user->GetById($itineraire->UserId->Value);
                
                $user->AddSolde($price);
             }
            
            CartHelper::ClearCart();
        }
    }

    /***
     * Update a command
     */
    public static function Update($core, $data){

    }

    /***
     * Get The User Command
     */
    public static function GetByUser($core, $order =" Id desc"){

        $command = new ShopCommand($core);
        $commands = $command->Find("UserId = '" .$core->User->IdEntite."' ORDER BY " .$order );

        return $commands;
    }

    /***
     * Get the Bill of a command 
     */
    public static function GetBills($core, $command){

        $bill = new ShopBill($core);
        return $bill->Find("CommandId=" . $command->IdEntite); 
    }
}

