<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;
use EF;

class Plot extends Model
{
  
	private $generic_condition = [];

	public function __construct()
	{
	   $this->setCondition(['is_recycle' => 0]);
	}

	public function setCondition($condition = [])
	{
       $this->generic_condition = $condition;
	}

	public function getCondition()
	{
       return $this->generic_condition;
	}

  public function getPlotListByGroup($column,$status = ['unsold','sold','reserve'])
  {
     return Plot::groupby($column)->whereIn('status',$status)->orderBy($column,'asc')->selectRaw($column.', count('.$column.') AS count')->get();
  }

  public function storeInventory($object,$plot_labels)
  {
    return DB::transaction(function () use ($object,$plot_labels){

            $inventory = new Plot;

            $inventory->plot_id            =  $object[$plot_labels['plot_name']];
            $inventory->type         =  $object[$plot_labels['type']];
            $inventory->category     =  $object[$plot_labels['category']];

            if($object[$plot_labels['dimension_x']] > 0 && $object[$plot_labels['dimension_y']] > 0)
            {
              $inventory->dimensions   =  $object[$plot_labels['dimension_x']].' X '.$object[$plot_labels['dimension_y']];
            }
            
            $inventory->size         =  $object[$plot_labels['size']];
            $inventory->rate         =  $object[$plot_labels['rate']];
            $inventory->branch_id    =  $object[$plot_labels['branch']];
            $inventory->featurecharges     =  $object[$plot_labels['feature_charges']];
            $inventory->parking_check      = $object['parking_check'];
            $inventory->block_name         = $object[$plot_labels['block']];
            $inventory->floor              =  $object[$plot_labels['floor']];
            $inventory->feature_description =  $object[$plot_labels['feature_description']];


            $inventory->save();

            return with($inventory);
        

     });
  }

  public function inventoryUpdate($object,$plot_labels)
  {
     return DB::transaction(function () use ($object,$plot_labels){
        $booking = new Booking;
        $inventory = Plot::find($object[$plot_labels['inventory']]);

        if(isset($inventory->id))
        {
            $dimension_x = $object[$plot_labels['dimension_x']];
            $dimension_y = $object[$plot_labels['dimension_y']];

            $inventory->plot_id      =  $object[$plot_labels['plot_name']];
            $inventory->type         =  $object[$plot_labels['type']];     
            $inventory->category     =  $object[$plot_labels['category']];

            if($dimension_x > 0 && $dimension_y > 0)
            {
                $inventory->dimensions   =  $dimension_x.' X '.$dimension_y;
            }
            else
            {
              $inventory->dimensions = NULL;
            }
            
            $inventory->size         =  $object[$plot_labels['size']];
            $inventory->rate         =  $object[$plot_labels['rate']];
            // $inventory->branch_id    =  $object[$plot_labels['branch']];
          
            $inventory->feature_description =  $object[$plot_labels['feature_description']];
            $inventory->featurecharges     =  $object[$plot_labels['feature_charges']];
            $inventory->parking_check      = $object['parking_check'];
            $inventory->block_name         = $object[$plot_labels['block']];
            $inventory->floor              =  $object[$plot_labels['floor']];

            $inventory->update();

            $curr_booking = $booking->getBookingByPlotId($inventory->id);

            if(isset($curr_booking->id))
            {
              $curr_booking->file_number = $inventory->branch->code.'/'.$inventory->floor.'-'.$inventory->plot_id;
              $curr_booking->reference_number = EF::showPlotFormat($inventory);
              $curr_booking->update();
            }
            return with($inventory);
        }

     });
  }

  public function updateBulkInventory($object,$condition,$plot_labels)
  {
     return DB::transaction(function () use ($object,$condition,$plot_labels){

        $columns = ['rate' => $object[$plot_labels['rate']]];

        $condition += $this->getCondition();

        $condition += ['status' => 'unsold'];

        return Plot::where($condition)->update($columns);

     });
  }

  public function getAllPlot($status = ['sold','unsold'],$branch = [])
  {
     $condition = $this->getCondition();

     return Plot::where($condition)->whereIn('status',$status)->whereIn('branch_id',$branch)->get();
  }



    public function getPlotByBlock($block)
    {
    	$condition = $this->getCondition();

    	$condition += ['block_name' => $block, 'status' => 'unsold'];

      return Plot::where($condition)->get();
    }

    // public function getPlots($category,$type,$project)
    // {
    //   $condition = $this->getCondition();

    //   $condition += ['category' => $category,'type'=> $type,'branch_id'=>$project,'status' => 'unsold'];

    //   return Plot::where($condition)->get();
    // }


    public function getPlots($project)
    {
      $condition = $this->getCondition();

      $condition += ['branch_id'=>$project,'status' => 'unsold'];

      return Plot::where($condition)->get();
    }
    public function getPlotListByColumn($column)
   {
       return Plot::where($this->getCondition())->distinct($column)->orderBy($column,'asc')->get([$column]);
   }
    public function getInventoryCountByStatus($status = [])
    {
       return Plot::where($this->getCondition())->wherein('status',$status)->count();
    }
    public function getPlotById($id)
    {
         $condition = $this->getCondition();

         $condition += ['id' => $id];

         return Plot::where($condition)->first();
    }

   //RETRIEVING DISTINCT BLOCK BY NAME
    public function getBlockList()
    {
    	return Plot::where($this->getCondition())->distinct()->get(['block_name']);
    }

    public function getPlotListByColoumn($column,$condition = [],$status = ['sold','unsold','reserve'])
    {

      $condition += $this->getCondition();
      
        return Plot::where($condition)->whereIn('status',$status)->distinct($column)->orderBy($column,'desc')->get([$column]);
    }
    public function getAllPlotListByColoumn($column,$condition = [],$status = ['sold','unsold','reserve'])
    {

      $condition += $this->getCondition();

        return Plot::where($condition)->whereIn('status',$status)->distinct($column)->orderBy($column,'asc')->get([$column]);
    }
   
    public function getPlotOfBranchByBlock($branch,$block, $availability = [0,1], $status = ['unsold'])
    {
    	$condition = $this->getCondition();

    	$condition += ['branch_id' => $branch,'block_name' => $block];

      return Plot::where($condition)->whereIn('status', $status)->get();
    }

    public function getBlockByStatus($condition)
   {
       $block_list = $this->getBlockList(); 

       $block = array();        

      foreach ($block_list as $rows)
      {
          $count = Plot::where(['block_name'  =>  $rows->block_name, 'is_recycle'   =>  '0'])->whereIn('status',$condition)->count();           

          $block[] = ['block_name' => $rows->block_name, 'nof_plot' => $count];
      }  

      return $block;
   }

   //Updating Plot status 
    public function updatePlotStatus($column = [],$id)
    {
        return DB::transaction(function () use ($id,$column) {

           $condition = $this->getCondition();

           $condition += ['id' => $id];

           Plot::where($condition)->update($column);


            
            
        });

    }

    public function inventoryReport($plot_condition = [])
    {
       $plot_condition += $this->getCondition();

       return Plot::where($plot_condition)->orderBy('block_name','asc')->get();
    }

    public function booking()
    {
        return $this->hasOne(Booking::class)->withDefault();
    }


    public function branch()
    {
        return $this->belongsTo(Branch::class,'branch_id')->withDefault();
    }

    public function removePlot($id)
    {
        return DB::transaction(function () use ($id) {

            $inventory = Plot::find($id);

            if(isset($inventory->id) && $inventory->bookings->count() == 0)
            {
                $inventory->is_recycle   = '1';
                $inventory->status       = 'unsold';

                
                $inventory->update();

                return 1;
            }

            
            return 0;
        });
    }

    public function getInventoryCountByStatusBranchwise($status = [],$branch_ids = [])
    {
       return Plot::where($this->getCondition())->wherein('status',$status)->branchwise($branch_ids)->count();
    }

    public function scopeBranchwise($query,$branch_ids){

        if(in_array(0,$branch_ids))
        {
            $branch_ids = Branch::where($this->getCondition())->pluck('id')->toArray();
        }

        return $query->whereIn('branch_id',$branch_ids);
    }

    public function getPlotListByGroupBranchwise($column,$status = ['unsold','sold','reserve'],$branch_ids = [])
    {
       return Plot::groupby($column)->whereIn('status',$status)->branchwise($branch_ids)->orderBy($column,'asc')->selectRaw($column.', count('.$column.') AS count')->get();
    }
  

    public function getBranchWisePlotList($branch,$column)
   {
    
       return Plot::whereIn('branch_id',$branch)->where($this->getCondition())->distinct($column)->orderBy($column,'asc')->get([$column]);
   }

   public function isPlotSold($form_collect)
   {
     $count = Plot::where(
            ['branch_id'=>$form_collect['project'],
            'floor'=>$form_collect['floor'],
            'plot_id'=>$form_collect['article_no'],
            'type'=>$form_collect['type'],
            'category'=>$form_collect['category'],'is_recycle' => '0'])->count();
     return $count;
   }

   public function bookings()
   {
      return $this->hasMany(Booking::class,'plot_id')->where('is_recycle','0');
   }
    
}
