<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\InventoryRequest;
use Illuminate\Contracts\Encryption\DecryptException;

use App\Plot;
use App\User;
use App\Branch;

use EF;
use Crypt;
use DataTables;

class PlotController extends Controller
{
    public function __construct()
    {
        
    }
	public function index()
    {
        $condition = ['Approve','Unapprove'];
        $employee_type = ['Employee'];
        $dealer_type   = ['Dealer','Sub Dealer'];

        $user  =       new User;
        $inventory = new Plot;
        $branch    = new Branch;

        $all_branch_id = $branch->getBranchId();

        $plot_view = view('components.plot.table_plot',[
            //  'inventory_list' => $inventory->getAllPlot(['unsold','sold'],$all_branch_id),
             'plot_labels'    => EF::plotWhiteLabel(),
             'booking_labels'      => EF::getWhiteLabel(),


        ]);

        

        return view('inventory.manage_inventory',
            [
                'inventory_list' => $inventory->getAllPlot(['unsold','sold']),
                'block_list'     => $inventory->getPlotListByColoumn('block_name'),
                'type_list'     => $inventory->getPlotListByColoumn('type'),

                'dimension_list' => $inventory->getPlotListByColoumn('dimensions'),
                'category_list'  => $inventory->getPlotListByColoumn('category'),
                'size_list'      => $inventory->getPlotListByColoumn('size'),
                'floor_list'      => $inventory->getPlotListByColoumn('floor'),

                'plot_labels'    => EF::plotWhiteLabel(),
                'branch'         => $branch->getBranchList(),
                'plot_view'      => $plot_view,

            ]);
    }

    public function showDatatablePlots(Request $request)
    {
        try
        {
            $inventory = new Plot;
            $branch    = new Branch;
            $conditions = ['unsold','sold'];
            $branch_id = $branch->getBranchId();

            if(isset($request->branch) && decrypt($request->branch) > 0)
            {
                $branch_id = [Crypt::decrypt($request->branch)];
            }

            $inventory = $inventory->getAllPlot($conditions,$branch_id);
            
            
            if(isset($request->block))
            {
                $inventory = $inventory->where('block_name', decrypt($request->block));
            }

            $count = 0;

            return DataTables::of($inventory)

                ->addColumn('count', function($rows) use (&$count) {
                    return strval(++$count);

                })
                ->addColumn('status', function($rows){


                  if($rows->status == "unsold")
                  {
                    $view = '<span class="badge badge-primary">'.$rows->status.'</span>';
                  }
                  else
                  {
                    $view = '<span class="badge badge-warning text-dark"> '.$rows->status.'</span>';
                  }

                  return $view;

                })
                ->addColumn('branch_name', function($rows) {
                    return $rows->branch->name;
                })
                ->addColumn('article_no', function($rows) {
                    return EF::showPlotFormat($rows);
                })
                
                ->addColumn('action', function($rows) {
                    return view('inventory.actions.inventory_actions',[
                        'rows' => $rows
                    ]);
                })


                ->rawColumns(['status','count','action'])
                ->make(true);
        }
        catch(DecryptException $e)
        {

        }
    }

    public function showAvailablePlot()
    {


        $condition = ['Approve','Unapprove'];
        $employee_type = ['Employee'];
        $dealer_type   = ['Dealer','Sub Dealer'];

        $user  =       new User;

        $inventory = new Plot;
        $branch    = new Branch;

        $all_branch_id = $branch->getBranchId();


        $plot_view = view('components.plot.table_plot',[
             'inventory_list' => $inventory->getAllPlot(['unsold'],$all_branch_id['0']),
             'plot_labels'    => EF::plotWhiteLabel(),
             'booking_labels'      => EF::getWhiteLabel(),


        ]);

        

        return view('inventory.manage_inventory',
            [
                'inventory_list' => $inventory->getAllPlot(['unsold']),
                'block_list'     => $inventory->getPlotListByColoumn('block_name'),
                'type_list'     => $inventory->getPlotListByColoumn('type'),

                'dimension_list' => $inventory->getPlotListByColoumn('dimensions'),
                'category_list'  => $inventory->getPlotListByColoumn('category'),
                'size_list'      => $inventory->getPlotListByColoumn('size'),
                'floor_list'      => $inventory->getPlotListByColoumn('floor'),

                'plot_labels'    => EF::plotWhiteLabel(),
                'branch'         => $branch->getBranchList(),
                'plot_view'      => $plot_view,

            ]);
    }

    public function getAllPlotBlockByProject($project)
    {
        try
        {
             $plot = new Plot;
             //project_id refers to branch_id
             $project_id = decrypt($project);
             // $project_id = 2;
             $column = 'block_name';
             $condition = ['branch_id'=> $project_id];
             $status = ['unsold'];

         
// dd($availability);

             $block_list = $plot->getAllPlotListByColoumn($column,$condition,$status);
             $view = '<option value="'.Crypt::encrypt(0).'">Select Block</option>';

             foreach($block_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->block_name).'">'.$rows->block_name.'</option>';
             }
                return $view;

        }
        catch(DecryptException $e)
        {

        }
    }

    public function updateInventory(InventoryRequest $request)
    {
        try
        {
            $plot_labels = EF::plotWhiteLabel();

            $form_collect = $request->input();

            if(isset($form_collect['parking_check']))
            {
                 $form_collect['parking_check'] =  1;
            }
            else
            {
                $form_collect['parking_check'] =  0;
            }

            // $form_collect[$plot_labels['branch']]    = decrypt($form_collect[$plot_labels['branch']]);

            $form_collect[$plot_labels['inventory']] = decrypt($form_collect[$plot_labels['inventory']]);



            $fetch_block = $form_collect[$plot_labels['block']];

            if($fetch_block === "Other")
            {
               $form_collect[$plot_labels['block']] = $form_collect['other_block'];
            }
            else if($fetch_block === "selected")
            {
                $form_collect[$plot_labels['block']] = NULL;
            }

            $inventory = new Plot;

            $inventory = $inventory->inventoryUpdate($form_collect,$plot_labels);

            if(isset($inventory->id))
            { 
                parent::setLogMessage(ucwords(ucwords(EF::plotWhiteLabel()['module'])).' '.$inventory->plot_id.' '.$inventory->type.' rate .'.number_format($inventory->rate).' has been updated.');

                parent::successMessage(ucwords(ucwords(EF::plotWhiteLabel()['module'])).' has been updated.',parent::getLogMessage());
            }
        }
        catch (DecryptException $e) 
        {
            
        }

        return redirect()->back();
    }

    public function storeInventory(InventoryRequest $request)
    {

        $form_collect = $request->input();


        if(isset($form_collect['parking_check']))
        {
             $form_collect['parking_check'] =  1;
        }
        else
        {
            $form_collect['parking_check'] =  0;
        }

        $plot_labels = EF::plotWhiteLabel();


        $fetch_block = $form_collect[$plot_labels['block']];

        if($fetch_block === "Other")
        {
           $form_collect[$plot_labels['block']] = $form_collect['other_block'];
        }
        else if($fetch_block === "selected")
        {
            $form_collect[$plot_labels['block']] = NULL;
        }

        $form_collect[$plot_labels['branch']] = decrypt($form_collect[$plot_labels['branch']]);
        
        $plot = new Plot;
        $count = $plot->isPlotSold($form_collect);
        if($count > 0){
            parent::errorMessage('Plot has found.' ,parent::getLogMessage());
            return redirect()->back();
        }
        
        $inventory = new Plot;
        $inventory = $inventory->storeInventory($form_collect,$plot_labels);

        if(isset($inventory->id))
        { 
            if(\Request::ajax())
            {
                parent::clearMessageLog(1);
                return $inventory;
            }

            parent::setLogMessage(ucwords(EF::plotWhiteLabel()['module']).$inventory->plot_id.' '.$inventory->type.' rate .'.number_format($inventory->rate).' has been added.');

            parent::successMessage(ucwords(EF::plotWhiteLabel()['module']) .' has been added.',parent::getLogMessage());
        }

        return redirect()->back();
    }

    public function updateBulkInventory(InventoryRequest $request)
    {
        try
        {
            $plot_condition = [];
            
            $plot_labels = EF::plotWhiteLabel();

            $form_collect = $request->input();
            // $block       = decrypt($form_collect[$plot_labels['block']]);
            $type   = decrypt($form_collect[$plot_labels['type']]);

            $category    = decrypt($form_collect[$plot_labels['category']]);
            // $dimension   = decrypt($form_collect[$plot_labels['dimension']]);
            $size        = decrypt($form_collect[$plot_labels['size']]);

            $floor        = decrypt($form_collect[$plot_labels['floor']]);


          

            // if($block != "0")
            // {
            //     $plot_condition += ['type' => $block];


            // }

            if($type != "0")
            {
                $plot_condition += ['type' => $type];


            }

            if($category != "0")
            {
                $plot_condition += ['category' => $category];
            }

            // if($dimension != "0")
            // {
            //     $plot_condition += ['dimensions' => $dimension];
            // }

            if($size != "0")
            {
                $plot_condition += ['size' => $size];
            }

            if($floor != "0")
            {
                $plot_condition += ['floor' => $floor];
            }


            $inventory = new Plot;

            if(@count($plot_condition) > 0 && $inventory->updateBulkInventory($form_collect,$plot_condition,$plot_labels))
            { 
                

                parent::successMessage('Bulk rate '.number_format($request->rate).' has been updated.');
            }
            else
            {
                parent::errorMessage('One selection field is required.');
            }
        }
        catch (DecryptException $e) 
        {
            
        }

        return redirect()->back();
    }

    public function getPlotByBlock($block)
    {
    	
        try
        { 
             $plot = new Plot;
             $type = decrypt($block);
             $plot_list = $plot->getPlotByBlock($type);
             $view = '<option value="0">Select Plot</option>';

             foreach($plot_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->plot_id.' '.$rows->category.'</option>';
             }
                return $view;

        }
        catch(DecryptException $e)
        {

        }
    }
    // public function getPlots($category,$type,$project)
    // {
        
    //     try
    //     { 
    //          $plot = new Plot;
    //          $category = decrypt($category);
    //          $type = decrypt($type);
    //          $project = decrypt($project);
      
    //          $plot_list = $plot->getPlots($category,$type,$project);
       
    //          $view = '<option value="'.Crypt::encrypt(0).'">Select Article</option>';

    //          foreach($plot_list as $rows)
    //          {
    //            $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->plot_id.' '.$rows->category.'</option>';
    //          }
    //             return $view;

    //     }
    //     catch(DecryptException $e)
    //     {

    //     }
    // }

    public function getPlots($project)
    {
        
        try
        { 
             $plot = new Plot;
           
             $project = decrypt($project);
      
             $plot_list = $plot->getPlots($project);
       
             $view = '<option value="'.Crypt::encrypt(0).'">Select Article</option>';

             foreach($plot_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.EF::showPlotFormat($rows).'</option>';
             }
                return $view;

        }
        catch(DecryptException $e)
        {

        }
    }

    public function getPlotTypeByProject($project)
    {
        
        try
        { 
             $plot = new Plot;
             //project_id refers to branch_id
             $project_id = decrypt($project);
             // $project_id = 2;
             $column = 'type';
             $condition = ['branch_id'=> $project_id];
             $status = ['unsold'];
             $type_list = $plot->getPlotListByColoumn($column,$condition,$status);

             $view = '<option value="'.Crypt::encrypt(0).'">Select Type</option>';

             foreach($type_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->type).'">'.$rows->type.'</option>';
             }
                return $view;

        }
        catch(DecryptException $e)
        {

        }
    }
         public function getPlotCategory($type,$project)
    {
        
        try
        { 
             $plot = new Plot;
             //project_id refers to branch_id
              $project_id = decrypt($project);
             $type = decrypt($type);
            
             $column = 'category';
             $condition = ['branch_id'=> $project_id ,'type'=> $type];
             $status = ['unsold'];
             $category_list = $plot->getPlotListByColoumn($column,$condition,$status);
            

             $view = '<option value="'.Crypt::encrypt(0).'">Select Category</option>';

             foreach($category_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->category).'">'.$rows->category.'</option>';
             }
                return $view;

        }
        catch(DecryptException $e)
        {

        }
    }

    public function getPlotBySize($id)
    {
        try
        {
             $plot = new Plot;

             $plot_id = decrypt($id);

             $plot_info = $plot->getPlotById($plot_id);

             if(isset($plot_info->id))
             {
                $plot_info->plot_detail = EF::showPlotFormat($plot_info);

                if(strlen(trim($plot_info->floor)) > 0)
                {
                    $plot_info->file_detail = $plot_info->branch->code.'/'.$plot_info->floor.'-'.$plot_info->plot_id;
                }
                else
                {
                    $plot_info->file_detail = $plot_info->branch->code.'-'.$plot_info->plot_id;
                }
                

             }

             return $plot_info;
        }
        catch(DecryptException $e)
        {

        }
     
    }

    public function removePlot($id)
    {
        // return redirect('home');
        
        parent::errorMessage(ucwords(EF::plotWhiteLabel()['module']).'not found.');

        try 
        {
            $id = decrypt($id);

            $inventory = new Plot;

            if($inventory->removePlot($id))
            {
                parent::successMessage(ucwords(EF::plotWhiteLabel()['module']).'has been removed.');
            } 
        } 
        catch (DecryptException $e) 
        {
            
        }

        return redirect('plots');
    }

    public function getBranchWiseBlock($project)
    {
       if(\Request::ajax())
       {
          try 
          {
             $view = '<option value="selected">Select Block</option>';

             $project = decrypt($project);

             $inventory = new Plot;

             $inventory_list = $inventory->getBranchWisePlotList([$project],'block_name');


             foreach ($inventory_list as $rows) 
             {
                $view .= '<option value="'.$rows->block_name.'">'.$rows->block_name.'</option>';
             }

             $view .= '<option value="Other">Other</option>';


             return $view;
          } 
          catch (DecryptException $e) 
          {
              
          }
       }
       

       return redirect()->back();
    }

     public function showPlot($plot)
    {
        if(\Request::ajax())
        {
            try
            {
               $plot = decrypt($plot);

               $inventory = new Plot;
               $branch = new Branch;


               $curr_plot = $inventory->getPlotById($plot);

               if(isset($curr_plot->id))
               {
                    return view('inventory.modals.update_inventory',[
                        'curr_plot'          => $curr_plot,
                         'inventory_list' => $inventory->getAllPlot(['unsold']),
                        'block_list'     => $inventory->getPlotListByColoumn('type'),
                        'type_list'     => $inventory->getPlotListByColoumn('type'),

                        'dimension_list' => $inventory->getPlotListByColoumn('dimensions'),
                        'category_list'  => $inventory->getPlotListByColoumn('category'),
                        'size_list'      => $inventory->getPlotListByColoumn('size'),
                        'plot_labels'    => EF::plotWhiteLabel(),
                        'branch'         => $branch->getBranchList(),
                        'project_block_list' => $inventory->getBranchWisePlotList([$curr_plot->branch_id],'block_name'),

                    ])->render();
               }

               
            }
            catch (DecryptException $e) 
            {
                
            }

            return '';
        }

        return redirect('/');
    }
}
