<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

class ProductionController extends Controller
{
	//MODIFICATION
	function voirmodif($id) {
		if(session('user')== null) {
            return redirect('/');
        }
        $matiere = DB::table('matiere')->orderby('designation','asc')->get();
        $produit = DB::table('produit_vendable')->orderby('designation','asc')->get();
        $production1 = DB::table('production')->where('id', $id)->first();
        $production = DB::table('production')->where('etat','!=','Annulé')->orderBydesc('id')->get();
        $ligne_production = DB::table('ligne_production')->where('production_id', $id)->get();

        return view('production/modifier',[

            'produit' => $produit,
            'matiere' => $matiere,
            'ligne' => $ligne_production,
            'production1' => $production1,
            'production' => $production,
        ]);
    }
	function validermodif($id)
    {

		$produit= request('produit_obtenu');
        $qte= request('qte_obtenu');
		$datep=implode('-', array_reverse(explode('/', request('date'))));
		//$datep= date('Y-m-d');
        
        $approvision=collect(request('approvision'))->chunk(2);

            DB::table('production')->where('id',$id)->update(
                [
                    'qte' => $qte,
                    'produit_id' => $produit,
                    'date' => $datep,
                    'etat' => "Non validé",
                   
                ]
            );
			
        DB::table('ligne_production')->where('production_id', $id)->delete();
		
		$i=0;

        foreach ($approvision as $key=> $approvisions){
			
		$qcount =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->get()->count();
			if ($qcount > 0){
			$qtesto2 =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$qtesto2 = 0;
			}
            $desi =  DB::table('matiere')->where('id', $approvisions[0 +$i])->first()->designation;

            if($qtesto2 < $approvisions[1 +$i]){

                DB::table('production')->where('id', $id)->delete();

                DB::table('ligne_production')->where('production_id', $id)->delete();

                $message = [
                    "title" => 'Erreur d\'enregistrement',
                    "type" => 'error',
                    "response" => 'La quantité de'.' '.$desi.' est insuffisante: stock actuel '.$qtesto2,
                ];
                return $message;
            }else{
                DB::table('ligne_production')->insert(
                    [
                        'production_id' => $id,
                        'etat' => "Non validé",
						'date' => $datep,
                        'matiere_id' => $approvisions[0 +$i],
                        'qte' => $approvisions[1 +$i],
                    ]
                );
                $i += count($approvisions->toArray());

            }

        }

            $message = [
                "title" => 'Succès',
                "type" => 'success',
                "response" => 'Modification effectuée avec succès !',
            ];

            return $message;
    }

	function voirligne ($id) {

        $ligneproduction= DB::table('ligne_production')->where('id',$id)->first();
        return [
            'ligneproduction' => $ligneproduction,
        ];
    }
	function suppligne () {

        $id=request('id');
		$prodid = DB::table('ligne_production')->where('id', $id)->first()->production_id;
		DB::table('ligne_production')->where('id', $id)->delete();
		$verif = DB::table('ligne_production')->where('production_id', $prodid)->get()->count();
		if ($verif > 0){
			return redirect()->route('detail-production',['id'=>$prodid])->with('status', 'Suppression effectuée avec succes');
		} else {
			DB::table('production')->where('id', $prodid)->delete();
			return redirect()->route('detail-production',['id'=>$prodid])->with('status', 'Suppression effectuée avec succes');
		}
    }
	function voirproduction ($id) {

        $production= DB::table('production')->where('id',$id)->first();
        return [
            'production' => $production,
        ];
    }
	function voirprod ($id) {

        $production= DB::table('production')->where('id',$id)->first();
        return [
            'prod' => $production,
        ];
    }
	function annuler () {

        $id=request('id');
		$today = date('Y-m-d');
		$prod = DB::table('production')->where('id', $id)->first();
            DB::table('production')->where('id', $id)->update(
                [
                    'etat' => "Annulé",
                ]
            );

            DB::table('ligne_production')->where('production_id', $id)->update(
                [
                    'etat' => "Annulé",
                ]
            );
			
			$nbreencarton = DB::table('produit_vendable')->where('id', $prod->produit_id)->first()->nbreencarton;
			$quantiteemb = $nbreencarton * $prod->qte;
			$emballagec = DB::table('emballage_produit')->where('produit_id',  $prod->produit_id)->get()->count();
			if ($emballagec > 0){
			$emballage = DB::table('emballage_produit')->where('produit_id',  $prod->produit_id)->get();
			foreach($emballage as $emballages){
				$desi =  DB::table('emballage')->where('id', $emballages->emballage_id)->first()->designation;
				//$qtesto = DB::table('emballage')->where('id', $emballages->emballage_id)->first()->stock;
				$stockr = DB::table('stock_emballage')->where('emballage_id', $emballages->emballage_id)->orderBydesc('id')->take(1)->first()->apres;
					DB::table('stock_emballage')->insert(
                    [
                        'date' => $prod->date,
                        'emballage_id' => $emballages->emballage_id,
                        'qte' => $quantiteemb,
                        'type_operation' => 'AnnulationProduction',
						'en_stock' => $stockr,
						'apres' => ($stockr + $quantiteemb),
                    ]
                );
					DB::table('emballage')->where('id', $emballages->id)->update(
						[
							'stock_general' => ($stockr + $quantiteemb),
						]
					);
				
			}
			}
			
			//$ligne = DB::table('production')->where('id', $id)->first();
            $stockproc = DB::table('stock_magasin')->where('produit_id', $prod->produit_id)->get()->count();
            if ($stockproc >0){
				$stockpro = DB::table('stock_magasin')->where('produit_id', $prod->produit_id)->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$stockpro = 0;
			}
            $qtevalp = $prod->qte;
            $date = $prod->date;
			
				DB::table('stock_magasin')->insert(
                    [
                        'magasin_id' => session('user')->magasin_id,
                        'date' => $date,
                        'produit_id' => $prod->produit_id,
                        'qte' => $qtevalp,
                        'type_operation' => 'AnnulationProduction',
						'en_stock' => $stockpro,
						'apres' => ($stockpro - $qtevalp),
                    ]
                );

            DB::table('produit_vendable')->where('id', $prod->produit_id)->update(
                [
                    'stock_general' => ($stockpro - $qtevalp),
                ]
            );
			
		
			$lignep = DB::table('ligne_production')->where('production_id', $id)->get();
			foreach($lignep as $ligneps){
            //$qtesto = DB::table('matiere')->where('id', $ligneps->matiere_id)->first()->stock_general;
            $qteval = $ligneps->qte;
			$verif = DB::table('stock_matiere')->where('matiere_id', $ligneps->matiere_id)->get()->count();
			if ($verif>0){
				$sm = DB::table('stock_matiere')->where('matiere_id', $ligneps->matiere_id)->orderBydesc('id')->take(1)->first()->apres;
				DB::table('stock_matiere')->insert(
                    [
                        'date' => $prod->date,
                        'matiere_id' => $ligneps->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'AnnulationProduction',
						'en_stock' => $sm,
						'apres' => ($sm + $qteval),
                    ]
                );
			} else {
				$sm = 0;
				DB::table('stock_matiere')->insert(
                    [
                       'date' => $prod->date,
                        'matiere_id' => $ligneps->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'AnnulationProduction',
						'en_stock' => $sm,
						'apres' => ($sm + $qteval),
                    ]
                );
			}
			
            DB::table('matiere')->where('id', $ligneps->matiere_id)->update(
                [
                    'stock_general' => ($sm + $qteval),
                ]
            );
			}

        return redirect()->route('production')->with('status', 'Production annulée avec succès');
	}

	
	function supprod () {

        $id=request('id');
		$production= DB::table('production')->where('id', $id)->first()->id;
		DB::table('production')->where('id', $id)->delete();
		DB::table('ligne_production')->where('production_id', $id)->delete();
		
	return redirect()->route('production')->with('status', 'Suppression effectuée avec succes');
    }
 
	public function consulter($id)
	{
		
		if(session('user')== null) {
            return redirect('/');
        }
		$detail=DB::table('ligne_production')->where('production_id',$id)->get();
		return view('production/detail', [
			'detail'=> $detail,
		]);
	}
	public function consulter2($id)
	{
		
		if(session('user')== null) {
            return redirect('/');
        }
		$detail=DB::table('ligne_transformation')->where('transformation_id',$id)->get();
		return view('production/detail-trans', [
			'detail'=> $detail,
		]);
	}

    function voirvalider ($id) {

        $production= DB::table('production')->where('id',$id)->first();
        return [
            'production' => $production,
        ];
    }
	function voirvalider2 ($id) {

        $transformation= DB::table('transformation')->where('id',$id)->first();
        return [
            'transformation' => $transformation,
        ];
    }
    
    function valider () {

        $id=request('id');
		$today = date('Y-m-d');
		$prod = DB::table('production')->where('id', $id)->first();
            DB::table('production')->where('id', $id)->update(
                [
                    'etat' => "Validé",
                ]
            );

            DB::table('ligne_production')->where('production_id', $id)->update(
                [
                    'etat' => "Validé",
                ]
            );
			
			$nbreencarton = DB::table('produit_vendable')->where('id', $prod->produit_id)->first()->nbreencarton;
			$quantiteemb = $nbreencarton * $prod->qte;
			$emballagec = DB::table('emballage_produit')->where('produit_id',  $prod->produit_id)->get()->count();
			if ($emballagec > 0){
			$emballage = DB::table('emballage_produit')->where('produit_id',  $prod->produit_id)->get();
			foreach($emballage as $emballages){
				$desi =  DB::table('emballage')->where('id', $emballages->emballage_id)->first()->designation;
				//$qtesto = DB::table('emballage')->where('id', $emballages->emballage_id)->first()->stock;
				$stockr = DB::table('stock_emballage')->where('emballage_id', $emballages->emballage_id)->orderBydesc('id')->take(1)->first()->apres;
					DB::table('stock_emballage')->insert(
                    [
                        'date' => $prod->date,
                        'emballage_id' => $emballages->emballage_id,
                        'qte' => $quantiteemb,
                        'type_operation' => 'Production',
						'en_stock' => $stockr,
						'apres' => ($stockr - $quantiteemb),
                    ]
                );
					DB::table('emballage')->where('id', $emballages->id)->update(
						[
							'stock_general' => ($stockr - $quantiteemb),
						]
					);
				
			}
			}
			
			//$ligne = DB::table('production')->where('id', $id)->first();
            $stockproc = DB::table('stock_magasin')->where('produit_id', $prod->produit_id)->get()->count();
            if ($stockproc >0){
				$stockpro = DB::table('stock_magasin')->where('produit_id', $prod->produit_id)->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$stockpro = 0;
			}
            $qtevalp = $prod->qte;
            $date = $prod->date;
			
				DB::table('stock_magasin')->insert(
                    [
                        'magasin_id' => session('user')->magasin_id,
                        'date' => $date,
                        'produit_id' => $prod->produit_id,
                        'qte' => $qtevalp,
                        'type_operation' => 'Production',
						'en_stock' => $stockpro,
						'apres' => ($stockpro + $qtevalp),
                    ]
                );

            DB::table('produit_vendable')->where('id', $prod->produit_id)->update(
                [
                    'stock_general' => ($stockpro + $qtevalp),
                ]
            );
			
		
			$lignep = DB::table('ligne_production')->where('production_id', $id)->get();
			foreach($lignep as $ligneps){
            //$qtesto = DB::table('matiere')->where('id', $ligneps->matiere_id)->first()->stock_general;
            $qteval = $ligneps->qte;
			$verif = DB::table('stock_matiere')->where('matiere_id', $ligneps->matiere_id)->get()->count();
			if ($verif>0){
				$sm = DB::table('stock_matiere')->where('matiere_id', $ligneps->matiere_id)->orderBydesc('id')->take(1)->first()->apres;
				DB::table('stock_matiere')->insert(
                    [
                        'date' => $prod->date,
                        'matiere_id' => $ligneps->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'Production',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
                    ]
                );
			} else {
				$sm = 0;
				DB::table('stock_matiere')->insert(
                    [
                       'date' => $prod->date,
                        'matiere_id' => $ligneps->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'Production',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
                    ]
                );
			}
			
            DB::table('matiere')->where('id', $ligneps->matiere_id)->update(
                [
                    'stock_general' => ($sm - $qteval),
                ]
            );
			}

        return redirect()->route('production')->with('status', 'Validation effectuée avec succès');
	}
	function valider2 () {

        $id=request('id');
		//$today=date('Y-m-d');
            DB::table('transformation')->where('id', $id)->update(
                [
                    'etat' => "Validé",
                ]
            );

            DB::table('ligne_transformation')->where('transformation_id', $id)->update(
                [
                    'etat' => "Validé",
                ]
            );

			$ligne = DB::table('transformation')->where('id', $id)->first();
            $stockrestocount = DB::table('stock_resto')->where('produit_id', $ligne->produit_id)->get()->count();
            if ($stockrestocount >0){
				$stockresto = DB::table('stock_resto')->where('produit_id', $ligne->produit_id)->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$stockresto = 0;
			}
            $qteval = $ligne->qte;
            $date = $ligne->date;
			
			//$sm = DB::table('stock_magasin')->where('produit_id', $lignes->produit_id)->where('magasin_id', $magasin)->orderBydesc('id')->take(1)->first()->apres;
				DB::table('stock_resto')->insert(
                    [
                        'date' => $date,
                        'produit_id' => $ligne->produit_id,
                        'qte' => $qteval,
                        'type_operation' => 'Transformation',
						'en_stock' => $stockresto,
						'apres' => ($stockresto + $qteval),
                    ]
                );

            DB::table('produit_vendable')->where('id', $ligne->produit_id)->update(
                [
                    'stock_gene' => ($stockresto + $qteval),
                ]
            );
			$lignep = DB::table('ligne_transformation')->where('transformation_id', $id)->get();
			foreach($lignep as $ligneps){
			
            $qtesto = DB::table('produit_vendable')->where('id', $ligneps->produit_id)->first()->stock_gene;

            $qteval = $ligneps->qte;
			
			$verif = DB::table('stock_resto')->where('produit_id', $ligneps->produit_id)->get()->count();
			if ($verif>0){
				$sm = DB::table('stock_resto')->where('produit_id', $ligneps->produit_id)->orderBydesc('id')->take(1)->first()->apres;
				DB::table('stock_resto')->insert(
                    [
                        'date' => $date,
                        'produit_id' => $ligneps->produit_id,
                        'qte' => $qteval,
                        'type_operation' => 'Sortie',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
                    ]
                );
			} else {
				$sm = 0;
				DB::table('stock_resto')->insert(
                    [
                        'date' => $date,
                        'produit_id' => $ligneps->produit_id,
                        'qte' => $qteval,
                        'type_operation' => 'Sortie',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
                    ]
                );
			}
			
            DB::table('produit_vendable')->where('id', $ligneps->produit_id)->update(
                [
                    'stock_gene' => ($sm - $qteval),
                ]
            );
			}

        return redirect()->route('transformation')->with('status', 'Validation effectuée avec succes');
	}

    function nouveau() {
		if(session('user')== null) {
            return redirect('/');
        }
        $produit = DB::table('produit_vendable')->orderBy('designation','asc')->get();
		$categorie=DB::table('categorie')->get();
        $matiere = DB::table('matiere')->orderBy('designation','asc')->get();
        $production = DB::table('production')->where('etat','!=','Annulé')->orderBydesc('id')->get();

        return view('production/nouveau',[

            'produit' => $produit,
            'matiere' => $matiere,
            'production' => $production,
            'categorie' => $categorie,
        ]);
    }
	function nouveau2() {
		if(session('user')== null) {
            return redirect('/');
        }
        $produit_vendable = DB::table('produit_vendable')->orderBy('designation','asc')->get();
        //$produit = DB::table('produit')->orderBy('designation','asc')->get();
        $transformation = DB::table('transformation')->orderBydesc('id')->get();

        return view('production/nouveau-trans',[

            //'produit' => $produit,
            'produit_vendable' => $produit_vendable,
            'transformation' => $transformation,
        ]);
    }


    function enregistrer(Request $request)
    {

        $produit= request('produit_obtenu');
        $qte= request('qte_obtenu');
        
		$datep= date('Y-m-d');
        
		$nbreencarton = DB::table('produit_vendable')->where('id', $produit)->first()->nbreencarton;
		$quantiteemb = $nbreencarton * $qte;
		$emballage = DB::table('emballage_produit')->where('produit_id',  $produit)->get();
		foreach($emballage as $emballages){
			$desi =  DB::table('emballage')->where('id', $emballages->emballage_id)->first()->designation;
            $qtesto = DB::table('emballage')->where('id', $emballages->emballage_id)->first()->stock_general;
			
			$verif = DB::table('stock_emballage')->where('emballage_id', $emballages->emballage_id)->get()->count();
			if ($verif >0){
				$stockresto = DB::table('stock_emballage')->where('emballage_id', $emballages->emballage_id)->orderBydesc('id')->take(1)->first()->apres;
			} else{
				$stockresto =  0;
			}
			if ($quantiteemb > $stockresto){
				$message = [
						"title" => 'Erreur d\'enregistrement',
						"type" => 'error',
						"response" => 'Stock insuffant de '.' '.$desi.' '.' pour enregistrer cette production',
					];
		
					return $message;
			}
        }
        $approvision=collect(request('approvision'))->chunk(2);

            DB::table('production')->insert(
                [
                    'qte' => $qte,
                    'produit_id' => $produit,
                    'date' => $datep,
                    'etat' => "Non validé",
                    //'emballage_id' => "Non validé",
                   
                ]
            );

            $idLastprod = DB::table('production')->get()->last()->id;

            $id2= strlen($idLastprod);

            if ($id2==1){

                DB::table('production')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'P-000'.$idLastprod,
                    ]
                );

            } elseif ($id2==2){

                DB::table('production')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'P-00'.$idLastprod,
                    ]
                );

            } elseif ($id2==3){

                DB::table('production')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'P-0'.$idLastprod,
                    ]
                );

            } else {

                DB::table('production')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'P-'.$idLastprod,
                    ]
                );
            }

        $i=0;

        foreach ($approvision as $key=> $approvisions){
			
			//$qtesto =  DB::table('stock_resto')->where('produit_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			$qcount =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->get()->count();
			if ($qcount > 0){
			$qtesto2 =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$qtesto2 = 0;
			}
            $desi =  DB::table('matiere')->where('id', $approvisions[0 +$i])->first()->designation;

            if($qtesto2 < $approvisions[1 +$i]){

                DB::table('production')->where('id', $idLastprod)->delete();

                DB::table('ligne_production')->where('production_id', $idLastprod)->delete();

                $message = [
                    "title" => 'Erreur d\'enregistrement',
                    "type" => 'error',
                    "response" => 'La quantité de'.' '.$desi.' est insuffisante: stock actuel '.$qtesto2,
                ];
    
                return $message;

            }else{

                DB::table('ligne_production')->insert(
                    [
                        'production_id' => $idLastprod,
                        'etat' => "Non validé",
						'date' => $datep,
                        'matiere_id' => $approvisions[0 +$i],
                        'qte' => $approvisions[1 +$i],
                    ]
                );
                $i += count($approvisions->toArray());

            }

        }

            $message = [
                "title" => 'Succès',
                "type" => 'success',
                "response" => 'Enregistrement effectué avec succès !',
            ];

            return $message;
    }
	function enregistrer2(Request $request)
    {

        $produit= request('produit_obtenu');
        $qte= request('qte_obtenu');
        
		$datep= date('Y-m-d');
        
		
        $approvision=collect(request('approvision'))->chunk(2);

            DB::table('transformation')->insert(
                [
                    'qte' => $qte,
                    'produit_id' => $produit,
                    'date' => $datep,
                    'etat' => "Non validé",
                   
                ]
            );

            $idLastprod = DB::table('transformation')->get()->last()->id;

            $id2= strlen($idLastprod);

            if ($id2==1){

                DB::table('transformation')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'transformation-000'.$idLastprod,
                    ]
                );

            } elseif ($id2==2){

                DB::table('transformation')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'transformation-00'.$idLastprod,
                    ]
                );

            } elseif ($id2==3){

                DB::table('transformation')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'transformation-0'.$idLastprod,
                    ]
                );

            } else {

                DB::table('transformation')->where('id', $idLastprod)->update(
                    [
                        'numero' => 'transformation-'.$idLastprod,
                    ]
                );
            }

        $i=0;

        foreach ($approvision as $key=> $approvisions){
			
			//$qtesto =  DB::table('stock_resto')->where('produit_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			$qcount =  DB::table('stock_resto')->where('produit_id', $approvisions[0 +$i])->get()->count();
			if ($qcount > 0){
			$qtesto2 =  DB::table('stock_resto')->where('produit_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$qtesto2 = 0;
			}
            $desi =  DB::table('produit_vendable')->where('id', $approvisions[0 +$i])->first()->designation;

            if($qtesto2 < $approvisions[1 +$i]){

                DB::table('transformation')->where('id', $idLastprod)->delete();

                DB::table('ligne_transformation')->where('transformation_id', $idLastprod)->delete();

                $message = [
                    "title" => 'Erreur d\'enregistrement',
                    "type" => 'error',
                    "response" => 'La quantité de'.' '.$desi.' est insuffisante: stock actuel '.$qtesto2,
                ];
    
                return $message;

            }else{

                DB::table('ligne_transformation')->insert(
                    [
                        'transformation_id' => $idLastprod,
                        'etat' => "Non validé",
						'date' => $datep,
                        'produit_id' => $approvisions[0 +$i],
                        'qte' => $approvisions[1 +$i],
                    ]
                );
                $i += count($approvisions->toArray());

            }

        }

            $message = [
                "title" => 'Succès',
                "type" => 'success',
                "response" => 'Enregistrement effectué avec succès !',
            ];

            return $message;
    }

	// Fonction supprimer
	function supprimer () {

        $id=request('id');

        DB::table('ligne_production')->where('production_id', $id)->delete();

        DB::table('production')->where('id', $id)->delete();

        return redirect()->route('production')->with('status', 'Suppression effectuée avec succes');
      

    }
	function supprimer2 () {

        $id=request('id');

        DB::table('ligne_transformation')->where('transformation_id', $id)->delete();

        DB::table('transformation')->where('id', $id)->delete();

        return redirect()->route('transformation')->with('status', 'Suppression effectuée avec succes');
      

    }
	
}
