<?php
namespace App\Helpers;

use App\Invoice;
use App\LoopGroupUserPaid;
use Carbon\Carbon;
use Carbon\CarbonPeriod;

/**
* Class based Helper to get loop user details
*/
class LoopDetails
{

    /**
     * Helper to upload and resize Images
     * @param $loopDetails
     * @return array
     */
    public static function loopUserInfo($loopDetails= [])
    {
        $subscribeDate= [
            'subscribe_date' => date('F d, Y', strtotime($loopDetails['created_at'])),
            'subscribe_time' => date('h:i A', strtotime($loopDetails['created_at'])),
        ];

        // Finantial Info.

        $totalShare= $loopDetails['share'] * $loopDetails['period'];
        $loopGroupUserId= $loopDetails['loop_group_user_id'];
        $encashMentDate = Carbon::createFromFormat('Y-m-d', $loopDetails['encashment_month']);
        $from = Carbon::createFromFormat('Y-m-d', $loopDetails['loop_date']);
        $monthIndex = $encashMentDate->diffInMonths($from);
        $loopSettings= json_decode($loopDetails['setting'], true);

        //Fees
        $fees= ['managment_fees'=> 0, 'vat_fees'=> 0, 'government_fees'=> 0];
        $invoiceDetails= Invoice::where('loop_group_user_id', $loopGroupUserId)->where('meta->type', 'subscribe')->first();
        $feesKeys= ["vat_fees", "managment_fees", "government_fees"];
        // foreach ($invoiceDetails->meta as $key => $value) {
        //     if (in_array($key, $feesKeys)) {
        //         $fees[$key] = $value;
        //     }
        // }
        foreach ($feesKeys as $key) {
            $fees[$key] = $invoiceDetails->meta[$key] ?? 0;
        }
        $totalFees= ceil(array_sum($fees));
        // dd($totalFees, $totalShare, $fees);
        $totalEarned= $totalShare - $totalFees;

        // Paids for this loop
        // 1- Paid Months

        // $paidMonth= LoopGroupUserPaid::where('loop_group_user_id', $loopGroupUserId)->get()->pluck('month')->toArray();
        $paidMonthQuery= LoopGroupUserPaid::where('loop_group_user_id', $loopGroupUserId)->get()->toArray();
        $paidMonth= [];
        $uncompeletedPaidMonths= [];
        foreach ($paidMonthQuery as $value) {
            $paidMonth[]= $value['month'];
            if (!$value['done']) {
                $uncompeletedPaidMonths[]= $value['month'];
            }
        }
        // 2- unpaid Months
        // $loopDetails['period']=1;
        // 2.1- check if the loop has not closed, by comparing the current month with the last date of the loop
        $loopEndDate= $from->addMonths($loopDetails['period'] - 1);
        $currentDate= Carbon::now();

        // dd($from, $loopEndDate , Carbon::now());
        $endDate=  $loopEndDate < Carbon::now() ? $loopEndDate : $currentDate;
        $closed=  $loopEndDate < Carbon::now() || $loopDetails['status'] == 'cancelled' ? true : false;
        $cashed=  $encashMentDate < Carbon::now() ? true : false;
        // dd($cashed);
        // 2.2- get list of months between the current month and the last paid month

        $period = CarbonPeriod::create($loopDetails['loop_date'], '1 month', $endDate);

        $unPaidMonths= [];
        foreach ($period as $dt) {
            if ( ! in_array( $dt->format('m') , $paidMonth) ) {
                $unPaidMonths[] = intval($dt->format('m'));
            }
            // echo $dt->format("Y-m") . "<br>\n";
        }
        // dd( $loopDetails['loop_date'], $endDate->format('Y-m-d'), $unPaidMonths);
        // Loop Months
        $period = CarbonPeriod::create($loopDetails['loop_date'], '1 month', $loopEndDate);

        $loopMonths= [];
        foreach ($period as $dt) {
            // echo $dt->format("Y-m") . "<br>\n";
            $loopMonths[] = intval($dt->format('m'));
        }
        // dd($paidMonth, $unPaidMonths, $loopMonths);
        // dd($paids);
        // Set Months
        $months= [];

        for ($i=1; $i <=12 ; $i++) {
            if ( in_array( $i, $uncompeletedPaidMonths ) ) {
                $class="false";
                $image="close.svg";
            } elseif ( in_array( $i, $paidMonth ) ) {
                $class="true";
                $image="true.svg";
            } elseif ( in_array( $i, $unPaidMonths ) ) {
                $class="false";
                $image="close.svg";
            } elseif ( $i == intval( $encashMentDate->format('m') ) ) {
                $class="star";
                $image="star.svg";
            } elseif ( in_array( $i, $loopMonths ) ) {
                $class="enable";
                $image="add.svg";
            } else {
                $class='disable';
                $image="add.svg";
            }
            $months[] = [
                'month' => date("M", mktime(0, 0, 0, $i, 1)),
                'class' => $class,
                'image' => $image
            ];
        }

        $encashMentDate= $encashMentDate->format('F d, Y');

        $data = compact('loopDetails', 'closed', 'cashed', 'subscribeDate', 'encashMentDate',  'totalShare', 'fees', 'totalFees', 'months' , 'loopMonths', 'paidMonth', 'uncompeletedPaidMonths', 'unPaidMonths');
        // dd($data);
        return $data;
    }

}
