<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helpers\DBFunctions;
use App\Models\Sales;
use App\Models\SalesComm;
use App\Models\Month;
use App\Models\Developer;
use App\Models\Team;
use App\Models\Receivables;
use App\Models\Project;
use App\Models\Client;
use App\Models\Agent;
use App\Models\Settings;

use App\Helpers\Numerics;
use App\Models\UnitManager;
use Carbon\Carbon;
use Auth;
use DB;

class SalesController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index() {

        $role_      = Auth::user()->role_id;
        $user_id    = Auth::user()->id;

        $month = date('m');
        $yy = date('Y');
        //$month = '06';
        $cmonth = date('m');

        $months = DB::select("select * from vw_months");
        $years  = DB::select("select * from vw_year");

        if ($role_ == 4) {
            $user_agent = DB::select('select * from vw_user_agent' . ' where user_id = ' . $user_id);
            $uagent = $user_agent[0]->agent_id;
            //$sales = Sales::with(['agent', 'project', 'client'])->where('agent_id','=',$uagent)->whereNull('deleted_at')->orderBy('id', 'DESC')->get();
            //$sales = DB::select("select * from vw_sales_list2 where agent_id='".$uagent."' and mmonth='".$month."' and yyear='".$yy."'");
            $sales = DB::select("select * from vw_sales_list2 where agent_id='".$uagent."'");
            return view('sales.index', compact('sales', 'months', 'years', 'cmonth'));
        } else {
            //$sales = Sales::with(['agent', 'project', 'client'])->whereNull('deleted_at')->orderBy('id', 'DESC')->get();
            //dd($sales);
            //$sales = DB::select("select * from vw_sales_list2 where mmonth='".$month."' and yyear='".$yy."'");
            $sales = DB::select("select * from vw_sales_list2");
            return view('sales.index', compact('sales', 'months', 'years', 'cmonth'));
        }

    }

    public function month($month, $year) {
        $role_      = Auth::user()->role_id;
        $user_id    = Auth::user()->id;

        $months = DB::select("select * from vw_months");
        $years  = DB::select("select * from vw_year");
        $cmonth = date('m');

        if ($role_ == 4) {
            $user_agent = DB::select('select * from vw_user_agent' . ' where user_id = ' . $user_id);
            $uagent = $user_agent[0]->agent_id;
            $sales = DB::select("select * from vw_sales_list2 where agent_id='".$uagent."' and mmonth='".$month."' and yyear='".$year."'");
            return view('sales.index', compact('sales', 'months', 'years', 'cmonth'));
        } else {
            $sales = DB::select("select * from vw_sales_list2 where mmonth='".$month."' and yyear='".$year."'");
            return view('sales.index', compact('sales', 'months', 'years','cmonth'));
        }
    }

    public function getNew() {
        //echo 'New';
        $agents = Agent::whereNull('deleted_at')->orderBy('fullname', 'ASC')->get(); //where('position', '=', 'Sales Executive')->get();
        $devs = Developer::all();
        $projects = Project::all();
        //$ums = Agent::where('position', '=', 'Unit Manager')->orderBy('fullname', 'ASC')->get();
        $ums  = UnitManager::orderBy('fullname', 'ASC')->get();

        $setts = Settings::where('id', '=', 3)->get();
        $def_rate = $setts[0]->values;

        $enum = new DBFunctions();
        $opts = $enum->get_enum_values('sales','finance_option');
        $status = $enum->get_enum_values('sales','status');

        $share = DB::select('SELECT * FROM sharing_table');
        //dd($share);

        $reservation_date = '02/21/2020';
        $date = str_replace('/', '-', $reservation_date );
        $newDate = date("Y-m-d", strtotime($date));

        /*$newDate = Carbon::createFromFormat('d-m-Y',$reservation_date->format('Y-m-d'));
        dd($newDate);*/

        return view ('sales.new', compact('agents', 'projects', 'opts', 'status', 'devs', 'def_rate', 'ums', 'share'));
    }

    public function editSales($id){

        $sale       = Sales::with(['agent', 'developer', 'project', 'client'])->where('id', $id)->first();
        $sale_comm  = SalesComm::where('sales_id', $id)->first();
        $team       = Team::orderBy('name', 'ASC')->get();
        $enum       = new DBFunctions();
        $devs       = Developer::all();
        $projects   = Project::all();
        $pst        = $enum->get_enum_values('agents','position');
        $opts       = $enum->get_enum_values('sales','finance_option');
        $share      = DB::select('SELECT * FROM sharing_table');
        $agents     = Agent::whereNull('deleted_at')->get(); //where('position', '=', 'Sales Executive')->get();
        //$ums        = Agent::where('position', '=', 'Unit Manager')->get();
        $ums        = UnitManager::orderBy('fullname', 'ASC')->get();

        $enum = new DBFunctions();
        $status = $enum->get_enum_values('sales','sale_status');

        return view ('sales.edit', compact('sale', 'sale_comm', 'agents', 'projects','ums', 'pst', 'team', 'devs', 'opts', 'share', 'status'));
    }

    public function postNew(Request $request){

        //dd($request->all());

        try {

            DB::beginTransaction();

            $validate = [
                'client_name'   => 'required',
                'developer_id'  => 'required',
                'project_id'    => 'required',
            ];

            $validator = \Validator::make($request->all(), $validate);

            //dd($validator);
            if ($validator->fails()) {
                //dd( $validator );
                return back()
                    ->withErrors($validator)
                    ->withInput();
            }

            $cl = new Client();
            $cl->client_name    = strtoupper($request['client_name']);
            $cl->email_ad       = $request['client_email'];
            $cl->facebook       = $request['client_fb'];
            $cl->contact_no     = $request['client_number'];
            $cl->save();

            $latestID = $cl->id;
            $userid = Auth::user()->id;

            //date_default_timezone_set("Asia/Manila");
            //$todayy = date("Y-m-d");
            //$rsvn_date = Carbon::createFromFormat('d-m-Y',$request->reservation_date)->format('Y-m-d');
            $r_date = $request['reservation_date'];
            $rsvn_date = date("Y-m-d", strtotime($r_date));

            /*$tsp = $request['total_selling_price'];

            //vat
            $vat_ = Settings::where('id', '=', 1)->get();
            $vat = $vat_[0]->percentage;

            //processing fee
            $pr_fee = Settings::where('id', '=', 2)->get();
            $p_fee = $pr_fee[0]->values;

            $net_selling = ($tsp * $vat) - $p_fee;*/

            $d = new Numerics();
            $tsp = $d->toFloat($request['total_selling_price']);
            $nsp = $d->toFloat($request['net_selling_price']);
            $eqt = $d->toFloat($request['equity']);
            $lna = $d->toFloat($request['loanable_amount']);

            $sale = new Sales();

            $data = [
                'reservation_date'  => $rsvn_date,
                'client_id'         => $latestID,
                'property_type_id'  => 4,
                'developer_id'      => $request['developer_id'],
                'project_id'        => $request['project_id'],
                'address'           => strtoupper($request['address']),
                'house_model'       => strtoupper($request['house_model']),
                'blk'               => $request['blk'],
                'lot'               => $request['lot'],
                'lot_area'          => $request['lot_area'],
                'floor_area'        => $request['floor_area'],
                'finance_option'    => $request['finance_option'],
                'total_selling_price' => $tsp,
                'net_selling_price' => $nsp,
                'equity'            => $eqt,
                'loanable_amount'   => $lna,
                'sale_status'       => 'Active',
                'agent_id'          => $request['agent_id'],
                'unit_manager_id'   => $request['umanager_id'],
                'user_id'           => $userid,
            ];

            $sale->fill($data);
            $sale->save();

            $s_id = $sale->id;

            if ($sale) {

                $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $trxn_code = $this->generate_string_online($permitted_chars,20);
                //Receivables
                $rcvd = new Receivables();

                $rc = [
                    'sales_id'          => $s_id,
                    'rcvd_code'         => $trxn_code,
                    'num_month'         => 1,
                    'contract_amount'   => $nsp,
                    'remarks'           => '-',
                    'user_id'           => $userid
                ];

                $rcvd->fill($rc);
                $rcvd->save();

                $agr = $d->toFloat($request['agent_com_rate']);
                $ucr = $d->toFloat($request['um_com_rate']);
                $bcr = $d->toFloat($request['broker_com_rate']);
                $rcr = $d->toFloat($request['ref_com_rate']);

                $s_com = new SalesComm();

                $dta = [
                    'sales_id'          => $s_id,
                    'agent_pcg_rate'    => $request['agent_pcg_rate'],
                    'agent_com_rate'    => $agr,
                    'um_pcg_rate'       => $request['um_pcg_rate'],
                    'um_com_rate'       => $ucr,
                    'broker_pcg_rate'   => $request['broker_pcg_rate'],
                    'broker_com_rate'   => $bcr,
                    'ref_pcg_rate'      => $request['ref_pcg_rate'],
                    'ref_com_rate'      => $rcr,
                ];

                $s_com->fill($dta);
                $s_com->save();

            }

            DB::commit();

            return redirect()->route('sales')->with('info', 'The new sales entry have been created.');
        } catch (\Exception $e) {
            // rollback db transactions
            DB::rollBack();
            //return redirect()->route('sales.new')->with('info', 'Oppsss something went wrong..');
            return redirect()->route('sales.new')->with('info', $e->getMessage());
        }

    }


    public function updateSales(Request $request){

        //dd($request->all());
        $id         = $request['id_'];
        $cust_id    = $request['client_id'];

        try {

            DB::beginTransaction();

            $validate = [
                'client_name'   => 'required',
                'developer_id'  => 'required',
                'project_id'    => 'required',
            ];

            $validator = \Validator::make($request->all(), $validate);

            //dd($validator);
            if ($validator->fails()) {
                //dd( $validator );
                return back()
                    ->withErrors($validator)
                    ->withInput();
            }

            $cl = Client::where('id', $cust_id)->first();
            $cl->client_name    = strtoupper($request['client_name']);
            $cl->email_ad       = $request['client_email'];
            $cl->facebook       = $request['client_fb'];
            $cl->contact_no     = $request['client_number'];
            $cl->update();

            //$latestID = $cl->id;
            $userid = Auth::user()->id;

            //date_default_timezone_set("Asia/Manila");
            //$todayy = date("Y-m-d");
            //$rsvn_date = Carbon::createFromFormat('d-m-Y',$request->reservation_date)->format('Y-m-d');
            $r_date = $request['reservation_date'];
            $rsvn_date = date("Y-m-d", strtotime($r_date));

            /*$tsp = $request['total_selling_price'];

            //vat
            $vat_ = Settings::where('id', '=', 1)->get();
            $vat = $vat_[0]->percentage;

            //processing fee
            $pr_fee = Settings::where('id', '=', 2)->get();
            $p_fee = $pr_fee[0]->values;

            $net_selling = ($tsp * $vat) - $p_fee;*/

            $d = new Numerics();
            $tsp = $d->toFloat($request['total_selling_price']);
            $nsp = $d->toFloat($request['net_selling_price']);
            $eqt = $d->toFloat($request['equity']);
            $lna = $d->toFloat($request['loanable_amount']);

            $sale   = Sales::where('id', $id)->first();

            $data = [
                'reservation_date'  => $rsvn_date,
                //'client_id'         => $latestID,
                'property_type_id'  => 4,
                'developer_id'      => $request['developer_id'],
                'project_id'        => $request['project_id'],
                'address'           => strtoupper($request['address']),
                'house_model'       => strtoupper($request['house_model']),
                'blk'               => $request['blk'],
                'lot'               => $request['lot'],
                'lot_area'          => $request['lot_area'],
                'floor_area'        => $request['floor_area'],
                'finance_option'    => $request['finance_option'],
                'total_selling_price' => $tsp,
                'net_selling_price' => $nsp,
                'equity'            => $eqt,
                'loanable_amount'   => $lna,
                'sale_status'       => $request['status_id'],
                'agent_id'          => $request['agent_id'],
                'unit_manager_id'   => $request['umanager_id'],
                'user_id'           => $userid,
            ];

            $sale->fill($data);
            $sale->update();

            if ($sale) {

                $s_com  = SalesComm::where('sales_id', $id)->first();

                $agr = $d->toFloat($request['agent_com_rate']);
                $ucr = $d->toFloat($request['um_com_rate']);
                $bcr = $d->toFloat($request['broker_com_rate']);
                $rcr = $d->toFloat($request['ref_com_rate']);

                $dta = [
                    //'sales_id'          => $s_id,
                    'agent_pcg_rate'    => $request['agent_pcg_rate'],
                    'agent_com_rate'    => $agr,
                    'um_pcg_rate'       => $request['um_pcg_rate'],
                    'um_com_rate'       => $ucr,
                    'broker_pcg_rate'   => $request['broker_pcg_rate'],
                    'broker_com_rate'   => $bcr,
                    'ref_pcg_rate'      => $request['ref_pcg_rate'],
                    'ref_com_rate'      => $rcr,
                ];

                $s_com->fill($dta);
                $s_com->save();
            }

            Receivables::where('sales_id', '=', $id)
                ->update(array(
                    'contract_amount' => $nsp,
                    'user_id'         => $userid
                )
            );

            DB::commit();

            return redirect()->route('sales')->with('info', 'Sales entry was successfully updated.');
        } catch (\Exception $e) {
            // rollback db transactions
            DB::rollBack();
            //return redirect()->route('sales.new')->with('info', 'Oppsss something went wrong..');
            return redirect()->route('sales.new')->with('info', $e->getMessage());
        }

    }

    public function getDefaultValues() {

        $vat_ = Settings::where('id', '=', 1)->get();
        $vat = $vat_[0]->percentage;

        //processing fee
        $pr_fee = Settings::where('id', '=', 2)->get();
        $p_fee = $pr_fee[0]->values;

        return response()->json(["vat"=>$vat,"proc_fee"=>$p_fee ]);

    }

    public function DeleteSales(Request $request){
        $id     = $request['id'];
        $sale   = Sales::where('id', $id)->first();
        $sale->delete();

        return redirect()->back()->with('info', "The selected Sales have been deleted.");
    }

    public function chkClientName(Request $request) {

        $client_name = $request->client_name;
        $client  = Client::where('client_name', '=', $client_name)->get();
        //return response()->json(["data"=>$agent]);
        if (isset($client_name)) {

            $client  = Client::where('client_name', '=', $client_name)->first();

            if ($client) {
                return response()->json(["chk"=>true]);
            } else {
                return response()->json(["chk"=>false]);
            }
            //return response()->json(["data"=>$agent]);
        } else {
            return response('No data');
        }
    }

    public function generate_string_online($input, $strength = 20){
        $input_length = strlen($input);
        $random_string = '';

        for ($i = 0; $i < $strength; $i++) {
            $random_character = $input[mt_rand(0, $input_length - 1)];
            $random_string .= $random_character;
        }

        /*$validate = DB::select("select * from payments where trxn_code='$random_string'");
        // dd($validate);
        if ($validate) {
            $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $this->generate_string($permitted_chars, 12);
        } else {
            return $random_string;
        }*/

        return $random_string;
    }

}

