<?php

namespace App\Http\Controllers;

use App\Salary;
use App\User;
use App\Post;
use App\DailyResult;
use App\ChamCong;
use App\PhongBan;
use App\Product;
use App\Maychamcong;
use App\PhieuPhat;
use App\UserKpi;
use App\CskhSetup;
use App\WorkingTime;
use App\Transaction;
use App\DkLichLv;
use App\DeNghiXuatHang;
use App\TransactionSellLine;
use App\TransactionPayment;
use App\WeeklyPoint;
use App\UsersTransfer;
use App\UserLevel;
use App\ToGroup;
use Carbon\Carbon;
use App\Utils\TransactionUtil;
use DB;
use App\Utils\SalaryUtil;
use Illuminate\Http\Request;

class SalaryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    protected $salaryUtil;
    protected $transactionUtil;

    public function __construct(SalaryUtil $salaryUtil,TransactionUtil $transactionUtil)
    {
        $this->salaryUtil = $salaryUtil;
        $this->transactionUtil = $transactionUtil;
    }


    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function createCongLuongNvkt()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')->where('users.user_type',2)->where('pb.code','PKT')->select('users.*')->where('users.status','active')->whereNULL('users.deleted_at')->get();
        return view('salary.create_cong_luong_nvkt')->with(compact('users','business_id'));
    }
    public function createCongLuongNvkd()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')->where('users.user_type',3)->where('pb.code','PKD')->select('users.*')->where('users.status','active')->whereNULL('users.deleted_at')->get();
        return view('salary.create_cong_luong_nvkd')->with(compact('users','business_id'));
    }

    public function create()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')->where('users.user_type',2)->where('pb.code','PKT')->select('users.*')->where('users.status','active')->whereNULL('users.deleted_at')->get();
        return view('salary.create')->with(compact('users','business_id'));
    }
    public function createKd()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')->where('pb.code','PKD')->select('users.*')->where('users.status','active')->whereNULL('users.deleted_at')->get();
        return view('salary.create_kd')->with(compact('users','business_id'));
    }
    public function createMkt()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')->where('pb.code','PMKT')->select('users.*')->where('users.status','active')->whereNULL('users.deleted_at')->get();
        return view('salary.create_mkt')->with(compact('users','business_id'));
    }

    public function createQuanLy()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }

        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')->where('users.id','<>',1)->where('users.user_type','<>',2)->where('users.status','active')->whereNULL('users.deleted_at')->select('users.*')->get();
        return view('salary.create_quan_ly')->with(compact('users','business_id'));
    }

    public function editLuongQuanLy(Request $request,$id)
    {   
        if (!auth()->user()->can('salary.edit') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $salary = Salary::findOrFail($id);
        return view('salary.edit_quan_ly')->with(compact('salary','business_id'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    
    public function createLuongTn()
    {   
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');
        $users = User::leftJoin('phong_bans as pb','users.phong_ban','=','pb.id')
                ->where(function ($query) {
                            $query->where('pb.code','PKD')->orWhere('pb.code','PKT')
                        ;})
                ->where(function ($query) {
                            $query->where('users.phan_quyen','tt')->orWhere('users.phan_quyen','tp')
                        ;})
                ->where('users.status','active')->whereNULL('users.deleted_at')->select('users.*')->get();
        return view('salary.create_luong_tn')->with(compact('users','business_id'));
    }
     public function storeLuongTn(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        $luong_trach_nhiem = 0;
        $business_id = request()->session()->get('user.business_id');
            foreach ($request->input('checkbox') as $key) {
                $user_id = $request->input('user_id')[$key];
                $user = User::findOrFail($user_id);

                if ((!empty($user->phong_ban))&&(!empty($user->bo_phan))&&(!empty($user->thoi_gian_lv))&&(!empty($user->salary_status))&&(!empty($user->to_group))&&(!empty($user->custom_field_2))) {
                    $start = $request->input('tu_ngay')[$key];
                    $ends = $request->input('den_ngay')[$key];
                    $phong_ban = PhongBan::findOrFail($user->phong_ban);

                    /*$dieu_hanh_to = WeeklyPoint::whereBetween('date',[$start,$ends])->where('user_id',$user_id)->avg('dieu_hanh_to');
                    $dao_tao_nv = WeeklyPoint::whereBetween('date',[$start,$ends])->where('user_id',$user_id)->avg('dao_tao_nv');
                    $hoan_thanh_cv = WeeklyPoint::whereBetween('date',[$start,$ends])->where('user_id',$user_id)->avg('hoan_thanh_cv');
                    $quan_ly_nv = WeeklyPoint::whereBetween('date',[$start,$ends])->where('user_id',$user_id)->avg('quan_ly_nv');*/
                    $dieu_hanh_to = 5;
                    $dao_tao_nv = 5;
                    $hoan_thanh_cv = 5;
                    $quan_ly_nv = 5;
                    if ($request->input('phan_quyen')[$key] == 'tt') {
                        $he_so_TB = ($dieu_hanh_to+$dao_tao_nv+$hoan_thanh_cv+$quan_ly_nv)/4;
                        if($phong_ban->code == "PKD"){
                            $luong_trach_nhiem = 1*$this->salaryUtil->LuongTrachNhiemPKD($user,$start,$ends,$user->user_type,$request->input('phan_quyen')[$key],$he_so_TB,$request->input('is_user_active')[$key]);
                        } else {
                            $luong_trach_nhiem = 1*$this->salaryUtil->LuongTrachNhiemSingle($user,$start,$ends,$user->user_type,$request->input('phan_quyen')[$key],$he_so_TB,$request->input('is_user_active')[$key]);
                        }
                    } else {
                        $he_so_TB = $request->input('he_so_TB')[$key];
                        if($phong_ban->code == "PKD"){
                            $luong_trach_nhiem = 1*$this->salaryUtil->LuongTrachNhiemPKD($user,$start,$ends,$user->user_type,$request->input('phan_quyen')[$key],$he_so_TB,$request->input('is_user_active')[$key]);
                        } else {
                            $luong_trach_nhiem = 1*$this->salaryUtil->LuongTrachNhiemSingle($user,$start,$ends,$user->user_type,$request->input('phan_quyen')[$key],$he_so_TB,$request->input('is_user_active')[$key]);
                        }
                    }
                    if ($request->input('luong_tn')[$key] > 0) {
                        $luong_trach_nhiem = $request->input('luong_tn')[$key];
                    }
                    
                    $luongs = Salary::where('user_id', $user_id)->first();
                    $luongs->luong_tn = $luong_trach_nhiem;
                    $luongs->save();
                }      
            }
        return redirect()->back();      
    }

    public function storeCongLuongNvkt(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        
        $business_id = request()->session()->get('user.business_id');
        $salary_check = Salary::groupBy('created_at')->count('id'); 
            foreach ($request->input('checkbox') as $key) {
                $user_id = $request->input('user_id')[$key];
                $user = User::findOrFail($user_id);
                $to_group = ToGroup::findOrFail($user->to_group);
                
                if ((!empty($user->phong_ban))&&(!empty($user->bo_phan))&&(!empty($user->thoi_gian_lv))&&(!empty($user->salary_status))&&(!empty($user->to_group))&&(!empty($user->custom_field_2))) {
                    $start = $request->input('tu_ngay')[$key];
                    $ends = $request->input('den_ngay')[$key];
                    $date = Carbon::parse($request->input('den_ngay')[$key])->format('d');
                    $year = Carbon::parse($request->input('den_ngay')[$key])->format('Y');
                    $month = Carbon::parse($request->input('den_ngay')[$key])->format('m');
                    
                    $ends2 = Carbon::create($year, $month, $date, 23, 59, 59);
                    $daily_results = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends]);
                    $ghi_chu = $request->input('ghi_chu')[$key];
                    $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends2])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                    $cong_no = $request->input('cong_no')[$key]+$tien_mua_sp_cty;
                    $tam_ung = $request->input('tam_ung')[$key];
                    $cty_giu = $request->input('cty_giu')[$key];
                    $ngay_cong = $daily_results->sum('so_cong');
                    $thuong = 0;
                    $phu_cap = $request->input('phu_cap')[$key];

                    
                    $phat = $daily_results->sum('phat')+PhieuPhat::whereNull('transaction_id')->where('user_id',$user_id)->whereBetween('ngay_phat',[$start,$ends])->sum('tien_phat') + PhieuPhat::where('phieu_phats.user_id',$user_id)->leftjoin('transactions as t1','phieu_phats.transaction_id','t1.id')->whereBetween('t1.created_at',[$start,$ends2])->sum('tien_phat');

                    $daily_first = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends])->first();
                    if (!empty($daily_first->bac_luong)) {
                      $userlevel = UserLevel::where('loai_nv',$daily_first->bac_luong)->first();
                    }
                    
                    if (!empty($userlevel)) {
                      $luong_cb = $userlevel->luong_cb;
                    } else {
                      $luong_cb = 0;
                    }
                    if ($to_group->group_code == 'TKTBH') {
                      $so_don_ps = $daily_results->sum('don_ps')+$daily_results->sum('ko_tinh_don_ps')+$daily_results->sum('don_ban_may');
                    } else {
                      $so_don_ps = $daily_results->sum('don_ps');
                    }
                    
                    $so_don_yc = $daily_results->sum('so_don_yc');
                    $so_don_vs = $daily_results->sum('don_vs');
                    // doanh so 
                    $ds_them = $daily_results->sum('don_them');
                    $doanh_so = $daily_results->sum('doanh_so');
                    //end doanh so  
                    $chiet_khau = $daily_results->sum('chiet_khau');
                    //
                    $salary = Salary::where('user_id' , $user_id)->where('thang' , $check)->first();
                    $luong_trach_nhiem = $this->salaryUtil->LuongTrachNhiem($user,$start,$ends,2);

                    $tong_luong = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['tong_luong'];
                    $kpi_gia_tri_dh = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_gia_tri_dh'];
                    $kpi_doanh_so = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_doanh_so'];
                    $kpi_so_don = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_so_don'];
                    $kpi_ti_le_vs = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_ti_le_vs'];
                    $luong_cb_trong_thang = $daily_results->sum('luong_cb');
                    //
                    $check = 'nvkt';
                    
                    $salary->den_ngay = $ends;
                    $salary->cong_no += $cong_no;
                    $salary->tam_ung += $tam_ung;
                    $salary->cty_giu += $cty_giu;
                    $salary->doanh_so += $doanh_so;
                    $salary->so_don_vs += $so_don_vs;
                    $salary->don_them += $ds_them;
                    $salary->phu_cap += $phu_cap;
                    $salary->kpi_gia_tri_dh += $kpi_gia_tri_dh;//
                    $salary->kpi_doanh_so += $kpi_doanh_so;//
                    $salary->kpi_so_don += $kpi_so_don;//
                    $salary->kpi_ti_le_vs += $kpi_ti_le_vs;//
                    $salary->so_don_ps += $so_don_ps;
                    $salary->so_don_yc += $so_don_yc;
                    $salary->chiet_khau += $chiet_khau;
                    $salary->ngay_cong += $ngay_cong;
                    $salary->luong_cb_trong_thang += $luong_cb_trong_thang;
                    $salary->luong_tn += $luong_trach_nhiem;
                    $salary->tong_luong += $tong_luong;
                    $salary->thuong_nong += $thuong;
                    $salary->phat += $phat;
                    $salary->save();
                    
                }      
            }
        return redirect()->back();      
    }

    public function storeCongLuongNvkd(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        
        $business_id = request()->session()->get('user.business_id');
        $salary_check = Salary::groupBy('created_at')->count('id'); 
        foreach ($request->input('checkbox') as $key) {
            //
            $user_id = $request->input('user_id')[$key];
            $user = User::findOrFail($user_id);  
            
           
            
            if ((!empty($user->phong_ban))&&(!empty($user->bo_phan))&&(!empty($user->thoi_gian_lv))&&(!empty($user->salary_status))&&(!empty($user->to_group))&&(!empty($user->custom_field_2))) {
                $start = $request->input('tu_ngay')[$key];
                $ends = $request->input('den_ngay')[$key];
                $daily_results = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends]);
                $ngay_cong = $daily_results->sum('so_cong');
                if ($user_id <> 132) {
                    $thuong = 0;
                    $phat = $daily_results->sum('phat')+PhieuPhat::where('user_id',$user_id)->whereBetween('ngay_phat', [$start,$ends])->sum('tien_phat');
                    $phu_cap = $request->input('phu_cap')[$key];
                    $so_don_ps = $daily_results->sum('don_ps')+$daily_results->sum('don_ban_may')-$daily_results->sum('don_bao_hanh');
                    $so_don_vs = $daily_results->sum('don_vs');
                    $doanh_so = $daily_results->sum('doanh_so')+$daily_results->sum('ds_ban_may');
                
                    //
                    $so_don_yc = $daily_results->sum('so_don_yc');
                    $doanh_so_yc = $daily_results->sum('doanh_so_yc');

                    $luong_trach_nhiem = $this->salaryUtil->LuongTrachNhiem($user,$start,$ends,3);
                    $tong_luong = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['luong'];
                    $kpi_gia_tri_dh = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['kpi_gia_tri_dh'];
                    $kpi_doanh_so = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['kpi_doanh_so'];
                    $kpi_so_don = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['kpi_so_don'];
                    $kpi_ti_le_vs = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['kpi_ti_le_vs'];
                    $vuot_ds = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['vuot_ds'];
                    $daily_first = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends])->first();
                    if (!empty($daily_first->bac_luong)) {
                      $userlevel = UserLevel::where('loai_nv',$daily_first->bac_luong)->first();
                    }
                    if (!empty($userlevel)) {
                      $luong_cb = $userlevel->luong_cb;
                    } else {
                      $luong_cb = 0;
                    }
                    $luong_cb_trong_thang = $daily_results->sum('luong_cb');
                } else {
                    $thuong = 0;
                    $phat = 0;
                    $phu_cap = $request->input('phu_cap')[$key];
                    $so_don_ps = $daily_results->sum('don_ps')+$daily_results->sum('don_ban_may')-$daily_results->sum('don_bao_hanh');
                    $so_don_vs = $daily_results->sum('don_vs');
                    $doanh_so = $daily_results->sum('doanh_so')+$daily_results->sum('ds_ban_may');
                
                    //
                    $daily_first = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends])->first();
                    if (!empty($daily_first->bac_luong)) {
                      $userlevel = UserLevel::where('loai_nv',$daily_first->bac_luong)->first();
                    }
                    if (!empty($userlevel)) {
                      $luong_cb = $userlevel->luong_cb;
                    } else {
                      $luong_cb = 0;
                    }
                    $luong_cb_trong_thang = $daily_results->sum('luong_cb');
                    $so_don_yc = $daily_results->sum('so_don_yc');
                    $doanh_so_yc = $daily_results->sum('doanh_so_yc');

                    $luong_trach_nhiem = 0;
                    $tong_luong = 0.06*$doanh_so+$luong_cb_trong_thang;
                    $kpi_gia_tri_dh = 0;
                    $kpi_doanh_so = 0;
                    $kpi_so_don = 0;
                    $kpi_ti_le_vs = 0;
                    $vuot_ds = $this->salaryUtil->TinhLuongKd($user,$start,$ends,$phu_cap)['vuot_ds'];
                  
                }
                $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                $check = 'nvkd';
                $cong_no = $request->input('cong_no')[$key]+$tien_mua_sp_cty;
                $salary = Salary::where('user_id' , $user_id)->where('thang' , $check)->first();
                $salary->den_ngay = $request->input('den_ngay')[$key];
                $salary->cong_no += $cong_no;
                $salary->tam_ung += $request->input('tam_ung')[$key];
                $salary->cty_giu += $request->input('cty_giu')[$key];
                $salary->doanh_so += $doanh_so;
                $salary->doanh_so_yc += $doanh_so_yc;
                $salary->so_don_vs += $so_don_vs;
                $salary->phu_cap += $phu_cap;
                $salary->kpi_gia_tri_dh += $kpi_gia_tri_dh;
                $salary->kpi_doanh_so += $kpi_doanh_so;
                $salary->kpi_so_don += $kpi_so_don;
                $salary->kpi_ti_le_vs += $kpi_ti_le_vs;
                $salary->so_don_ps += $so_don_ps;
                $salary->don_them += $vuot_ds;
                $salary->chiet_khau += $chiet_khau;
                $salary->ngay_cong += $ngay_cong;
                $salary->luong_cb_trong_thang += $luong_cb_trong_thang;
                $salary->luong_tn += $luong_trach_nhiem;
                $salary->so_don_yc += $so_don_yc;
                $salary->tong_luong += $tong_luong;
                $salary->thuong_nong += $thuong;
                $salary->phat += $phat;
                $salary->save();

            }
        }
        return redirect()->back();       
    }

    public function store(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.edit') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }

        
        $business_id = request()->session()->get('user.business_id');
        $salary_check = Salary::groupBy('created_at')->count('id'); 
            foreach ($request->input('checkbox') as $key) {
                $user_id = $request->input('user_id')[$key];
                $user = User::findOrFail($user_id);
                $to_group = ToGroup::findOrFail($user->to_group);
                
                if ((!empty($user->phong_ban))&&(!empty($user->bo_phan))&&(!empty($user->thoi_gian_lv))&&(!empty($user->salary_status))&&(!empty($user->to_group))&&(!empty($user->custom_field_2))) {
                    $start = $request->input('tu_ngay')[$key];
                    $ends = $request->input('den_ngay')[$key];
                    $date = Carbon::parse($request->input('den_ngay')[$key])->format('d');
                    $year = Carbon::parse($request->input('den_ngay')[$key])->format('Y');
                    $month = Carbon::parse($request->input('den_ngay')[$key])->format('m');
                    
                    $ends2 = Carbon::create($year, $month, $date, 23, 59, 59);
                    
                    $daily_results = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends2]);
                    $ghi_chu = $request->input('ghi_chu')[$key];
                    
                    $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends2])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                    $tien_cho_kh_no = Transaction::where('type','sell')->where(function ($query) {
                            $query->where('loai_don','<>','qly_don_no')->Orwhere('loai_don',NULL);})->where('status','final')->where(function($query){
                        $query->where('payment_status', 'due');
                        $query->orWhere('payment_status','partial');
                    
                    })->whereNotNull('ngay_hen_tra')->where('ngay_hen_tra','<',Carbon::now()->toDateString())->where('nvkt_id',$user_id)->whereBetween('transaction_date',[$start,$ends2])->sum('final_total') - TransactionPayment::leftJoin('transactions as t1','transaction_payments.transaction_id','t1.id')->where('t1.type','sell')
                    ->where(function ($query) {
                            $query->where('t1.loai_don','<>','qly_don_no')->Orwhere('t1.loai_don',NULL);})
                    ->where('t1.status','final')->where(function($query){
                        $query->where('t1.payment_status', 'due');
                        $query->orWhere('t1.payment_status','partial');
                    })->whereNotNull('t1.ngay_hen_tra')->where('t1.ngay_hen_tra','<',Carbon::now()->toDateString())->where('nvkt_id',$user_id)->whereBetween('t1.transaction_date',[$start,$ends2])->sum('transaction_payments.amount');
                    
                    $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                    if ($request->input('cong_no')[$key] == 0) {
                        $cong_no = $tien_mua_sp_cty;
                    } else {
                        $cong_no = $request->input('cong_no')[$key];
                    }
                    $luong_cb_trong_thang = $daily_results->sum('luong_cb');
                    $tam_ung = $request->input('tam_ung')[$key];
                    $cty_giu = $request->input('cty_giu')[$key];
                    $ngay_cong = $daily_results->sum('so_cong');
                    $thuong = 0;
                    $phu_cap = $request->input('phu_cap')[$key];

                    $phat = $daily_results->sum('phat')+PhieuPhat::where('user_id',$user_id)->whereBetween('ngay_phat',[$start,$ends2])->sum('tien_phat');

                    $daily_first = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends2])->first();
                    if (!empty($daily_first->bac_luong)) {
                      $userlevel = UserLevel::where('loai_nv',$user->custom_field_2)->first();
                    }
                    
                    if (!empty($userlevel)) {
                          $luong_cb = $userlevel->luong_cb;
                        } else {
                          $luong_cb = 0;
                        }
                    
                    if ($to_group->group_code == 'TKTBH') {
                      $so_don_ps = $daily_results->sum('don_ps')+$daily_results->sum('ko_tinh_don_ps')+$daily_results->sum('don_ban_may');
                    } else {
                      $so_don_ps = $daily_results->sum('don_ps');
                    }
                    
                    $so_don_yc = $daily_results->sum('so_don_yc');
                    $so_don_vs = $daily_results->sum('don_vs');
                    // doanh so 
                    $ds_them = $daily_results->sum('don_them');
                    $doanh_so = $daily_results->sum('doanh_so');
                    //end doanh so  
                    $chiet_khau = $daily_results->sum('chiet_khau');
                    $chiet_khau_mo_moi = $daily_results->sum('chiet_khau_mo_moi');
                    //

                    $tb_don_yc = 0;
                    $_tb_don = $daily_results->OrderBy('daily_results.ngay','desc')->where('tb_don_yc','>',0)->first();
                        
                    if (!empty($_tb_don)) {
                        $tb_don_yc = $_tb_don->tb_don_yc;
                    }
                    if ($so_don_ps == 0) {
                        $ti_le_vs = 0;
                    } else {
                        $ti_le_vs = ($so_don_ps+$so_don_ps);
                    }
                    $luong_trach_nhiem = 0;
                    $tong_luong = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['luong'];
                   
                    if ($user_id == 300) {
                         $kpi_gia_tri_dh = 0;
                        $kpi_doanh_so = 0;
                        $kpi_so_don = 0;
                        $kpi_ti_le_vs = 0;
                    } else {
                         $kpi_gia_tri_dh = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_gia_tri_dh'];
                        $kpi_doanh_so = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_doanh_so'];
                        // $kpi_so_don = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_so_don'];
                        $kpi_so_don = 0;
                        $kpi_ti_le_vs = $this->salaryUtil->TinhLuongKt($user,$start,$ends,$phu_cap,$business_id)['kpi_ti_le_vs'];
                    }
                    
                    

                    $data = array('user_id' => $user_id,
                                  'business_id' => $business_id,
                                  'thang' => 'nvkt',
                                  'tu_ngay' => $start,
                                  'den_ngay' => $ends,
                                  'cong_no' => $cong_no,
                                  'tam_ung' => $tam_ung,
                                  'cty_giu' => $cty_giu,
                                  'doanh_so' => $doanh_so,
                                  'so_don_vs' => $so_don_vs,
                                  'doanhso_yc' => 0,
                                  'tb_don_yc' => $tb_don_yc,
                                  'don_them' => $ds_them,
                                  'phu_cap' => $phu_cap+$kpi_so_don,
                                  'kpi_gia_tri_dh' => $kpi_gia_tri_dh,
                                  'kpi_doanh_so' => $kpi_doanh_so,
                                  'kpi_so_don' => $kpi_so_don,
                                  'kpi_ti_le_vs' => $kpi_ti_le_vs,
                                  'so_don_ps' => $so_don_ps,
                                  'chiet_khau' => $chiet_khau,
                                  'chiet_khau_mo_moi' => $chiet_khau_mo_moi,
                                  'ngay_cong' => $ngay_cong,
                                  'luong_cb_trong_thang' => $luong_cb_trong_thang,
                                  'luong_cb' => $luong_cb,
                                  'luong_tn' => $luong_trach_nhiem,
                                  'so_don_yc' => $so_don_yc,
                                  'tong_luong' => $tong_luong,
                                  'thuong' => 0,
                                  'thuong_nong' => $thuong,
                                  'phat' => $phat,
                                  'ghi_chu' => $ghi_chu);
                    if ($request->input('check_create')[$key] == 'tao_moi') {
                        Salary::Create($data);
                    } else {
                        Salary::updateOrCreate(array('user_id' => $user_id,'thang' => 'nvkt'),$data);
                    }
                }      
            }
        return redirect()->route('salary.kt');      
    }

    public function storeMkt(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.edit') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        
        $business_id = request()->session()->get('user.business_id');
        $salary_check = Salary::groupBy('created_at')->count('id'); 
        foreach ($request->input('checkbox') as $key) {
            //
            $user_id = $request->input('user_id')[$key];
            $user = User::findOrFail($user_id);  
            if ((!empty($user->phong_ban))&&(!empty($user->bo_phan))&&(!empty($user->thoi_gian_lv))&&(!empty($user->salary_status))&&(!empty($user->to_group))&&(!empty($user->custom_field_2))) {
                $start = $request->input('tu_ngay')[$key]; // date
                $ends = $request->input('den_ngay')[$key]; // datetime
                $daily_results = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends]);
                if (!empty($user->user_kpi)) {
                    $user_kpi = UserKpi::findOrFail($user->user_kpi);
                }
                if (1) {
                    /// Bắt đầu
                    $ngay_cong = $daily_results->sum('so_cong'); 
                    $so_don_ps = $daily_results->sum('don_ps')+$daily_results->sum('don_ban_may');
                    $so_don_vs = $daily_results->sum('don_vs');
                    $so_don_yc = $user_kpi->so_don_yc*$ngay_cong;
                    $ti_le_chot = $request->input('ti_le_chot')[$key];
                    // kpi 

                    //
                    /// bậc lương
                    $daily_first = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends])->first();
                    if (!empty($daily_first->bac_luong)) {
                      $userlevel = UserLevel::where('loai_nv',$daily_first->bac_luong)->first();
                    }
                    if (!empty($userlevel)) {
                      $luong_cb = $userlevel->luong_cb;
                    } else {
                      $luong_cb = 0;
                    }
                    $luong_cb_trong_thang = $daily_results->sum('luong_cb');
                    // chiết khấu đơn nvkd
                    
                    $chiet_khau_don_vuot = 0;
                    $kpi_so_don = 0;
                    if ($so_don_yc > $so_don_ps) {
                        $chiet_khau_don = $so_don_ps*$userlevel->chiet_khau_don;
                        $kpi_so_don = ($so_don_yc-$so_don_ps)*$userlevel->tru_thieu_don; 
                    } else {
                        $chiet_khau_don = $so_don_yc*$userlevel->chiet_khau_don;
                        $chiet_khau_don_vuot = ($so_don_ps - $so_don_yc)*$userlevel->chiet_khau_don_vuot;
                    }
                    // end ck
                    $chiet_khau = $chiet_khau_don+$chiet_khau_don_vuot;
                    $luong_trach_nhiem = 0;
                    $luong_trong_thang = $luong_cb_trong_thang+$chiet_khau+$luong_trach_nhiem;
                    $phu_cap = $request->input('phu_cap')[$key];
                    $tong_luong = $luong_trong_thang+$phu_cap;
                    
                    $kpi_ti_le_chot = 0; //
                    if ($ti_le_chot < $user_kpi->ti_le_chot) {
                        $kpi_ti_le_chot = $tong_luong*15/100;
                    }
                    
                    $phat = $daily_results->sum('phat')+PhieuPhat::where('user_id',$user_id)->whereBetween('ngay_phat', [$start,$ends])->sum('tien_phat');
                    $khau_tru = $kpi_so_don+$kpi_ti_le_chot+$phat;
                    $luong_thuc_te = $tong_luong - $khau_tru;
                    $tam_ung = $request->input('tam_ung')[$key];
                    $cty_giu = $request->input('cty_giu')[$key];
                    $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                    if ($request->input('cong_no')[$key] == 0) {
                        $cong_no = $tien_mua_sp_cty;
                    } else {
                        $cong_no = $request->input('cong_no')[$key];
                    }
                    $thuong_nong = $daily_results->sum('thuong'); 
                    $thuc_linh = $luong_thuc_te - $tam_ung - $cty_giu - $cong_no + $thuong_nong;

                    $data = array('user_id' => $user_id,
                              'business_id' => $business_id,
                              'thang' => 'nvmkt',
                              'tu_ngay' => $start,
                              'den_ngay' => $ends,
                              'so_don_ps' => $so_don_ps,
                              'so_don_vs' => $so_don_vs,
                              'so_don_yc' => $so_don_yc,
                              'ti_le_chot' => $ti_le_chot,  
                              'ti_le_chot_yc' => $user_kpi->ti_le_chot,  
                              'luong_cb' => $luong_cb,
                              'ngay_cong' => $ngay_cong,
                              'chiet_khau' => $chiet_khau,
                              'luong_tn' => $luong_trach_nhiem,
                              'luong_cb_trong_thang' => $luong_cb_trong_thang,
                              'phu_cap' => $phu_cap,
                              'tong_luong' => $tong_luong,
                              'kpi_so_don' => $kpi_so_don,
                              'kpi_ti_le_chot' => $kpi_ti_le_chot,
                              'phat' => $phat,
                              'don_them' => 0,
                              'thuong_nong' => $thuong_nong,
                              'cong_no' => $cong_no,
                              'tam_ung' => $tam_ung,
                              'cty_giu' => $cty_giu,
                              'ghi_chu' => $request->input('ghi_chu')[$key]);

                }

                
                if ($request->input('check_create')[$key] == 'tao_moi') {
                    Salary::Create($data);
                } else {
                    Salary::updateOrCreate(array('user_id' => $user_id,'thang' => 'nvmkt'),$data);
                }
            }
        }
        return redirect()->back();       
    }

    public function storeKd(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.edit') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }

        
        $business_id = request()->session()->get('user.business_id');
        $salary_check = Salary::groupBy('created_at')->count('id'); 
        foreach ($request->input('checkbox') as $key) {
            //
            $user_id = $request->input('user_id')[$key];
            $user = User::findOrFail($user_id);  
            if ((!empty($user->phong_ban))&&(!empty($user->bo_phan))&&(!empty($user->thoi_gian_lv))&&(!empty($user->salary_status))&&(!empty($user->to_group))&&(!empty($user->custom_field_2))) {
              
                $start = $request->input('tu_ngay')[$key]; // date
                $ends = $request->input('den_ngay')[$key]; // datetime
                $daily_results = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends]);
                //
                if ($request->input('buoi_from_date')[$key] == 'chieu') {
                    $daily_results->where(function ($query) use ($start,$ends) {
                        $query->whereBetween('ngay',[$start,$ends])
                        ->whereDate('ngay','<>',Carbon::parse($start)->toDateString())
                        ->Orwhere(function ($query2) use ($start,$ends) {
                            $query2->whereDate('ngay',Carbon::parse($start)->toDateString())
                            ->where('ca','chieu');
                        });
                    });
                    $start = Carbon::create(Carbon::parse($start)->year,Carbon::parse($start)->month,Carbon::parse($start)->day,14,0,0);

                }
                if ($request->input('buoi_to_date')[$key] == 'sang') {
                    $daily_results->where(function ($query) use ($start,$ends) {
                        $query->whereBetween('ngay',[$start,$ends])
                        ->whereDate('ngay','<>',Carbon::parse($ends)->toDateString())
                        ->Orwhere(function ($query2) use ($start,$ends) {
                            $query2->whereDate('ngay',Carbon::parse($ends)->toDateString())
                            ->where('ca','sang');
                        });
                    });
                    $ends = Carbon::create(Carbon::parse($ends)->year,Carbon::parse($ends)->month,Carbon::parse($ends)->day,12,0,0);
                }
                //

                if (!empty($user->user_kpi)) {
                    $user_kpi = UserKpi::findOrFail($user->user_kpi);
                }
                if (1) {

                    /// Bắt đầu
                    $ngay_cong = $daily_results->sum('so_cong'); 
                    $so_don_ps = $daily_results->sum('don_ps')+$daily_results->sum('don_ban_may');
                    $so_don_vs = $daily_results->sum('don_vs');
                    $so_don_yc = round($daily_results->sum('so_don_yc'));
                    $sl_nghe_may_yc = $daily_results->sum('sl_nghe_may_yc');
                    $sl_nghe_may = $daily_results->sum('sl_nghe_may');
                    // kpi 
                    $khai_thac_ton_yc = 0; //
                    $khai_thac_dinh_ky_yc = 0; //
                    $khai_thac_dinh_ky = 0; //
                    $khai_thac_ton = 0; //
                    
                    $thang = Carbon::parse($start)->format('m');
                    $nam = Carbon::parse($start)->format('Y');
                    $sl_data_ton = CskhSetup::where('user_id',$user_id)->where('type','dinh_ky')->where('thang',$thang)->where('nam',$nam)->sum('sl_data_ton');
                    $don_ps_ton = $daily_results->sum('don_ps_ton');

                    $sl_data_dinh_ky = CskhSetup::where('user_id',$user_id)->where('type','dinh_ky')->where('thang',$thang)->where('nam',$nam)->sum('sl_data_dinh_ky');
                    $don_ps_dinh_ky = $daily_results->sum('don_ps_dinh_ky');
           
                  
                    //
                    /// bậc lương
                    $daily_first = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends])->orderBy('created_at','desc')->where('luong_cb','>',0)->first();
                    if (!empty($daily_first->bac_luong)) {
                      $userlevel = UserLevel::where('loai_nv',$daily_first->bac_luong)->first();
                    }
                    if ($user_id == 132) {
                        $userlevel = UserLevel::where('loai_nv',$user->custom_field_2)->first();
                    }
                    if (!empty($userlevel)) {
                      $luong_cb = $userlevel->luong_cb;
                    } else {
                      $luong_cb = 0;
                    }
                    $luong_cb_trong_thang = $daily_results->sum('luong_cb');
                    $chiet_khau = 0;
                    if ($user_id == 132) {
                        $luong_cb_trong_thang = $userlevel->luong_cb*$ngay_cong/26;
                        $chiet_khau = $so_don_ps*50000;
                    } else {
                        if ($so_don_ps > $so_don_yc) {
                            $chiet_khau = ($so_don_ps-$so_don_yc)*$userlevel->chiet_khau_don_vuot;
                        }
                    }
                    

                    
                    $luong_trach_nhiem = 0;
                    $luong_trong_thang = $luong_cb_trong_thang+$chiet_khau+$luong_trach_nhiem;
                    $phu_cap = $request->input('phu_cap')[$key];
                    $tong_luong = $luong_trong_thang+$phu_cap;
                    /// kpi số đơn
                    $kpi_don_percent = 0;
                    if ($so_don_ps < $so_don_yc) {
                        if ((($so_don_yc - $so_don_ps) >= 1)&&(($so_don_yc - $so_don_ps) <= 5) ){
                            $kpi_don_percent = 10;
                        } else {
                            $kpi_don_percent = 20;
                        }
                    }
                   /* $kpi_so_don = 0;*/
                    /*$kpi_sl_nghe_may = 0; */
                    if ($user_id == 315) {
                    	$kpi_so_don = ($luong_trong_thang)*$kpi_don_percent/100;
                    } else {
                    	$kpi_so_don = ($luong_trong_thang-$userlevel->luong_cb*5/26)*$kpi_don_percent/100;
                    }
                    
                    // $kpi_so_don = $luong_cb_trong_thang*$kpi_don_percent/100;
                    $kpi_sl_nghe_may = $daily_results->sum('tru_sl_nghe_may'); 
                    $kpi_khai_thac_dinh_ky = 0; //
                    $kpi_khai_thac_ton = 0; //
                    $phat = PhieuPhat::where('user_id',$user_id)->where('code','<>','thieu_cuoc_goi')->where('code','<>','thieu_don')->whereBetween('ngay_phat', [Carbon::parse($start)->startOfDay(),$ends])->sum('tien_phat');
                    $khau_tru = $kpi_so_don+$kpi_sl_nghe_may+$kpi_khai_thac_ton+$kpi_khai_thac_dinh_ky+$phat;
                    $luong_thuc_te = $tong_luong - $khau_tru;
                    $tam_ung = $request->input('tam_ung')[$key];
                    $cty_giu = $request->input('cty_giu')[$key];
                    $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                    if ($request->input('cong_no')[$key] == 0) {
                        $cong_no = $tien_mua_sp_cty;
                    } else {
                        $cong_no = $request->input('cong_no')[$key];
                    }
                    $thuong_nong = 0; 
                    $thuc_linh = $luong_thuc_te - $tam_ung - $cty_giu - $cong_no + $thuong_nong;

                    $data = array('user_id' => $user_id,
                              'business_id' => $business_id,
                              'thang' => 'nvkd',
                              'tu_ngay' => $start,
                              'den_ngay' => $ends,
                              'so_don_ps' => $so_don_ps,
                              'so_don_vs' => $so_don_vs,
                              'so_don_yc' => $so_don_yc,
                              'sl_nghe_may_yc' => $sl_nghe_may_yc,
                              'sl_nghe_may' => $sl_nghe_may,
                              'khai_thac_dinh_ky_yc' => $khai_thac_dinh_ky_yc,
                              'khai_thac_ton_yc' => $khai_thac_ton_yc,
                              'khai_thac_dinh_ky' => $khai_thac_dinh_ky,
                              'khai_thac_ton' => $khai_thac_ton,
                              'luong_cb' => $luong_cb,
                              'ngay_cong' => $ngay_cong,
                              'chiet_khau' => $chiet_khau,
                              'luong_tn' => $luong_trach_nhiem,
                              'luong_cb_trong_thang' => $luong_cb_trong_thang,
                              'phu_cap' => $phu_cap,
                              'tong_luong' => $tong_luong,
                              'khai_thac_dinh_ky' => $khai_thac_dinh_ky,
                              'khai_thac_ton' => $khai_thac_ton,
                              'kpi_so_don' => $kpi_so_don,
                              'kpi_sl_nghe_may' => $kpi_sl_nghe_may,
                              'kpi_khai_thac_ton' => $kpi_khai_thac_ton,
                              'kpi_khai_thac_dinh_ky' => $kpi_khai_thac_dinh_ky,
                              'phat' => $phat,
                              'don_them' => 0,
                              'thuong_nong' => $thuong_nong,
                              'cong_no' => $cong_no,
                              'tam_ung' => $tam_ung,
                              'cty_giu' => $cty_giu,
                              'ghi_chu' => $request->input('ghi_chu')[$key]);

                }

                
                if ($request->input('check_create')[$key] == 'tao_moi') {
                    Salary::Create($data);
                } else {
                    Salary::updateOrCreate(array('user_id' => $user_id,'thang' => 'nvkd'),$data);
                }
            }
        }
        return redirect()->route('salary.kd');       
    }

    public function storeQuanLy(Request $request)
    {
        if (!auth()->user()->can('salary.create') && !auth()->user()->can('salary.edit') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
        
        $business_id = request()->session()->get('user.business_id');
        foreach ($request->input('checkbox') as $key) {
            //
            $user_id = $request->input('user_id')[$key];
            $user = User::findOrFail($user_id);  
            $phong_ban = PhongBan::findOrFail($user->phong_ban);
            $userlevel = UserLevel::where('loai_nv',$user->custom_field_2)->first(); 
            $luong_cb = 0;
            $luong_trach_nhiem = 0;
            
            if (1) {
                $start = $request->input('tu_ngay')[$key];
                $ends = $request->input('den_ngay')[$key];
                if (!empty($userlevel)) {
                    if (!empty($request->input('so_cong')[$key])) {
                        $so_cong = $request->input('so_cong')[$key];
                        $luong_cb = $userlevel->luong_cb/26*$so_cong;
                    } else {
                        $cham_congs = Maychamcong::where('ma_nhanvien',$user->surname)->whereBetween('ngay_cham',[$start,$ends])->get();
                        $so_cong = DailyResult::where('business_id',$business_id)->where('user_id',$user_id)->whereBetween('ngay',[$start,$ends])->sum('so_cong');
                        $luong_cb = $userlevel->luong_cb/26*$so_cong;
                    }
                } 
                
                $phat = PhieuPhat::where('user_id',$user->id)->whereBetween('ngay_phat',[$start,$ends])->sum('tien_phat');
                if ($user->id == 115) {
                    
                }
                $luong_trach_nhiem = $this->salaryUtil->LuongTrachNhiem($user,$start,$ends,$user->user_type);
                $chiet_khau_mo_moi = Transaction::where('nvkd_id',$user_id)->where('type', 'sell')->where('status', 'final')->whereBetween('created_at', [$start,$ends])->where('is_mo_moi', 'mo_moi')->sum('final_total')*0.1;
                $chiet_khau = 0;
               
                $doanh_so = $request->input('doanh_so')[$key];
                $hoa_hong = $request->input('hoa_hong')[$key];
                $chiet_khau = $hoa_hong/100*$doanh_so;
                if ($user_id == 299) {
                    $so_cong = 20;
                    $chiet_khau = 947000;
                    $luong_cb = 2847000;
                }
                if ($user_id == 320) {
                    $so_cong = 19;
                    $chiet_khau = 554000;
                    $luong_cb = 1938000;
                }
                if ($user_id == 330) {
                    $so_cong = 6;
                    $chiet_khau = 96000 + 24000;
                    $luong_cb = 1384615;
                    $userlevel->luong_cb = 6000000;
                }
                
                if ($user_id == 228) {
                    $luong_cb = 2873912;
                }
                if ($user_id == 322) {
                    $luong_cb = 2953840;
                }
                
                $tien_mua_sp_cty = DeNghiXuatHang::where('de_nghi_xuat_hangs.business_id',$business_id)->where('de_nghi_xuat_hangs.type','xuat_ban_nv')->where('de_nghi_xuat_hangs.status','da_xuat')->where('de_nghi_xuat_hangs.method','due')->where('de_nghi_xuat_hangs.user_id',$user_id)->whereBetween('de_nghi_xuat_hangs.created_at',[$start,$ends])->leftjoin('de_nghi_xuat_hang_details as dnxhdt','de_nghi_xuat_hangs.id','dnxhdt.de_nghi_xuat_id')->sum('dnxhdt.thanh_tien');
                if ($request->input('cong_no')[$key] > 0) {
                    $cong_no = $request->input('cong_no')[$key];
                } else {
                    $cong_no = $tien_mua_sp_cty;
                }
                $cty_giu = $request->input('cty_giu')[$key];
                    
                $tong_luong = $luong_cb + $chiet_khau + $request->input('phu_cap')[$key]+$luong_trach_nhiem-$phat+$chiet_khau_mo_moi - $cong_no- $cty_giu;
                $data = array('user_id' => $user_id,
                              'business_id' => $business_id,
                              'thang' => 'quan_ly',
                              'chiet_khau_mo_moi' => $chiet_khau_mo_moi,
                              'tu_ngay' => $request->input('tu_ngay')[$key],
                              'den_ngay' => $request->input('den_ngay')[$key],
                              'cong_no' => $cong_no,
                              'tam_ung' => $request->input('tam_ung')[$key],
                              'cty_giu' => $cty_giu,
                              'chiet_khau' => $chiet_khau,
                              'doanh_so' => 0,
                              'doanhso_yc' => 0,
                              'so_don_vs' => 0,
                              'phu_cap' => $request->input('phu_cap')[$key],
                              'kpi_gia_tri_dh' => 0,
                              'kpi_doanh_so' => 0,
                              'kpi_so_don' => 0,
                              'kpi_ti_le_vs' => 0,
                              'so_don_ps' => 0,
                              'don_them' => 0,
                              'ngay_cong' => $so_cong,
                              'luong_cb' => $userlevel->luong_cb,
                              'luong_cb_trong_thang' => $luong_cb,
                              'luong_tn' =>   0,
                              'so_don_yc' => 0,
                              'tong_luong' => $tong_luong,
                              'thuong' => 0,
                              'phat' => $phat,
                              'ghi_chu' => $request->input('ghi_chu')[$key]);
                if ($request->input('check_create')[$key] == 'tao_moi') {
                    Salary::Create($data);
                } else {
                    Salary::updateOrCreate(array('user_id' => $user_id,'thang' => 'quan_ly'),$data);
                }
                
            }
        }
        return redirect()->route('salary.luong-cung-khac');       
    }


    public function updateQuanLy(Request $request,$id)
    {
        if (!auth()->user()->can('salary.edit') && !auth()->user()->can('salary.view')) {
            abort(403, 'Unauthorized action.');
        }
              $salary = Salary::findOrFail($id);
        $salary->tu_ngay = $request->input('tu_ngay');
        $salary->den_ngay = $request->input('den_ngay');
        $salary->cong_no = $request->input('cong_no');
        $salary->tam_ung = $request->input('tam_ung');
        $salary->phu_cap = $request->input('phu_cap');
        $salary->ngay_cong = $request->input('ngay_cong');
        // $salary->luong_tn = $request->input('luong_trach_nhiem');
        $salary->phat = $request->input('phat');
        $salary->ghi_chu = $request->input('ghi_chu');
            //
        $user_id = $salary->user_id;
        $user = User::findOrFail($salary->user_id);  
        $userlevel = UserLevel::where('loai_nv',$user->custom_field_2)->first(); 
        $luong_cb = 0;
        
        if (!empty($userlevel)) {
          $luong_cb = round($userlevel->luong_cb/26*$request->input('ngay_cong'), -2);
        } 
        
        $tong_luong = $luong_cb + $request->input('phu_cap');
        $salary->luong_cb_trong_thang = $luong_cb;
        $salary->luong_cb = round($userlevel->luong_cb, -2);
        $salary->tong_luong = $tong_luong;
        $salary->save();
        return redirect()->route('salary.luong-cung-khac');       
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Salary  $salary
     * @return \Illuminate\Http\Response
     */
    public function show(Salary $salary)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Salary  $salary
     * @return \Illuminate\Http\Response
     */
    public function edit($thang)
    {   

        $salaries = Salary::where('thang',$thang)->get();
        $business_id = request()->session()->get('user.business_id');
        $users = User::where('user_type','2')->where('status','active')->whereNull('deleted_at')->limit(3)->get();
        return view('salary.edit')->with(compact('users','business_id','salaries','thang'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Salary  $salary
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $thang)
    {
        if (!auth()->user()->can('user.create') && !auth()->user()->can('user.view')) {
            abort(403, 'Unauthorized action.');
        }
        $salaries = Salary::where('thang',$thang)->get();
        $business_id = request()->session()->get('user.business_id');
            foreach ($salaries as $key => $salary_check) {
                $salary = Salary::findOrFail($salary_check->id);
                $values = Salary::where('thang', $thang)->update(['data'=>$data]);
                
            }
        return back(); 
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Salary  $salary
     * @return \Illuminate\Http\Response
     */
    public function delete($id)
    {   
        if (!auth()->user()->can('salary.delete')) {
            abort(403, 'Unauthorized action.');
        }
        $salary = Salary::find($id);
        $salary->delete();
        
        return response()->json('ok');
    }
    public function destroy($salary)
    {
       
    }

    private function GetCK($id,$level_loai,$group_id,$start,$ends) {

        $transfers = UsersTransfer::where('user_id',$id)->orderBy('created_at')->whereBetween('created_at', [$start,$ends])->get();
        $transfer_count = UsersTransfer::where('user_id',$id)->orderBy('times', 'desc')->whereBetween('created_at', [$start,$ends])->count();
        $chiet_khau = 0;
        $chiet_khaus = 0;
        
        if ($transfer_count) {
            $chiet_khaus1 = 0;
            $chiet_khaus2 = 0;
            if ($transfer_count == 1) {
                $trans_s1 = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$start,$transfers[0]->created_at])->get();
                $trans_s2 = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$transfers[0]->created_at,$ends])->get();
                $level1 = UserLevel::where('loai_nv',$transfers[0]->trans_from)->first();
                $to_group1 = ToGroup::findOrFail($transfers[0]->trans_group_from);
                $chiet_khaus1 = $this->ChietKhau($trans_s1,$level1,$to_group1)['chiet_khaus'];

                $level2 = UserLevel::where('loai_nv',$transfers[0]->trans_to)->first();
                $to_group2 = ToGroup::findOrFail($transfers[0]->trans_group_to);
                $chiet_khaus2 = $this->ChietKhau($trans_s2,$level2,$to_group2)['chiet_khaus'];                       

                $chiet_khaus = $chiet_khaus1 + $chiet_khaus2;
                
            } else {
                //tranfer_foreach
                foreach ($transfers as $key => $transfer) {
                    $chiet_khaux =0;
                    $chiet_khaus3 = 0;

                    if ($key == 0) {
                        $trans_s1 = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$start,$transfers[$key]->created_at])->get();
                        $trans_s2 = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$transfers[$key]->created_at,$transfers[($key+1)]->created_at])->get();
                        
                        // giai ddoanj
                        $level1 = UserLevel::where('loai_nv',$transfer->trans_from)->first();
                        $to_group1 = ToGroup::findOrFail($transfer->trans_group_from);
                        $chiet_khaus1 = $this->ChietKhau($trans_s1,$level1,$to_group1)['chiet_khaus'];
                        // giai ddoanj
                        $level2 = UserLevel::where('loai_nv',$transfer->trans_to)->first();
                        $to_group2 = ToGroup::findOrFail($transfer->trans_group_to);
                        $chiet_khaus2 = $this->ChietKhau($trans_s2,$level2,$to_group2)['chiet_khaus'];
                        // giai ddoanj
                        $chiet_khaux = $chiet_khaus1 + $chiet_khaus2;

                    } else {
                        if ($key == ($transfer_count-1)) {
                            $end = $ends;
                        } else {
                            $end = $transfers[($key+1)]->created_at;
                        }

                        $trans_s = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$transfers[$key]->created_at,$end])->get();
                        $level = UserLevel::where('loai_nv',$transfer->trans_to)->first();
                        $to_group = ToGroup::findOrFail($transfer->trans_group_to);
                        $chiet_khaus3 = $this->ChietKhau($trans_s,$level,$to_group)['chiet_khaus'];
                        
                        $chiet_khaux = $chiet_khaus3;
                    }
                    $chiet_khaus += $chiet_khaux;
                }
                //tranfer_foreach
            } 
            //  
        } else {
            
            $trans_s = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$start,$ends])->get();
            $level = UserLevel::where('loai_nv',$level_loai)->first();
            $to_group = ToGroup::findOrFail($group_id);
            $chiet_khaus = $this->ChietKhau($trans_s,$level,$to_group)['chiet_khaus'];
            // giai ddoanj
        }
        return $chiet_khaus;
    }

    public function ChietKhau($trans_s,$level,$to_group){
        $chiet_khaus = 0; 
        $ds_them = 0;
        $don_them = 0;
        if (empty($level)) {
            $level = '';
        }
        if (!empty($trans_s)) {
            foreach ($trans_s as $trans) {
                $chiet_khau = 0;
                if ($trans->nvkd_id == 114) {
                    $don_them = 0.08*$trans->final_total;
                }  
                $tran_sell_lines = TransactionSellLine::where('transaction_id',$trans->id)->get();
                $x= 0;
                $y = 0;                                  
                $counts = 0;
                $ck_giam =0;
                    foreach ($tran_sell_lines as $tran_sell_line) {
                        $trans_product = Product::where('id',$tran_sell_line->product_id)->first();
                        $count = 0; 
                        
                        if ($trans_product) {
                                switch ($level->phong_to) {
                                    case 'KTKDTV1':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_kd_tv1;
                                        $y = $trans_product->kt_kd_tv1;;
                                        break;
                                    case 'KTKDTV2':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_kd_tv2;
                                        $y = $trans_product->kt_kd_tv2;
                                        break;
                                    case 'KTKDCT':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_kd_ct;
                                        $y = $trans_product->kt_kd_ct;
                                        break;
                                    case 'KTCSKHTV1':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_cskh_tv1;
                                        $y = $trans_product->kt_cskh_tv1;
                                        break;
                                    case 'KTCSKHTV2':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_cskh_tv2;
                                        $y = $trans_product->kt_cskh_tv2;
                                        break;
                                    case 'KTCSKHCT':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_cskh_ct;
                                        $y = $trans_product->kt_cskh_ct;
                                        break;
                                    case 'KTKDTV1':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_kd_tv1;
                                        $y = $trans_product->kt_kd_tv1;;
                                        break;
                                    case 'KTBHTV2':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_kd_tv2;
                                        $y = $trans_product->kt_kd_tv2;
                                        break;
                                    case 'KTBHCT':
                                        $x=$tran_sell_line->quantity*$trans_product->kt_kd_ct;
                                        $y = $trans_product->kt_kd_ct;
                                        break;
                                    default:
                                        $x=0;
                                        $y=0;
                                        break;
                                }
                        } else {
                           $x=0;
                        }
                        if (substr($trans_product->product_check,  0, 3) == 'bo3') {
                            $count = 1;
                            $ck_giam = $y;
                        }
                        //    
                        $chiet_khau+=$x;
                        $counts += $count;
                    }
                    if ($counts==2) {
                        $chiet_khau=$chiet_khau - $ck_giam;

                    } elseif($counts==3) {
                        if($to_group->group_type_2 != 'su_kien'){
                            if($level->phong_to == 'KTCSKHCT'){
                                $chiet_khau=$chiet_khau - $ck_giam -5000;
                            } else {
                                $chiet_khau=$chiet_khau - $ck_giam;
                            } 
                        } else {
                            if(($level->phong_to == 'KTCSKHCT')||($level->phong_to == 'KTBHCT')){
                                $chiet_khau=$chiet_khau;
                            } else {
                                $chiet_khau=$chiet_khau + $ck_giam;
                            } 
                        }
                    }
                    $ds_them += $don_them;
                    $chiet_khaus += $chiet_khau;
            }
        } else {
            $chiet_khaus = 0;
            $ds_them = 0;
        }
        $data = [
                'chiet_khaus' => $chiet_khaus,
                'ds_them' => $ds_them,
            ];
        return $data;
    }

    private function TinhLuong($id,$start,$ends,$level,$to_group,$chiet_khaus,$phu_cap=0) {
        $ngay_cong = ChamCong::where('nhanvien_id',$id)->whereBetween('created_at', [$start,$ends])->sum('cham_cong');
        $so_don_ps = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total','>', 0)->whereBetween('created_at', [$start,$ends])->count();
        $don_vs = Transaction::where('nvkt_id',$id)->where('type', 'sell')->where('final_total', 0)->whereBetween('created_at', [$start,$ends])->get();
        $so_don_vs = $don_vs->count();
        $user = User::findOrFail($id);
        
        // luong_tn
        $doanh_so_pt = 0;
        $so_don_pt = 0;
        $doanh_so_pt_yc = 0;
        $so_don_pt_yc = 0;
        $count_ds =0;
        $count_sd =0;
        
        
        //
        $doanh_so = Transaction::where('nvkt_id',$id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->sum('final_total');
        $products = Product::active()
                    ->leftjoin(
                        'transaction_sell_lines AS tsl',
                        'products.id',
                        '=',
                        'tsl.product_id'
                    )
                    ->leftjoin(
                        'transactions AS t1',
                        'tsl.transaction_id',
                        '=',
                        't1.id'
                    )
                    ->leftjoin(
                        'brands AS b1',
                        'products.brand_id',
                        '=',
                        'b1.id'
                    )
                    ->join('variations', 'products.id', '=', 'variations.product_id')
                    ->where('t1.type','sell')
                    ->where('t1.nvkt_id',$id)
                    ->GroupBy('tsl.product_id')
                    ->whereBetween('t1.created_at', [$start,$ends])
                    ->where('products.not_for_selling',0)
                    ->select(
                    'b1.id as brand_id',
                    'variations.sell_price_inc_tax as selling_price',
                    DB::raw('sum(tsl.quantity) as so_luong')
                )->get();

        $gia_may = 0;       
        $tru_don = 0;       
                 
        foreach ($products as $key => $product) {
            if ($product->brand_id == 12) {
                $gia_may += $product->so_luong*$product->selling_price;
                $tru_don += 1; 
                
            }
            
        } 
        $so_don_ps -= $tru_don;
        $doanh_so -=  $gia_may;
        $so_don = $so_don_ps+$so_don_vs;
        // End tính triết khấu
        $thuong = ChamCong::where('nhanvien_id',$id)->whereBetween('created_at', [$start,$ends])->sum('thuong_ngay');
        $phat = ChamCong::where('nhanvien_id',$id)->whereBetween('created_at', [$start,$ends])->sum('phat_ngay');
        // Tính kpi
        $luong_cb = round($ngay_cong*($level->luong_cb)/26, -2);
        $don_yc_thang = $level->don_yc*$ngay_cong;
        $x = $luong_cb+$chiet_khaus+$thuong+$luong_trach_nhiem+$phu_cap;
        $x_a = 100;
        $luong_0 = 0;
        if ($so_don>0) {
            $tb_don_thuc= $doanh_so/$so_don_ps;
            $ti_le_vs = $so_don_vs/$so_don;
        } else {
            $ti_le_vs = 0;
            $tb_don_thuc = 0;
            $luong_0 = 1;
        }
        
        if ($to_group->group_code != 'TKTBH') {
            if ($don_yc_thang-$so_don_ps<=3 && $don_yc_thang-$so_don_ps>=1) {
                $x_b = $x_a;
                if (($level->tb_don)>$tb_don_thuc) {
                    $x_c = $x_b-20;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }

                    $luong = $x_d*$x/100-500000-$phat;
                } else {
                    $x_c = $x_b;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-500000-$phat;
                }
                
            } elseif ($don_yc_thang-$so_don_ps > 3) {
                $x_b = $x_a-20;
                if (($level->tb_don)>$tb_don_thuc) {
                    $x_c = $x_b-20;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;    
                    }
                    $luong = $x_d*$x/100-$phat;
                } else {
                    $x_c = $x_b;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-$phat;
                }
                
            } else {
                $x_b = $x_a;
                if (($level->tb_don)>$tb_don_thuc) {
                    $x_c = $x_b-20;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-$phat;
                } else {
                    $x_c = $x_b;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;   
                    }
                    $luong = $x_d*$x/100-$phat;
                }
                
            }
            // end dieu kien
        } else {
            $luong = $x-$phat;
        }
        $khau_tru_kpi = $x - $luong - $phat;
        
        $data = [
                'luong_tn' => $luong_trach_nhiem,
                'khau_tru_kpi' => $khau_tru_kpi,
                'luong' => $x,
                'so_don_yc' => $don_yc_thang,
                'doanhso_yc' => $level->doanhso_yc*$ngay_cong,
                'luong_cb' => $level->luong_cb*$ngay_cong/26
            ];
        return $data;
    }
  

    private function TinhLuongKD($id,$start,$ends,$level,$phu_cap = 0) {
        $ngay_cong = ChamCong::where('nhanvien_id',$id)->whereBetween('created_at', [$start,$ends])->sum('cham_cong');
        $so_don_ps = Transaction::where('nvkd_id',$id)->where('type', 'sell')->where('final_total','>', 0)->where('is_quotation', 0)->whereBetween('created_at', [$start,$ends])->count();
        $don_vs = Transaction::where('nvkd_id',$id)->where('type', 'sell')->where('final_total', 0)->where('is_quotation', 0)->whereBetween('created_at', [$start,$ends])->get();
        $so_don_vs = $don_vs->count();
        $doanh_so_thuc = Transaction::where('nvkd_id',$id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->sum('final_total');
        $tong_so_don = $so_don_ps+$so_don_vs;
        // End tính triết khấu
        // tinhs luong trach nhiem
        $user = User::findOrFail($id);
        $doanh_so_pt = 0;
        $so_don_pt = 0;
        $doanh_so_pt_yc = 0;
        $so_don_pt_yc = 0;
        $count_ds =0;
        $count_sd =0;
        if ($user->phan_quyen == 'tp') {
            $pto_s = User::where('user_type','3')->where('status','active')->whereNull('deleted_at')->get();

            $pto_s_count = $pto_s->count();
            foreach ($pto_s as $key => $pto) {
                $level_pto = UserLevel::where('loai_nv',$pto->custom_field_2)->first();
                $ngay_cong_pto = ChamCong::where('nhanvien_id',$pto->id)->whereBetween('created_at', [$start,$ends])->sum('cham_cong');
                $ds_pt_yc = Transaction::where('nvkd_id',$pto->id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->sum('final_total');
                $sd_pt_yc = $level_pto->don_yc*$ngay_cong_pto;
                $ds_pt_yc = $sd_pt_yc*$level_pto->tb_don*$ngay_cong_pto;
                $ds_pt = Transaction::where('nvkd_id',$pto->id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->sum('final_total');
                $sd_pt = Transaction::where('nvkd_id',$pto->id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->count();
                $doanh_so_pt += $ds_pt;
                $so_don_pt += $sd_pt;
                $doanh_so_pt_yc += $ds_pt_yc;
                $so_don_pt_yc += $sd_pt_yc;
                if ($ds_pt>$ds_pt_yc) {
                    $count_ds +=1;
                }
                if ($sd_pt>$sd_pt_yc) {
                    $count_sd +=1;
                }                 
            }
            // he so so don
            if ($so_don_pt > $so_don_pt_yc) {
                $he_so_sd = 0.8;
            } else {
                $he_so_sd = 0.6;
            }
 
            // he so doanh so

            if ($doanh_so_pt > $doanh_so_pt_yc) {
                $he_so_ds = 0.8;
            } else {
                $he_so_ds = 0.6;
            }
            if ($doanh_so_pt_yc&&$doanh_so_pt_yc) {
                $luong_trach_nhiem = $doanh_so_pt*($he_so_ds*$doanh_so_pt/$doanh_so_pt_yc+$he_so_sd*$so_don_pt/$so_don_pt_yc)/200;
            } else {
                $luong_trach_nhiem = 0;
            }
        } elseif ($user->phan_quyen == 'tt') {
            $pto_s = User::where('to_group',$user->to_group)->get();
            $pto_s_count = User::where('to_group',$user->to_group)->count();
            foreach ($pto_s as $key => $pto) {
                $level_pto = UserLevel::where('loai_nv',$pto->custom_field_2)->first();
                $ngay_cong_pto = ChamCong::where('nhanvien_id',$pto->id)->whereBetween('created_at', [$start,$ends])->sum('cham_cong');
                $ds_pt_yc = Transaction::where('nvkd_id',$pto->id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->sum('final_total');
                $sd_pt_yc = $level_pto->don_yc*$ngay_cong_pto;
                $ds_pt_yc = $sd_pt_yc*$level_pto->tb_don*$ngay_cong_pto;
                $ds_pt = Transaction::where('nvkd_id',$pto->id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->sum('final_total');
                $sd_pt = Transaction::where('nvkd_id',$pto->id)->where('type', 'sell')->whereBetween('created_at', [$start,$ends])->count();
                $doanh_so_pt += $ds_pt;
                $so_don_pt += $sd_pt;
                $doanh_so_pt_yc += $ds_pt_yc;
                $so_don_pt_yc += $sd_pt_yc;
                if ($ds_pt>$ds_pt_yc) {
                    $count_ds +=1;
                }
                if ($sd_pt>$sd_pt_yc) {
                    $count_sd +=1;
                }                 
            }
            // he so so don
            if ((($count_ds/$pto_s_count)>0.5)&&(($count_sd/$pto_s_count)>0.5)) {
                if ($doanh_so_pt > $doanh_so_pt_yc) {
                    $he_so_ds = 0.5;
                    $he_so_sd = 0.5;
                } else {
                    $he_so_ds = 0.3;
                    $he_so_sd = 0.3;
                }
            } else {
                $he_so_ds = 0;
                $he_so_sd = 0;
            }
            if ($doanh_so_pt_yc&&$doanh_so_pt_yc) {
                $luong_trach_nhiem = $doanh_so_pt*($he_so_ds*$doanh_so_pt/$doanh_so_pt_yc+$he_so_sd*$so_don_pt/$so_don_pt_yc)/200;
            } else {
                $luong_trach_nhiem = 0;
            }
            //
        } else {
            $he_so_sd = 0;
            $he_so_ds = 0;
            $luong_trach_nhiem = 0;
        } 
        //end 
        $thuong = ChamCong::where('nhanvien_id',$id)->whereBetween('created_at', [$start,$ends])->sum('thuong_ngay');
        $phat = ChamCong::where('nhanvien_id',$id)->whereBetween('created_at', [$start,$ends])->sum('phat_ngay');
        // Tính kpi
        $luong_cb = round($ngay_cong*($level->luong_cb)/26, -2);
        $don_yc_thang = $level->don_yc*$ngay_cong;
        $doanh_so_0 = $level->doanhso_yc*$ngay_cong;
        $luong = 0;
        $vuot_ds = 0;


        if ($level->phong_to == 'KDSKCT') {  
              $phan_tram_vuot = 8;
              $tien_vuot_1 = 500000;
              $tien_vuot_2 = 1000000;
          } else {
              if (substr($level->loai_nv,  7, 1) == 'P') {
                  $phan_tram_vuot = 5;
                  $tien_vuot_1 = 200000;
                  $tien_vuot_2 = 500000;
              } else {
                  $phan_tram_vuot = 5;
                  $tien_vuot_1 = 500000;
                  $tien_vuot_2 = 1000000;
              }
          }

          if (substr($level->phong_to,  0, 4) == 'KDSK') {
              $vuot_1 = 50000000;
              $vuot_2 = 80000000;
             
          } else {
              if (substr($level->phong_to,  4, 2) == 'TV') {
                  $vuot_1 = 20000000;
                  $vuot_2 = 40000000;
                 
              } else {
                  $vuot_1 = 30000000;
                  $vuot_2 = 50000000;
                 
              }
              
          }
        if ($tong_so_don>0) {
            $luong_0 = false;
        } else {

            $luong_0 = true;
        }
        $khau_tru_kpi = 0;
        // Tổ sự kiện
        if ($don_yc_thang&&$doanh_so_0) {
            if(($doanh_so_thuc/$doanh_so_0<50/100)||($so_don_ps/$don_yc_thang<50/100)==true)
            {   
                $x=$luong_cb+$thuong+$luong_trach_nhiem+$phu_cap;
                $y = $x;
                $z=$luong_cb/2+$thuong+$luong_trach_nhiem;
                $vuot_ds = 0;
                $khau_tru_kpi = $x-$z;
                $tong_luong = $x;
            }
            elseif (($doanh_so_thuc-$doanh_so_0)>=0) {
                    $x=$luong_cb+$phan_tram_vuot/100*($doanh_so_thuc-$doanh_so_0)+$thuong+$luong_trach_nhiem+$phu_cap;
                    $vuot_ds = $phan_tram_vuot/100*($doanh_so_thuc-$doanh_so_0);
                    if (($doanh_so_thuc-$doanh_so_0)>0&&($doanh_so_thuc-$doanh_so_0)<$vuot_1) {
                            $y = $x;
                            if (($don_yc_thang-$so_don_ps)<0) {
                                $z = $y;
                            } elseif (($don_yc_thang-$so_don_ps)==1) {
                                $z = $y - 50000;
                            } elseif (($don_yc_thang-$so_don_ps)==2) {
                                $z = $y - 100000;    
                            } elseif (($don_yc_thang-$so_don_ps)>=3&&($don_yc_thang-$so_don_ps)<=5) {
                                $z = $y - 200000;
                            } else {
                                $z = 80/100*$y;
                            }
                    } elseif (($doanh_so_thuc-$doanh_so_0)>$vuot_1&&($doanh_so_thuc-$doanh_so_0)<$vuot_2) {
                            $y = $x+$tien_vuot_1;
                            if (($don_yc_thang-$so_don_ps)<0) {
                                $z = $y;
                            } elseif (($don_yc_thang-$so_don_ps)==1) {
                                $y = $y - 50000;
                            } elseif (($don_yc_thang-$so_don_ps)==2) {
                                $z = $y - 100000;    
                            } elseif (($don_yc_thang-$so_don_ps)>=3&&($don_yc_thang-$so_don_ps)<=5) {
                                $z = $y - 200000;
                            } else {
                                $z = 80/100*$y;
                            }
                    } else{
                            $y = $x+$tien_vuot_2;
                            if (($don_yc_thang-$so_don_ps)<0) {
                                $z = $y;
                            } elseif (($don_yc_thang-$so_don_ps)==1) {
                                $y = $y - 50000;
                            } elseif (($don_yc_thang-$so_don_ps)==2) {
                                $z = $y - 100000;    
                            } elseif (($don_yc_thang-$so_don_ps)>=3&&($don_yc_thang-$so_don_ps)<=5) {
                                $z = $y - 200000;
                            } else {
                                $z = 80/100*$y;
                            }
                        }
                    $khau_tru_kpi = $y-$z;
                    $tong_luong = $y;
            } elseif(($doanh_so_thuc-$doanh_so_0)<0) 
            {
                    $x=90/100*($luong_cb+$thuong+$luong_trach_nhiem+$phu_cap);
                    $y = $x;
                    $vuot_ds = 0;
                            if (($don_yc_thang-$so_don_ps)<0) {
                                $z = $y;
                            } elseif (($don_yc_thang-$so_don_ps)==1) {
                                $y = $y - 50000;
                            } elseif (($don_yc_thang-$so_don_ps)==2) {
                                $z = $y - 100000;    
                            } elseif (($don_yc_thang-$so_don_ps)>=3&&($don_yc_thang-$so_don_ps)<=5) {
                                $z = $y - 200000;
                            } else {
                                $z = 80/100*$y;
                            }
                    $khau_tru_kpi = $luong_cb+$thuong+$luong_trach_nhiem-$z;
                    $tong_luong = $luong_cb+$thuong+$luong_trach_nhiem+$phu_cap;
            }
            
            // end tổ sự kiện
            
            if ($luong_0) {
                $luong = 0;
            } else {
                $luong = $z-$phat;
                
            }
        } else {
            $luong = 0;
            $tong_luong = 0;
        }
        
        
        $data = [
                'vuot_ds' => $vuot_ds,
                'luong_tn' => $luong_trach_nhiem,
                'khau_tru_kpi' => $khau_tru_kpi,
                'luong' => $tong_luong,
                'so_don_yc' => $don_yc_thang,
                'doanhso_yc' => $level->doanhso_yc*$ngay_cong,
                'luong_cb' => $level->luong_cb*$ngay_cong/26
            ];
        return $data;
    }

    public function testerView(Request $request) {
      $luongs = Post::where('type','test')->orderBy('created_at','DESC')->first();
      if (!empty($luongs)) {
         $luong = $luongs->content;
      } else {
         $luong = 0;
      }
      
        
        return view('test.index')->with(compact('luong'));
    }
    public function tester(Request $request) {
        $ngay_cong = $request->input('ngay_cong');
        $so_don_ps = $request->input('so_don_ps');
        $so_don_vs = $request->input('so_don_vs');
        $doanh_so = $request->input('doanh_so');
        $so_don = $so_don_ps+$so_don_vs;
        $gia_tri_tb_don = $request->input('gia_tri_tb_don');
        // End tính triết khấu
        $thuong = $request->input('thuong');
        $phat = $request->input('phat');
        // Tính kpi
        $luong_cb = $request->input('luong_cb')/26*$ngay_cong;
        $don_yc_thang = $request->input('don_yc');
        $chiet_khaus = $request->input('chiet_khau');
        $x = $luong_cb+$chiet_khaus+$thuong;
        $x_a = 100;
        $luong_0 = 0;
        if ($so_don>0) {
            $tb_don_thuc= $doanh_so/$so_don_ps;
            $ti_le_vs = $so_don_vs/$so_don;
        } else {
            $ti_le_vs = 0;
            $tb_don_thuc = 0;
            $luong_0 = 1;
        }
        
        if ($request->input('to_group') != 'KTBH') {
            if ($don_yc_thang-$so_don_ps<=3 && $don_yc_thang-$so_don_ps>=1) {
                $x_b = $x_a;
                if (($gia_tri_tb_don)>$tb_don_thuc) {
                    $x_c = $x_b-20;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-500000-$phat;
                } else {
                    $x_c = $x_b;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-500000-$phat;
                }
                
            } elseif ($don_yc_thang-$so_don_ps > 3) {
                $x_b = $x_a-20;
                if (($gia_tri_tb_don)>$tb_don_thuc) {
                    $x_c = $x_b-20;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;    
                    }
                    $luong = $x_d*$x/100-$phat;
                } else {
                    $x_c = $x_b;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-$phat;
                }
                
            } else {
                $x_b = $x_a;
                if (($gia_tri_tb_don)>$tb_don_thuc) {
                    $x_c = $x_b-20;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;
                    }
                    $luong = $x_d*$x/100-$phat;
                } else {
                    $x_c = $x_b;
                    if ($ti_le_vs>0.05) {
                        $x_d = $x_c-10;
                    } else {
                        $x_d = $x_c;   
                    }
                    $luong = $x_d*$x/100-$phat;
                }
                
            }
            // end dieu kien
        } else {
            $luong = $x-$phat;
        }
        $post = new Post;
        $post->content = $luong;
        $post->type = 'test';
        $post->created_by = $luong;
        $post->tb_title = $luong;
        $post->save();
        return back();
    }
}
