<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Country;
use App\City;
use App\BuyBack;
use App\Inventory;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\DepositorBank;
use App\CompanyBank;

class BuyBackController extends Controller
{
    public function __construct() 
    {
        
    }
    
    function  index ()
    {
        $buyback_properties = BuyBack::where('is_approve' , 1)->orderBy('id' , 'ASC')->get();
        return view('buy-back.index',compact('buyback_properties'));
    }
    
    function add()
    {
        $buyback_properties = BuyBack::where('is_approve' , 1)->orderBy('id' , 'ASC')->get(['ref_no', 'id']);
        return view('buy-back.add',compact('buyback_properties'));
    }
    
    function insert(Request $request)
    {
        
         $validator = Validator::make($request->all(), [
                'ref_no' => 'required|unique:buy_back,ref_no,'.$request->bb_requ_form,
                'date' => 'required',
                'party_code'=>'required',
                'total_amount_invested'=>'required',
                'total_amount_received'=>'required',
                'if_merging_then_value_of_merging'=>'required',
                'buy_back_value_requested_by_client' => 'required',
                'buy_back_option' => 'required',
                'roi_terms'=>'required',
                'sales_agents'=>'required',
                'merging_sold'=>'required',
                'merging_receipts' => 'required',
                'rental_discount_paid_to_customer_for_unit'=>'required',
                'loss_or_profit_on_merging'=>'required',
                'total_rebate_payable'=>'required',
                'rebate_paid'=>'required',
                'merging_selling_expenses' => 'required',
                'rebate_on_buy_back' => 'required',
                'value_of_appreciation_in_pkr'=>'required',
        ]);



        if ($validator->fails()) 
        {
            return redirect('/buy-back/add')
            ->withErrors($validator)
            ->withInput()
            ->with([
            'message' => 'Invalid Inputs!',
            'alert-type' => 'error',
            ]);
        }
        
       // die;
         DB::beginTransaction();
        try 
        {
            BuyBack::where('id' , $request->bb_requ_form)->update(Input::except('_token','bb_requ_form'));
            DB::commit();
            return redirect('/buy-back/add')
            ->with([
            'message' => 'Buy Back Property Added Successfully',
            'alert-type' => 'info',
            ]);
        }
        catch (\Exception $e) 
        {
           //dd($e);
            DB::rollback();
            return redirect('/buy-back/add')
            ->withInput()
            ->with([
            'message' => 'Buy Back Property Not Added ',
            'alert-type' => 'error',
            ]);
        }
        
    }
    
        function getBBRequisiData(Request $request)
        {
          $buyback = BuyBack::where('id' , $request->bb_id)->with('inventory','DepositorBank','companyAccount')->first(); 
          
            if($buyback == true)
            {
              echo json_encode(array('output' => $buyback , 'depositer_bank' => $buyback->DepositorBank->name , 'company_bank' => $buyback->companyAccount->name));
            }
            else
            {
                echo json_encode(array('output' => ''));
            }
        }
    
        function form($id)
        {
            $buyback =  BuyBack::where('id' , $id)->first();
            return view('buy-back.bb_form' , compact('buyback'));
        }
    
    
         ////////////// property Buy Back requisition form Section///////////////////////////////
    
    
          function  indexBuyBack()
        {
            $buyback_properties = BuyBack::with('inventory')->orderBy('id' , 'ASC')->get();
            return view('buy-back.requisition_index',compact('buyback_properties'));
        }
        
          function  pendingApproval()
        {
            $buyback_properties = BuyBack::where('is_approve' , 0)->orderBy('id' , 'ASC')->get();
            return view('buy-back.pending_approval',compact('buyback_properties'));
        }

    
        function addBuyBack()
        {
          $unitNumbers = Inventory::where([['is_deleted',false]])->orderby('unit_number','asc')->select('id','unit_number AS name')->get();
          $banks = DepositorBank::all();
            $cBanks = CompanyBank::all();
           return view('buy-back.requisition_add',compact('unitNumbers','banks' ,'cBanks'));
        }
    
    function insertBuyBack(Request $request)
    {
         $validator = Validator::make($request->all(), [
                'ref_no' => 'required|unique:buy_back,ref_no',
                'date' => 'required',
                'party_code'=>'required',
                'inventory_id'=>'required',
                'total_amount_invested'=>'required',
                'total_amount_received'=>'required',
                'if_merging_then_value_of_merging'=>'required',
                'buy_back_value_requested_by_client' => 'required',
                'buy_back_option' => 'required',
                'roi_terms'=>'required',
                'sales_agents'=>'required',
                'merging_sold'=>'required',
        ]);



        if ($validator->fails()) 
        {
            return redirect('/buy-back/add-requisition')
                            ->withErrors($validator)
                            ->withInput()
                            ->with([
                                'message' => 'Invalid Inputs!',
                                'alert-type' => 'error',
            ]);
        }
        
        
         DB::beginTransaction();
        try 
        {
        //    $buyback_properties = BuyBack::create(Input::all());
            $input=$request->all();
            $buyback_properties = BuyBack::create($input);

            DB::commit();
            return redirect('/buy-back/add-requisition')
                            ->with([
                                'message' => 'Buy Back Requisition  Added Successfully',
                                'alert-type' => 'info',
            ]);
        }
        catch (\Exception $e) 
        {
            //dd($e);
            DB::rollback();
            return redirect('/buy-back/add-requisition')
            ->withInput()
            ->with([
            'message' => 'Buy Back Requisition Property Not Added ',
            'alert-type' => 'error',
            ]);
        }
    }
    
    public function pendingApprovalStatus($id ,  Request $request)
    {
       BuyBack::where('id' , $id)->update(['is_approve' => $request->status]);
       
       if($request->status == 1)
       {
           return back()->with([
            'message' => 'Buy Back  Requisition Property Approved',
            'alert-type' => 'success',
            ]);
       }
       else
           {
               return back()->with([
            'message' => 'Buy Back  Requisition Property Cancel',
            'alert-type' => 'error',
            ]);
           } 
    }
    
    function formBuyBack($id)
    {
        $buyback =  BuyBack::where('id' , $id)->first();
        
        return view('buy-back.bb_req_form' , compact('buyback'));
    }
    
    
    
      ////////////// property Buy Back payment form Section///////////////////////////////
    
    
          function  indexPayment()
        {
            $buyback_payment = BuyBack::with('inventory')->orderBy('id' , 'ASC')->get();
            return view('buy-back.payment_index',compact('buyback_payment'));
        }
        
      
        function addPayment()
        {
           $buyback_payments = BuyBack::where('is_approve' , 1)->orderBy('id' , 'ASC')->get(['ref_no', 'id']);
           return view('buy-back.add_payment',compact('buyback_payments'));
        }
    
    function insertPayment(Request $request)
    {
        $validator = Validator::make($request->all(), [
        'ref_no' => 'required|unique:buy_back,ref_no,'.$request->bb_requ_form,
        'date' => 'required',
        'party_code'=>'required',
        'total_amount_invested'=>'required',
        'total_amount_received'=>'required',
        'if_merging_then_value_of_merging'=>'required',
        'buy_back_value_requested_by_client' => 'required',
        'buy_back_option' => 'required',
        'roi_terms'=>'required',
        'sales_agents'=>'required',
        'merging_sold'=>'required',
        'total_amount' => 'required',
        'payee_name'=>'required',
        'payee_cnic'=>'required',
        ]);


        if ($validator->fails()) 
        {
            return redirect('/buy-back/add-payment')
            ->withErrors($validator)
            ->withInput()
            ->with([
            'message' => 'Invalid Inputs!',
            'alert-type' => 'error',
            ]);
        }
        
        
         DB::beginTransaction();
        try 
        {
            BuyBack::where('id' , $request->bb_requ_form)->update(Input::except('_token','bb_requ_form'));
            DB::commit();
            return redirect('/buy-back/add-payment')
            ->with([
            'message' => 'Buy Back Payment Added Successfully',
            'alert-type' => 'info',
            ]);
        }
        catch (\Exception $e) 
        {
           //dd($e);
            DB::rollback();
            return redirect('/buy-back/add-payment')
            ->withInput()
            ->with([
            'message' => 'Buy Back Payment Not Added ',
            'alert-type' => 'error',
            ]);
        }
        
    }
   
    
    function formPayment($id)
    {
        $buyback =  BuyBack::where('id' , $id)->first();
        
        return view('buy-back.bb_pay_form' , compact('buyback'));
    }
    
}
