<?php

namespace App\Http\Controllers\Api\V2\DailySales;

use App\Branch;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\DsrBooking;
use Carbon\CarbonPeriod;
use App\Http\Controllers\Requests\DailySales\DailySalesListRequest;
use App\DsrSplit;
use App\Quarter;
use App\User;

class DailySalesReportController extends Controller
{
    public function index(DailySalesListRequest $request)
    {
        $authUser = auth()->user();
        // $branchId = $request->branch_id;
        $type = $request->type;
        $currentDate = date('Y-m-d');
        $quarterlyTarget = Quarter::whereRaw('? between date_from and date_to', $currentDate)
            ->first();

        $start = '';
        $mid = '';
        $end = '';

        if ($quarterlyTarget) {
            $months = CarbonPeriod::create($quarterlyTarget->date_from, '1 month', $quarterlyTarget->date_to);
            foreach ($months as $dt) {
                $month[] = $dt->format('F');
            }
            $start = $month[0];
            $mid = $month[1];
            $end = $month[2];
        }

        $branch_name = '';
        if ($branchId) {
            $branch = Branch::find($branchId);
            $branch_name = $branch->name;
        }

        $teamLeaders = User::with('roles', 'getDsr')
            ->whereHas('roles', function ($query) use ($type) {
                $query->when($type == "team-leader", function ($query) {
                    return $query->where('id', 7);
                });

                $query->when($type == "sales-person", function ($query) {
                    return $query->where('id', 8)->where('reporting_to', '!=', 282);
                });
            })
            ->when($branchId, function ($q, $branchId) {
                return $q->where('branch_id', $branchId);
            })
            ->when(auth()->user()->hasRole('sales-head'), function ($query) {
                $query->where('branch_id', auth()->user()->branch_id);
            })
            ->when(auth()->user()->hasRole('head-sales-2'), function ($query) use ($authUser) {
                $userIds = $authUser->getAllReportingUsersIds();
                $users = User::whereIn('id', $userIds)->get();
                foreach ($users as $user) {
                    $branchId[] = $user->branch_id;
                }
                $query->whereIn('branch_id', $branchId);
            })
            ->where('status', 1)
            //->where('id', '!=', 282)
            ->whereNotIn('id', [282, 276, 269])
            ->where('is_individual_tracker', 0)
            ->get();

        if ($type == "team-leader") {
            $allTeams = $teamLeaders->map(function ($item, $key) use ($quarterlyTarget) {
                $teamMembers = User::where('reporting_to', $item->id)->where('status', 1)->get();

                $teamMembers->each(function ($member) use ($quarterlyTarget) {
                    $member->individual_totals = $this->calculateIndividualTotals($quarterlyTarget, $member);
                });

                $item->individual_totals = $this->calculateIndividualTotals($quarterlyTarget, $item);


                $teamTotals = $this->calculateIndividualTotals($quarterlyTarget, null, $item);

                $teamAgreementTotalAmount = $teamTotals['individual_agreement_total_amount'];
                $teamAgreementTotalUnits = $teamTotals['individual_agreement_total_units'];

                // dd($teamMembersWithLeaderIds);
                return [
                    'team_leader' => $item,
                    'team_members' => $teamMembers,
                    'team_total_amount' => $teamAgreementTotalAmount,
                    'team_total_units' => $teamAgreementTotalUnits,
                ];
            });

            $datas = $allTeams->sortByDesc('team_total_amount');


            $reports = [];

            foreach ($datas as $key => $data) {
                $reportItem = [
                    'name' => $data['team_leader']['name'],
                    'agreement_no_of_unit' => round($data['team_total_units']),
                    'agreement_sale_value' => $data['team_total_amount'] > 0 ? round($data['team_total_amount'] / 100000) : 0,
                ];

                $reports[] = $reportItem;
            }
        } else {
            $users = $teamLeaders->map(function ($item, $key) use ($quarterlyTarget) {
                $individual_totals = $this->calculateIndividualTotals($quarterlyTarget, $item);
                $userAgreementTotalAmount = $individual_totals['individual_agreement_total_amount'];
                $userAgreementTotalUnits = $individual_totals['individual_agreement_total_units'];

                return [
                    'name' => $item->name,
                    'units' => $userAgreementTotalUnits,
                    'sale_value' => $userAgreementTotalAmount,
                ];
            });
            $datas = $users->sortByDesc('sale_value');

            $reports = [];

            foreach ($datas as $key => $data) {
                $reportItem = [
                    'name' => $data['name'],
                    'agreement_no_of_unit' => round($data['units']),
                    'agreement_sale_value' => $data['sale_value'] > 0 ? round($data['sale_value'] / 100000) : 0,
                ];

                $reports[] = $reportItem;
            }
        }


        $jsonData = [
            'success' => true,
            'message' => '',
            'data' => [
                'reports' => $reports,
            ],
        ];

        return response()->json($jsonData);
    }


    protected function calculateIndividualTotals($quarterlyTarget, $user = null, $teamLeader = null)
    {
        $individualDsrBooking = DsrBooking::where('quarter', $quarterlyTarget->name)
            ->where('split', 1)
            ->when($teamLeader, function ($query) use ($teamLeader) {
                return $query->where('team_leader_id', $teamLeader->id);
            })
            ->when($user, function ($query) use ($user) {
                return $query->where('sales_person_id', $user->id);
            })
            ->get();

        $individualDsrSplit = DsrSplit::where('quarter', $quarterlyTarget->name)
            ->when($teamLeader, function ($query) use ($teamLeader) {
                return $query->where('team_leader_id', $teamLeader->id);
            })
            ->when($user, function ($query) use ($user) {
                return $query->where('user_id', $user->id);
            })
            ->get();

        $individualTotal = [
            'individual_agreement_total_amount' => 0,
            'individual_agreement_total_units' => 0,
            'individual_booking_total_amount' => 0,
            'individual_booking_total_units' => 0,
            'individual_pending_total_amount' => 0,
            'individual_pending_total_units' => 0,
        ];

        foreach ($individualDsrBooking as $booking) {
            if ($booking->status === 'AGREEMENTED') {
                $sumAmount = $booking->sale_value;
                $individualTotal['individual_agreement_total_amount'] += $sumAmount;

                $sumUnit = 1;

                $individualTotal['individual_agreement_total_units'] += $sumUnit;
            } elseif ($booking->status === 'BOOKING') {
                $sumAmount = $booking->sale_value;
                $individualTotal['individual_booking_total_amount'] += $sumAmount;
                $sumUnit = 1;
                $individualTotal['individual_booking_total_units'] += $sumUnit;
            }

            if ($booking->status === 'PENDING' || $booking->status === 'BOOKING') {
                $sumAmount = $booking->sale_value;
                $individualTotal['individual_pending_total_amount'] += $sumAmount;
                $sumUnit = 1;
                $individualTotal['individual_pending_total_units'] += $sumUnit;
            }
            if ($booking->status === 'AGREEMENTED' && $booking->transferred_quarter === null) {
                $sumAmount = $booking->sale_value;
                $individualTotal['individual_booking_total_amount'] += $sumAmount;
                $sumUnit = 1;
                $individualTotal['individual_booking_total_units'] += $sumUnit;
            }
        }

        foreach ($individualDsrSplit as $split) {
            if ($split->status === 'AGREEMENTED') {
                $sumAmount = $split->amount;
                $individualTotal['individual_agreement_total_amount'] += $sumAmount;

                $sumUnit = 1 / $split->split;

                $individualTotal['individual_agreement_total_units'] += $sumUnit;
            } elseif ($split->status === 'BOOKING') {
                $sumAmount = $split->amount;
                $individualTotal['individual_booking_total_amount'] += $sumAmount;
                $sumUnit = 1 / $split->split;
                $individualTotal['individual_booking_total_units'] += $sumUnit;
            }

            if ($split->status === 'PENDING' || $split->status === 'BOOKING') {
                $sumAmount = $split->amount;
                $individualTotal['individual_pending_total_amount'] += $sumAmount;
                $sumUnit = 1 / $split->split;
                $individualTotal['individual_pending_total_units'] += $sumUnit;
            }
            if ($split->status === 'AGREEMENTED' && $split->transferred_quarter === null) {
                $sumAmount = $split->amount;
                $individualTotal['individual_booking_total_amount'] += $sumAmount;
                $sumUnit = 1 / $split->split;
                $individualTotal['individual_booking_total_units'] += $sumUnit;
            }
        }

        return $individualTotal;
    }
}
