<?php

namespace App\Http\Controllers\Api\V1\User;

use Carbon\CarbonPeriod;
use App\Models\User;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Constants\GlobalConst;
use App\Http\Helpers\Response;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Constants\PaymentGatewayConst;
use App\Models\UserHasInvestPlan;
use App\Providers\Admin\CurrencyProvider;
use Illuminate\Support\Carbon;
use App\Http\Helpers\Api\Helpers as ApiResponse;
use App\Models\ParlourBooking;

class DashboardController extends Controller
{
    public function dashboard() {
        $default_currency = CurrencyProvider::default();
        $total_transactions             = ParlourBooking::auth()->with(['parlour','schedule','payment_gateway','user'])->count();
        $total_online_transactions      = ParlourBooking::auth()->whereNot('payment_method',GlobalConst::CASH_PAYMENT)->with(['parlour','schedule','payment_gateway','user'])->count();
        $total_cash_transactions        = ParlourBooking::auth()->where('payment_method',GlobalConst::CASH_PAYMENT)->with(['parlour','schedule','payment_gateway','user'])->count();
        $total_transactions_amount_get     = ParlourBooking::auth()->where('payment_method',GlobalConst::CASH_PAYMENT)->with(['parlour','schedule','payment_gateway','user'])->sum('price');
        $total_transactions_amount       = (int) $total_transactions_amount_get;
        // Transaction logs
        $transactions = Transaction::auth()->latest()->take(10)->get();
        $transactions->makeHidden([
            'id',
            'user_type',
            'user_id',
            'wallet_id',
            'payment_gateway_currency_id',
            'request_amount',
            'exchange_rate',
            'percent_charge',
            'fixed_charge',
            'total_charge',
            'total_payable',
            'receiver_type',
            'receiver_id',
            'available_balance',
            'payment_currency',
            'input_values',
            'details',
            'reject_reason',
            'remark',
            'stringStatus',
            'callback_ref',
            'updated_at',
        ]);

        // Chart Data
        $monthly_day_list = CarbonPeriod::between(now()->startOfDay()->subDays(30),today()->endOfDay())->toArray();
        $define_day_value = array_fill_keys(array_values($monthly_day_list),"0.00");

        // User Information
        $user_info = auth()->user()->only([
            'id',
            'firstname',
            'lastname',
            'fullname',
            'username',
            'email',
            'image',
            'mobile_code',
            'mobile',
            'full_mobile',
            'email_verified',
            'two_factor_verified',
            'two_factor_status',
            'two_factor_secret',
        ]);

        $profile_image_paths = [
            'base_url'          => url("/"),
            'path_location'     => files_asset_path_basename("user-profile"),
            'default_image'     => files_asset_path_basename("profile-default"),
        ];

        // Chart Data
        $add_money_record = Transaction::where('type',PaymentGatewayConst::PAYMENTMETHOD)
                            ->whereBetween('created_at',[now()->subDays(30),today()->endOfDay()])
                            ->where('user_type',GlobalConst::USER)
                            ->where('user_id',auth()->user()->id)
                            ->select([
                                DB::raw('DATE(created_at) as date'),
                                DB::raw("(sum(receive_amount)) as total_amount"),
                            ])
                            ->groupBy('date')
                            ->pluck("total_amount","date")
                            ->toArray();


        foreach($define_day_value as $timestamp => $value) {

            $payments[$timestamp]['timestamp']  = $timestamp;
            $payments[$timestamp]['value']      = $value;


            // add money record
            foreach($add_money_record as $date => $amount) {
                if(Carbon::parse($timestamp)->toDateString() == Carbon::parse($date)->toDateString()) {
                    $payments[$timestamp]['value']  = (string) $amount;
                }
            }



        }

        return Response::success([__('User dashboard data fetch successfully!')],[
            'instructions'  => [
                'transaction_types' => [
                    PaymentGatewayConst::PAYMENTMETHOD,
                ],
                'recent_transactions'   => [
                    'status'        => '1: Success, 2: Pending',
                ],
            ],

            'user_info'     => $user_info,
            'recent_transactions'   => $transactions,
            'chart_data'        => [
                'payments'      => array_values($payments),
            ],
            'total_transactions'    =>$total_transactions,
            'total_online_transactions' =>$total_online_transactions,
            'total_cash_transactions'   =>$total_cash_transactions,
            'total_transactions_amount' =>$total_transactions_amount,
            'profile_image_paths'   => $profile_image_paths,
            'profile_image_paths'   => $profile_image_paths,
        ]);
    }

    public function notifications() {
        $vendor_id = auth()->user()->id;
        $image_paths = [
            'base_url'          => url("/"),
            'path_location'     => files_asset_path_basename("site-section"),
            'default_image'     => files_asset_path_basename("default"),
        ];
        $notifications  = ParlourBooking::where('user_id', $vendor_id)->with('parlour')->latest()->take(5)->get();


        $message =  ['success'=>[__('Notification data  fetch successfully!')]];
        $data = [
            'image_path'        => $image_paths,
            'notification_data' => $notifications,

        ];
        return ApiResponse::success($message,$data);

    }
}
