<?php
namespace App\Http\Controllers;
use Validator;
use App\Http\Controllers\Controller;
use App\Project;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Requests\StoreProjectsRequest;
use App\Http\Requests\UpdateProjectsRequest;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;

class ProjectsController extends Controller
{


    /**
     * Display a listing of Project.
     *
     * @return \Illuminate\Http\Response
     */
    public function projects()
    {
        $relations = [
            'projects' => DB::table('projects')->orderby('created_at')->get(),
            'fullPayments' => \App\PaymentPlan::select(\DB::raw("CONCAT(name, ' Booking/Allotment: ', booking, '% - Registry: ', emi, '%') AS name_text"), 'id')
            ->where([['type','=', 0]])
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
            'emiPayments' => \App\PaymentPlan::select(\DB::raw("CONCAT(name, ' Booking: ', booking, '% - Allotment: ', allotment, ' EMI: ', emi, '%') AS name_text"), 'id')
            ->where([['type','=', 1]])
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
        ];
        return view('admin.projects.addprojects', $relations);
    }

    /**
     * Show the form for creating new Project.
     *
     * @return \Illuminate\Http\Response
     */

    public function project_create(Request $request)
    {
        $user = Auth::user();
            if($request->name){
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'description' => 'max:255',
                'rate' => 'required|numeric',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                Project::create([
                'name' => $request->name,
                'description' => $request->description,
                'rate' => $request->rate,
                'status' => ($request->status=='on')?1:0,
                ]);
            return Redirect::back()->with('message','Project added Successfully !');
            }
        }

    }

    public function project_update($id, Request $request)
    {
        $user = Auth::user();
            $relations = [
                'projects' => DB::table('projects')->orderby('created_at')->get(),
                'project' => DB::table('projects')->where('id', '=', $id)->first(),
                'fullPayments' => \App\PaymentPlan::select(\DB::raw("CONCAT(name, ' Booking/Allotment: ', booking, '% - Registry: ', emi, '%') AS name_text"), 'id')
                ->where([['type','=', 0]])
                ->get()
                ->pluck('name_text', 'id')->prepend('Please select', ''),
                'emiPayments' => \App\PaymentPlan::select(\DB::raw("CONCAT(name, ' Booking: ', booking, '% - Allotment: ', allotment, ' EMI: ', emi, '%') AS name_text"), 'id')
                ->where([['type','=', 1]])
                ->get()
                ->pluck('name_text', 'id')->prepend('Please select', ''),
            ];

            if($request->name){
                $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'description' => 'required|max:255',
                'rate' => 'required|numeric',
                'full_payment_plan_id' => 'required|numeric',
                'emi_payment_plan_id' => 'required|numeric',
                ]);

                if ($validator->fails()) {
                    return Redirect::back()
                                ->withErrors($validator)
                                ->withInput();
                }else{
                Project::where('id', '=', $id)->update([
                'name' => $request->name,
                'description' => $request->description,
                'rate' => $request->rate,
                'full_payment_plan_id' => $request->full_payment_plan_id,
                'emi_payment_plan_id' => $request->emi_payment_plan_id,
                'status' => ($request->status=='on')?1:0,
                ]);
                return Redirect::back()->with('message','Project updated Successfully !');
                }
            }

            return view('admin.projects.edit_project',  $relations);
    }
    
    public function paymentplan()
    {
        $relations = [
            'paymentPlans' => DB::table('payment_plans')->orderby('created_at')->get(),
        ];
        return view('admin.projects.add_payment_plan', $relations);
    }

    /**
     * Show the form for creating new Project.
     *
     * @return \Illuminate\Http\Response
     */

    public function paymentplan_create(Request $request)
    {
        $user = Auth::user();
            if($request->name){
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'payment_plan_type' => 'required|numeric',
                'booking' => 'required|numeric',
                'allotment' => 'required|numeric',
                'emi' => 'required|numeric',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                \App\PaymentPlan::create([
                'name' => $request->name,
                'type' => $request->payment_plan_type,
                'booking' => $request->booking,
                'allotment' => $request->allotment,
                'emi' => $request->emi,
                ]);
            return Redirect::back()->with('message','Payment Plan added Successfully !');
            }
        }

    }

    public function paymentplan_update($id, Request $request)
    {
        $relations = [
            'paymentPlans' => DB::table('payment_plans')->orderby('created_at')->get(),
            'paymentPlan' => DB::table('payment_plans')->where('id', '=', $id)->first(),
            'user' => Auth::user()
        ];
        
        if($request->name){
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'payment_plan_type' => 'required|numeric',
                'booking' => 'required|numeric',
                'allotment' => 'required|numeric',
                'emi' => 'required|numeric',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                \App\PaymentPlan::where('id', '=', $id)->update([
                'name' => $request->name,
                'type' => $request->payment_plan_type,
                'booking' => $request->booking,
                'allotment' => $request->allotment,
                'emi' => $request->emi,
                ]);
            return Redirect::back()->with('message','Payment Plan updated Successfully !');
            }
        }

        return view('admin.projects.edit_payment_plan', $relations);
    }

    public function sectors()
    {
        $relations = [
            'sectors' => DB::table('sectors')
            ->select('sectors.*', 'projects.name as projectName')
            ->join('projects', 'projects.id', '=', 'sectors.project_id')
            ->orderby('sectors.created_at')
            ->get(),
            
            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
        ];
        return view('admin.sectors.add_sectors', $relations);
    }

    /**
     * Show the form for creating new Project.
     *
     * @return \Illuminate\Http\Response
     */

    public function sector_create(Request $request)
    {
        $user = Auth::user();
            if($request->name){
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'project_id' => 'required|numeric',
                'area' => 'required|max:155',
                'dimension' => 'required|max:155',
                'plc' => 'required|max:155',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                \App\Sector::create([
                'name' => $request->name,
                'project_id' => $request->project_id,
                'area' => $request->area,
                'dimension' => $request->dimension,
                'plc' => $request->plc,
                ]);
            return Redirect::back()->with('message','sector added Successfully !');
            }
        }

    }

    public function sector_update($id, Request $request)
    {
        $user = Auth::user();
        $relations = [
            'sectors' => DB::table('sectors')
            ->select('sectors.*', 'projects.name as projectName')
            ->join('projects', 'projects.id', '=', 'sectors.project_id')
            ->orderby('sectors.created_at')
            ->get(),
             
            'sector' => DB::table('sectors')->where('id', '=', $id)->first(),
            
            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
        ];

            if($request->name){
                $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'project_id' => 'required|numeric',
                'area' => 'required|max:155',
                'dimension' => 'required|max:155',
                'plc' => 'required|max:155',
                ]);

                if ($validator->fails()) {
                    return Redirect::back()
                                ->withErrors($validator)
                                ->withInput();
                }else{
                \App\Sector::where('id', '=', $id)->update([
                'name' => $request->name,
                'project_id' => $request->project_id,
                'area' => $request->area,
                'dimension' => $request->dimension,
                'plc' => $request->plc,
                ]);
                return Redirect::back()->with('message','sector updated Successfully !');
                }
            }

            return view('admin.sectors.edit_sectors',  $relations);
    }
 
    public function blocks()
    {
        $relations = [
            'blocks' => DB::table('blocks')
            ->select('blocks.*', 'projects.name as projectName', 'sectors.name as sectorName')
            ->join('projects', 'projects.id', '=', 'blocks.project_id')
            ->join('sectors', 'sectors.id', '=', 'blocks.sector_id')
            ->orderby('blocks.created_at')
            ->get(),
            
            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
        ];
        return view('admin.blocks.add_blocks', $relations);
    }

    /**
     * Show the form for creating new Project.
     *
     * @return \Illuminate\Http\Response
     */

    public function block_create(Request $request)
    {
        $user = Auth::user();
            if($request->name){
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'project_id' => 'required|numeric',
                'sector_id' => 'required|numeric',
                'area' => 'required|max:155',
                'dimension' => 'required|max:155',
                'plc' => 'required|max:155',
                'plot_count' => 'required|numeric',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                $newBlock = \App\Block::create([
                'name' => $request->name,
                'project_id' => $request->project_id,
                'sector_id' => $request->sector_id,
                'area' => $request->area,
                'dimension' => $request->dimension,
                'plc' => $request->plc,
                'plot_count' => $request->plot_count,
                ]);
                $plotsData = [];
                for($i = 0; $i < $request->plot_count; $i++){
                    $plotData = [
                        'name'=> $request->name.'-'.$i,
                        'project_id' => $request->project_id,
                        'sector_id' => $request->sector_id,
                        'block_id' => $newBlock->id,
                        'area' => $request->area,
                        'dimension' => $request->dimension,
                        'plc' => $request->plc,
                    ];
                    array_push($plotsData, $plotData);
                }
                \App\Plot::insert($plotsData);
            return Redirect::back()->with('message','Block added Successfully !');
            }
        }

    }

    public function block_update($id, Request $request)
    {
        $user = Auth::user();
        $relations = [
            'blocks' => DB::table('blocks')
            ->select('blocks.*', 'projects.name as projectName', 'sectors.name as sectorName')
            ->join('projects', 'projects.id', '=', 'blocks.project_id')
            ->join('sectors', 'sectors.id', '=', 'blocks.sector_id')
            ->orderby('blocks.created_at')
            ->get(),

            'block' => DB::table('blocks')
            ->select('blocks.*', 'projects.name as projectName', 'sectors.name as sectorName')
            ->join('projects', 'projects.id', '=', 'blocks.project_id')
            ->join('sectors', 'sectors.id', '=', 'blocks.sector_id')
            ->where('blocks.id', '=', $id)->first(),

            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),

            'sectors' => \App\Sector::select(\DB::raw("CONCAT(name, '-',area,'-',dimension,'-',plc) AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
        ];

            if($request->name){
                $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'project_id' => 'required|numeric',
                'sector_id' => 'required|numeric',
                'area' => 'required|max:155',
                'dimension' => 'required|max:155',
                'plc' => 'required|max:155',
                ]);

                if ($validator->fails()) {
                    return Redirect::back()
                                ->withErrors($validator)
                                ->withInput();
                }else{
                \App\Block::where('id', '=', $id)->update([
                'name' => $request->name,
                'project_id' => $request->project_id,
                'sector_id' => $request->sector_id,
                'area' => $request->area,
                'dimension' => $request->dimension,
                'plc' => $request->plc,
                ]);
                return Redirect::back()->with('message','Block updated Successfully !');
                }
            }

            return view('admin.blocks.edit_blocks',  $relations);
    }
    

    public function plots()
    {
        $relations = [
            'plots' => DB::table('plots')
            ->select('plots.*', 'projects.name as projectName', 'sectors.name as sectorName', 'blocks.name as blockName')
            ->join('projects', 'projects.id', '=', 'plots.project_id')
            ->join('sectors', 'sectors.id', '=', 'plots.sector_id')
            ->join('blocks', 'blocks.id', '=', 'plots.block_id')
            ->orderby('plots.created_at')
            ->get(),
            
            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
        ];
        return view('admin.plots.add_plots', $relations);
    }

    /**
     * Show the form for creating new Project.
     *
     * @return \Illuminate\Http\Response
     */

    public function plot_create(Request $request)
    {
        $user = Auth::user();
            if($request->name){
                $validator = Validator::make($request->all(), [
                    'name' => 'required|max:155',
                    'project_id' => 'required|numeric',
                    'sector_id' => 'required|numeric',
                    'block_id' => 'required|numeric',
                    'area' => 'required|max:155',
                    'dimension' => 'required|max:155',
                    'plc' => 'required|max:155',
                ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                $newPlot = \App\Plot::create([
                'name' => $request->name,
                'project_id' => $request->project_id,
                'sector_id' => $request->sector_id,
                'block_id' => $request->block_id,
                'area' => $request->area,
                'dimension' => $request->dimension,
                'plc' => $request->plc,
                ]);
            return Redirect::back()->with('message','Plot added Successfully !');
            }
        }

    }

    public function plot_update($id, Request $request)
    {
        $user = Auth::user();
        $relations = [
            'plots' => DB::table('plots')
            ->select('plots.*', 'projects.name as projectName', 'sectors.name as sectorName', 'blocks.name as blockName')
            ->join('projects', 'projects.id', '=', 'plots.project_id')
            ->join('sectors', 'sectors.id', '=', 'plots.sector_id')
            ->join('blocks', 'blocks.id', '=', 'plots.block_id')
            ->orderby('plots.created_at')
            ->get(),

            'plot' => DB::table('plots')
            ->select('plots.*', 'projects.name as projectName', 'sectors.name as sectorName', 'blocks.name as blockName')
            ->join('projects', 'projects.id', '=', 'plots.project_id')
            ->join('sectors', 'sectors.id', '=', 'plots.sector_id')
            ->join('blocks', 'blocks.id', '=', 'plots.block_id')
            ->where('plots.id', '=', $id)->first(),

            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),

            'sectors' => \App\Sector::select(\DB::raw("CONCAT(name, '-',area,'-',dimension,'-',plc) AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
            
            'blocks' => \App\Block::select(\DB::raw("CONCAT(name, '-',area,'-',dimension,'-',plc) AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
            ];

            if($request->name){
                $validator = Validator::make($request->all(), [
                'name' => 'required|max:155',
                'project_id' => 'required|numeric',
                'sector_id' => 'required|numeric',
                'block_id' => 'required|numeric',
                'area' => 'required|max:155',
                'dimension' => 'required|max:155',
                'plc' => 'required|max:155',
                ]);

                if ($validator->fails()) {
                    return Redirect::back()
                                ->withErrors($validator)
                                ->withInput();
                }else{
                \App\Plot::where('id', '=', $id)->update([
                'name' => $request->name,
                'project_id' => $request->project_id,
                'sector_id' => $request->sector_id,
                'block_id' => $request->block_id,
                'area' => $request->area,
                'dimension' => $request->dimension,
                'plc' => $request->plc,
                ]);
                return Redirect::back()->with('message','Plot updated Successfully !');
                }
            }

            return view('admin.plots.edit_plots',  $relations);
    }


    public function selectAjax(Request $request)
    {
        if($request->ajax()){
            if($request->project_id){
                $resultData = \App\Sector::select(\DB::raw("CONCAT(name) AS name_text"), 'id')
                    ->where('project_id', '=', $request->project_id)
                    ->get()
                    ->pluck('name_text', 'id');
            }elseif($request->sector_id){
                $resultData = \App\Block::select(\DB::raw("CONCAT(name) AS name_text"), 'id')
                    ->where('sector_id', '=', $request->sector_id)
                    ->get()
                    ->pluck('name_text', 'id');
            }elseif($request->block_id){
                $resultData = \App\Plot::select(\DB::raw("CONCAT(plots.name, '-',area,'-',dimension,'-',plcs.name, ' ', plcs.amount, ' Extra') AS name_text"), 'plots.id')
                    ->where('plots.block_id', '=', $request->block_id)
                    ->join('plcs', 'plcs.id', '=', 'plots.plc');
                
                if(isset($request->filter) && $request->filter=='available'){
                    $resultData = $resultData->where([['status', '=', $request->filter], ['admin_status', '=', NULL]]);
                }
                $resultData = $resultData->get()->pluck('name_text', 'id');
            }
            
            $data = view('partials.ajax-select',compact('resultData'))->render();
            return response()->json(['options'=>$data]);
        }
    }
    public function plotStatus(Request $request){
        if($request->block_id){
            DB::table('plots')->where([
                ['admin_status_date', '<', Carbon::now()],
                ['admin_status', '!=', 'registered'],
            ])->update(['admin_status'=>NULL]);
            $resultData = \App\Plot::select('plots.*', 'plcs.name as plcName', 'plcs.amount', 'plcs.type')
                    ->where('plots.block_id', '=', $request->block_id)
                    ->join('plcs', 'plcs.id', '=', 'plots.plc')->get();
            $output = "";

            $plot_status = NULL;
            foreach($resultData as $plot){
                $plot_status = $plot->admin_status;
                if($plot->status=='available' && $plot->admin_status==NULL){
                    $color= 'green';
                    $plot_status = 'available';
                }elseif($plot->status=='onhold' || $plot->admin_status=='onhold'){
                    $color= 'grey';
                    $plot_status = 'onhold';
                }elseif($plot->status=='registered' || $plot->admin_status=='registered'){
                    $color= 'red';
                    $plot_status = 'registered';
                }elseif($plot->status=='booked'){
                    $color= 'orange';
                    $plot_status = 'Booked';
                }elseif($plot->status=='alloted'){
                    $color= 'pink';
                    $plot_status = 'Alloted';
                }
                
                $output .= '<div class="col-1 col-lg-1 col-sm-2 tip" data-tip="tip-'.$plot->id.'"'
                            .'>'
                            .'<div style="width:100%; height: 70px; background-color:'.$color.'; color:#fff; margin-left:5px; margin-bottom:5px; padding:10px;">'
                            .$plot->name
                            .'</div>'
                            .'<div id="tip-'.$plot->id.'" class="tip-content hidden">'
                            .'<table class="tip-content-t">'
                            .'  <tr><td>Name </td><td> '.$plot->name.'</td></tr>'
                            .'  <tr><td>Area </td><td> '.$plot->area.'</td></tr>'
                            .'  <tr><td>Dimension </td><td> '.$plot->dimension.'</td></tr>'
                            .'  <tr><td>Status </td><td> '.ucfirst($plot_status).'</td></tr>'
                            .'  <tr><td>PLC </td><td> '.ucfirst($plot->plcName).'</td></tr>'
                            .'</table>'
                            .'</div>'
                            .'</div>'
                            ;
            }
            if($output==''){$output='No plot found.';}

            echo $output;
        }
    }
    
    public function dataAjax(Request $request)
    {
        if($request->ajax()){
            if($request->project_id){
                $resultData = \App\Project::select('id', 'name', 'area', 'dimension', 'plc')
                    ->where('id', '=', $request->project_id)
                    ->first();
            }elseif($request->sector_id){
                $resultData = \App\Sector::select('id', 'name', 'area', 'dimension', 'plc')
                    ->where('id', '=', $request->sector_id)
                    ->first();
            }elseif($request->block_id){
                $resultData = \App\Block::select('id', 'name', 'area', 'dimension', 'plc')
                    ->where('id', '=', $request->block_id)
                    ->first();
            }elseif($request->plot_id){
                $resultData = \App\Plot::select('id', 'name', 'area', 'dimension', 'plc')
                    ->where('id', '=', $request->plot_id)
                    ->first();
            }
            return response()->json($resultData);
        }
    }
 
}
