<?php

namespace App\Http\Controllers\Administrator\Construction;

use App\ClientModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\ConstructionModel\BOQModel;
use App\ProjectModel;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\DataTables;
use DB;
use App\RelationshipStatus;

class EditHouseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:Edit-House-Create', ['only' => ['create','store']]);
        $this->middleware('permission:Edit-House-List', ['only' => ['index']]);
        $this->middleware('permission:Edit-House-Edit', ['only' => ['edit','update']]);
        $this->middleware('permission:Edit-House-Show', ['only' => ['show']]);
        $this->middleware('permission:Edit-House-Print', ['only' => ['contract']]);
        $this->middleware('permission:Edit-House-Set-Complete-Task', ['only' => ['set_to_complete_task']]);
    }
    public function index(Request $request)
    {
        if($request->Ajax()){
            $data =DB::table('nso007_edit_house_info_construction')
            ->join("nso007_project_stock","nso007_project_stock.id","nso007_edit_house_info_construction.project_id")
            ->join("nso007_client","nso007_client.id","nso007_edit_house_info_construction.client_id")
            ->select(
                "nso007_edit_house_info_construction.*",
                "nso007_project_stock.project_name",
                "nso007_client.client_fullname"
            )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->get();
            return  Datatables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('date',function($data){
                    return date('d-m-Y',strtotime($data->date));
                })
                ->editColumn('contract_date',function($data){
                    return date('d-m-Y',strtotime($data->contract_date));
                })
                ->addColumn('client_id',function($data){
                    return $data->client_fullname;
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if($data->status==0){
                        $button .= "<a href='".route('edit_house.edit',Crypt::encrypt($data->id))."' style='margin-left:5px;' class='btn btn-sm btn-primary' title='Edit' data-id='".$data->id."'>
                        <span class='fa fa-edit'></span>
                        </a>";
                    }
                    else{
                        $button .= "<a href='javascript:void(0)' style='margin-left:5px;' class='btn btn-sm btn-primary' title='Edit' disabled data-id='".$data->id."'>
                        <span class='fa fa-edit'></span>
                        </a>";
                    }
                    $button .= "<a href='".route('edit_house.show',Crypt::encrypt($data->id))."' style='margin-left:5px;' class='btn btn-sm btn-success' title='Show Detail' data-id='".$data->id."'>
                        <span class='fa fa-eye'></span>
                        </a>";
                    
                    $button .= "<a href='".route('edit_house.contract',Crypt::encrypt($data->id))."' style='margin-left:5px;' class='btn btn-sm btn-primary' title='Print Contract' data-id='".$data->id."'>
                        <span class='fa fa-print'></span>
                        </a>";
                    
                    if($data->status==1){
                        $button .= "<a href='javascript:void(0)' style='margin-left:5px;' class='btn btn-sm btn-danger' title='Set To Complete Task' data-id='".$data->id."' disabled>
                        <span class='fa fa-check'></span>
                        </a>";
                    }
                    else{
                        $button .= "<a href='javascript:void(0)' style='margin-left:5px;' class='btn btn-sm btn-danger' title='Set To Complete Task' data-id='".$data->id."' onclick='set_to_completed(this)'>
                        <span class='fa fa-check'></span>
                        </a>";
                    }

                    
                    

                    return $button;
                })  
                ->rawColumns(['action'=>'action'])    
                ->make(true);
        }
        return view("administrator.edit-house.index");
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $clients = ClientModel::pluck("client_fullname","id")->prepend("Please Select","");
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })
        ->pluck("project_name","id")->prepend("Please Select","");
        return view("administrator.edit-house.create",compact('clients','projects'));
    }
    public function get_sale_info(Request $request)
    {
        $sale_info = DB::table('nso007_sale_stock')
            ->join("nso007_sale_detail_stock","nso007_sale_detail_stock.saledetail_saleid",'nso007_sale_stock.id')
            ->join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")
            ->select(
                "nso007_sale_stock.id as sale_id",
                DB::raw("GROUP_CONCAT(nso007_item_stock.item_house) as item_names")
            )
            ->where("nso007_item_stock.item_projectid",$request->project_id)
            ->where("nso007_sale_stock.sale_clientid",$request->client_id)
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->groupBy("nso007_sale_stock.id")
            ->get();
        return json_encode($sale_info);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        $this->validate($request,[
            'client_id'=>'required',
            'contract_number'=>'required',
            'contract_date'=>'required',
            'date'=>'required',
            'description.*'=>'required',
            'qty.*'=>'required',
            'fee_price.*'=>'required',
            'project_id'=>'required',
            'sale_id'=>'required'
        ]);
        $data = array(
            'project_id'=>$request->project_id,
            'client_id'=>$request->client_id,
            'contract_number'=>$request->contract_number,
            'contract_date'=>date('Y-m-d',strtotime($request->contract_date)),
            'date'=>date('Y-m-d',strtotime($request->date)),
            'user_id'=>Auth::user()->id,
            'sale_id'=>$request->sale_id
        );
        
        DB::table('nso007_edit_house_info_construction')->insert($data);

        $insert_id = DB::table("nso007_edit_house_info_construction")->max("id");

        foreach($request->description as $key=>$value)
        {
            $data = array(
                'edit_house_main_id'=>$insert_id,
                'request_description'=>$request->description[$key],
                'unit'=>$request->unit[$key],
                'qty'=>$request->qty[$key],
                'fee_price'=>$request->fee_price[$key],
                'user_id'=>Auth::user()->id
            );
            DB::table('nso007_edit_house_info_detail_construction')->insert($data);
        }

        \LogActivity::addToLog('Edit House store successfully !');
        return redirect()->route('edit_house.index')->with('success','Successfully !');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $edit_house_main_id = Crypt::decrypt($id);

        $clients = ClientModel::pluck("client_fullname","id")->prepend("Please Select","");
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })
        ->pluck("project_name","id")->prepend("Please Select","");

        $data = DB::table('nso007_edit_house_info_construction')
                ->join("nso007_project_stock","nso007_project_stock.id",'nso007_edit_house_info_construction.project_id')
                ->join("nso007_client","nso007_client.id",'nso007_edit_house_info_construction.client_id')
                ->select(
                    'nso007_client.client_fullname',
                    'nso007_project_stock.project_name',
                    'nso007_edit_house_info_construction.*'
                )
                ->where("nso007_edit_house_info_construction.id",$edit_house_main_id)->first();

        $data_detail = DB::table('nso007_edit_house_info_detail_construction')->where('edit_house_main_id',$edit_house_main_id)->get();

        $sale_info = DB::table('nso007_sale_stock')
            ->join("nso007_sale_detail_stock","nso007_sale_detail_stock.saledetail_saleid",'nso007_sale_stock.id')
            ->join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")
            ->select(
                "nso007_sale_stock.id as sale_id",
                DB::raw("GROUP_CONCAT(nso007_item_stock.item_house) as item_names")
            )
            ->where("nso007_item_stock.item_projectid",$data->project_id)
            ->where("nso007_sale_stock.sale_clientid",$data->client_id)
            ->where("nso007_sale_stock.id",$data->sale_id)
            ->first();

        return view("administrator.edit-house.show",compact('clients','projects','data','data_detail','sale_info'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $edit_house_main_id = Crypt::decrypt($id);

        $clients = ClientModel::pluck("client_fullname","id")->prepend("Please Select","");
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck("project_name","id")->prepend("Please Select","");

        $data = DB::table('nso007_edit_house_info_construction')->where("id",$edit_house_main_id)->first();

        $data_detail = DB::table('nso007_edit_house_info_detail_construction')->where('edit_house_main_id',$edit_house_main_id)->get();

        $sale_info = DB::table('nso007_sale_stock')
            ->join("nso007_sale_detail_stock","nso007_sale_detail_stock.saledetail_saleid",'nso007_sale_stock.id')
            ->join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")
            ->select(
                "nso007_sale_stock.id as sale_id",
                DB::raw("GROUP_CONCAT(nso007_item_stock.item_house) as item_names")
            )
            ->where("nso007_item_stock.item_projectid",$data->project_id)
            ->where("nso007_sale_stock.sale_clientid",$data->client_id)
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->groupBy("nso007_sale_stock.id")
            ->pluck("item_names","sale_id")
            ->prepend("Please Select","");

        return view("administrator.edit-house.edit",compact('clients','projects','data','data_detail','sale_info'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($id);
        $this->validate($request,[
            'client_id'=>'required',
            'contract_number'=>'required',
            'contract_date'=>'required',
            'date'=>'required',
            'description.*'=>'required',
            'qty.*'=>'required',
            'fee_price.*'=>'required',
            'project_id'=>'required',
            'sale_id'=>'required'
        ]);

        $data = array(
            'project_id'=>$request->project_id,
            'client_id'=>$request->client_id,
            'contract_number'=>$request->contract_number,
            'contract_date'=>date('Y-m-d',strtotime($request->contract_date)),
            'date'=>date('Y-m-d',strtotime($request->date)),
            'sale_id'=>$request->sale_id
        );
        
        DB::table('nso007_edit_house_info_construction')->where("id",$id)->update($data);

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

        foreach($request->description as $key=>$value)
        {
            $data = array(
                'edit_house_main_id'=>$id,
                'request_description'=>$request->description[$key],
                'unit'=>$request->unit[$key],
                'qty'=>$request->qty[$key],
                'fee_price'=>$request->fee_price[$key]
            );
            DB::table('nso007_edit_house_info_detail_construction')->insert($data);
        }

        \LogActivity::addToLog('Edit House update successfully !');
        return redirect()->route('edit_house.index')->with('success','Successfully !');
    }

    public function contract($id)
    {
        $id = Crypt::decrypt($id);
        $data = DB::table('nso007_edit_house_info_construction')
                ->join("nso007_project_stock","nso007_project_stock.id",'nso007_edit_house_info_construction.project_id')
                ->join("nso007_client","nso007_client.id",'nso007_edit_house_info_construction.client_id')
                ->select(
                    'nso007_client.client_fullname',
                    'nso007_client.id as client_id',
                    'nso007_project_stock.project_name',
                    'nso007_project_stock.id as project_id',
                    'nso007_edit_house_info_construction.*'
                )
                ->where("nso007_edit_house_info_construction.id",$id)->first();
        
        $client_info = DB::table('nso007_client')->where('id',$data->client_id)->first();

        $data_detail = DB::table('nso007_edit_house_info_detail_construction')->where('edit_house_main_id',$id)->get();

        $loan_id = DB::table("nso007_loan")->where("loan_saleid",$data->sale_id)->first()->id;

        $relations=RelationshipStatus::where('loan_id',$loan_id)->get();

        $client_relationship='';
        $client_relationship_name = "";
        if($relations!=[]){
            foreach ($relations as $key => $value) {
                $client_relationship.='និ​ង​ឈ្មោះ​ <span class="font-moul-light">'.$value->client_relations->clientship_fullname."</span>";
                $client_relationship.='​ កា​ន់​អ​ត្ត​លេ​ខ​'.$value->client_relations->clientship_cardid;
                $client_relationship.='​ ​ត្រូ​វ​ជា​ '.$value->relationship_status;

                $client_relationship_name .= " , ".$value->client_relations->clientship_fullname;
            }
        }


        $project_info = ProjectModel::where("id",$data->project_id)->first();
        $province_km=optional($project_info->provices)->province_km;
        $district_km=optional($project_info->districts)->district_km;
        $commune_km=optional($project_info->communes)->commune_km;
        $village_km=optional($project_info->villages)->village_km;
        $project_address = (!empty($project_info->house_number)?("ផ្ទះលេខ ".$project_info->house_number):"").(!empty($project_info->street_number)?(" ផ្លូវលេខ ".$project_info->street_number):"").' ភូមិ '.$village_km.' ឃុំ/សង្កាត់ '.$commune_km.' ស្រុក/ខណ្ឌ '.$district_km.' ខេត្ត/ក្រុង '.$province_km;

        $payment_policy = "";
        $payment_policy_detail = "";
        $sale_payment_policies = DB::table('nso007_sale_policy_payment')->where("sale_id",$data->sale_id)->first();
        
        if(!empty($sale_payment_policies))
        {
            $payment_policy.=DB::table("nso007_payment_policy")->where("id",$sale_payment_policies->payment_policy_id)->first()->name;
        }
        
        if(!empty($sale_payment_policies))
        {
            $payment_policy_detail.=optional(DB::table("nso007_payment_policy_detail")->where("id",optional($sale_payment_policies)->policy_detail_id)->first())->name;
        }

        $item_info = DB::table('nso007_sale_stock')
            ->join("nso007_sale_detail_stock","nso007_sale_detail_stock.saledetail_saleid",'nso007_sale_stock.id')
            ->join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")
            ->join("nso007_sub_category_stock","nso007_sub_category_stock.id","nso007_item_stock.item_sub_categoryid")
            ->select(
                "nso007_sale_stock.id as sale_id",
                DB::raw("GROUP_CONCAT(nso007_item_stock.item_house) as item_names"),
                DB::raw("GROUP_CONCAT(nso007_sub_category_stock.sub_category_name) as sub_category_names"),
                "nso007_item_stock.item_street"
            )
            ->where("nso007_item_stock.item_projectid",$data->project_id)
            ->where("nso007_sale_stock.sale_clientid",$data->client_id)
            ->where("nso007_sale_stock.id",$data->sale_id)
            ->first();


        return view("administrator.edit-house.contract",compact('data','data_detail','project_address','client_info','client_relationship','payment_policy_detail','payment_policy','item_info','client_relationship_name'));
    }
    public function set_to_complete_task()
    {
        $id = $_GET['id'];
        DB::table('nso007_edit_house_info_construction')->where('id',$id)->update(['status'=>1]);
        \LogActivity::addToLog('Edit House complete successfully !');
        return redirect()->route('edit_house.index')->with('success','Successfully !');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
