<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CustomReferralCode;
use Illuminate\Http\Request;
use App\Models\IamPrincipal;
use Illuminate\Support\Facades\DB;
use App\Models\ManageRestaurant;
use App\Models\Subscriptions;
use Carbon\Carbon;
use App\Exports\DashboardExportUser;
use App\Exports\DashboardSelectedExportUser;
use App\Models\ReferralUsers;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;


class DashboardController extends Controller
{
    /**
     * Created By : sayali parab
     * Created at : 16 May 2024
     * Use : To show the dashboard.
     */

    public function showDashboard()
    {


        $dailyData = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("DATE(created_at) as date"))
            ->whereBetween('created_at', [now()->subDays(7), now()]) // Fetch data for the last 7 days
            ->groupBy(DB::raw("DATE(created_at)"))
            ->orderBy(DB::raw("DATE(created_at)"))
            ->pluck('count', 'date')
            ->toArray();
        $customReferralCode =  CustomReferralCode::where('is_active', 1)->first();

        $start_date = now()->subDays(7)->startOfDay();
        $end_date = now()->endOfDay();
        $formattedDailyData = [];
        while ($start_date <= $end_date) {
            $formattedDailyData[$start_date->format('Y-m-d')] = $dailyData[$start_date->format('Y-m-d')] ?? 0;
            $start_date->addDay();
        }

        $defaultData = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("MONTH(created_at) as month"))
            ->whereYear('created_at', date('Y'))
            ->groupBy(DB::raw("MONTH(created_at)"))
            ->orderBy(DB::raw("MONTH(created_at)"))
            ->pluck('count', 'month')
            ->toArray();

        $months = range(1, 12);
        $formattedDefaultData = [];
        foreach ($months as $month) {
            $formattedDefaultData[$month] = $defaultData[$month] ?? 0;
        }

        $quarterlyData = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("QUARTER(created_at) as quarter"))
            ->whereYear('created_at', date('Y'))
            ->groupBy(DB::raw("QUARTER(created_at)"))
            ->orderBy(DB::raw("QUARTER(created_at)"))
            ->pluck('count', 'quarter')
            ->toArray();

        for ($i = 1; $i <= 4; $i++) {
            $quarterlyData[$i] = $quarterlyData[$i] ?? 0;
        }

        ksort($quarterlyData);

        $yearlyData = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("YEAR(created_at) as year"))
            ->groupBy(DB::raw("YEAR(created_at)"))
            ->pluck('count', 'year')
            ->toArray();

        $dataMonthlyWithType3 = IamPrincipal::select(DB::raw("COUNT(*) as count"), DB::raw("MONTH(created_at) as month"))
            ->where('principal_type_xid', 3)
            ->whereYear('created_at', date('Y'))
            ->groupBy(DB::raw("MONTH(created_at)"))
            ->orderBy(DB::raw("MONTH(created_at)"))
            ->pluck('count', 'month')
            ->toArray();

        $dataMonthlyWithType4 = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("MONTH(created_at) as month"))
            ->whereYear('created_at', date('Y'))
            ->groupBy(DB::raw("MONTH(created_at)"))
            ->orderBy(DB::raw("MONTH(created_at)"))
            ->pluck('count', 'month')
            ->toArray();

        $dataMonthlyWithType3 = array_replace(array_fill_keys($months, 0), $dataMonthlyWithType3);
        $dataMonthlyWithType4 = array_replace(array_fill_keys($months, 0), $dataMonthlyWithType4);

        $dataQuarterlyWithType3 = IamPrincipal::select(DB::raw("COUNT(*) as count"), DB::raw("QUARTER(created_at) as quarter"))
            ->where('principal_type_xid', 3)
            ->groupBy(DB::raw("QUARTER(created_at)"))
            ->orderBy(DB::raw("QUARTER(created_at)"))
            ->pluck('count', 'quarter')
            ->toArray();

        $dataQuarterlyWithType4 = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("QUARTER(created_at) as quarter"))
            ->groupBy(DB::raw("QUARTER(created_at)"))
            ->orderBy(DB::raw("QUARTER(created_at)"))
            ->pluck('count', 'quarter')
            ->toArray();

        // Fill missing quarters with zeros
        $quarters = range(1, 4);
        $dataQuarterlyWithType3 = array_replace(array_fill_keys($quarters, 0), $dataQuarterlyWithType3);
        $dataQuarterlyWithType4 = array_replace(array_fill_keys($quarters, 0), $dataQuarterlyWithType4);

        $dataYearlyWithType3 = IamPrincipal::select(DB::raw("COUNT(*) as count"), DB::raw("YEAR(created_at) as year"))
            ->where('principal_type_xid', 3)
            ->groupBy(DB::raw("YEAR(created_at)"))
            ->pluck('count', 'year')
            ->toArray();

        $dataYearlyWithType4 = Subscriptions::select(DB::raw("COUNT(*) as count"), DB::raw("YEAR(created_at) as year"))
            ->groupBy(DB::raw("YEAR(created_at)"))
            ->pluck('count', 'year')
            ->toArray();

        $customerCount = IamPrincipal::where('principal_type_xid', 3)->count();
        $restaurantCount = ManageRestaurant::where('is_active', 1)->count();
        $formattedDateTime = now()->format('Y-m-d H:i:s');

        $recent_transactions = Subscriptions::with('subscription')
            ->orderBy('id', 'desc')
            ->get();

        $formatted_transactions = $recent_transactions->map(function ($transaction) {
            return [
                'id' => $transaction->id,
                'subscription' => $transaction->subscription ? [
                    'first_name' => $transaction->subscription->first_name,
                    'last_name' => $transaction->subscription->last_name,
                    'id' => $transaction->subscription->id,
                ] : null,
                'amount' => $transaction->amount,
                'subscription_id' => $transaction->subscription_id,
                'stripe_customer_id' => $transaction->stripe_customer_id,
                'status' => $transaction->status,
                'current_period_start' => $transaction->current_period_start ? Carbon::parse($transaction->current_period_start)->format('m/d/Y') : null,
                'current_period_end' => $transaction->current_period_end ? Carbon::parse($transaction->current_period_end)->format('m/d/Y') : null,
                'next_payment_date' => $transaction->next_payment_date ? Carbon::parse($transaction->next_payment_date)->format('m/d/Y') : null,
            ];
        })->toArray();

        $response = ReferralUsers::with(['referredUser', 'refeersUser'])->latest()->get()->toArray();

        $referralData = [];

        foreach ($response as $item) {
            $principalId = $item['iam_principal_xid'];

            if (!isset($referralData[$principalId])) {
                $referralData[$principalId] = [
                    'referred_user' => $item['referred_user'],
                    'refeers_users' => []
                ];
            }

            // Add the refeers_user to the respective principalId
            if (isset($item['refeers_user'])) {
                $referralData[$principalId]['refeers_users'][] = $item['refeers_user'];
            }
        }

        return view(
            'Admin.dashboard',
            compact(
                'customReferralCode',
                'customerCount',
                'restaurantCount',
                'dataMonthlyWithType3',
                'dataMonthlyWithType4',
                'dataQuarterlyWithType3',
                'dataQuarterlyWithType4',
                'dataYearlyWithType3',
                'dataYearlyWithType4',
                'formatted_transactions',
                'dailyData',
                'formattedDailyData',
                'defaultData',
                'formattedDefaultData',
                'quarterlyData',
                'yearlyData',
                'referralData'
            )
        );
    }

    /*
            Created By : Hritik
            Created at : 02 Aug 2024
            Use : To Store or Update Custom Referral Code
            */





    public function createOrUpdateReferralCode(Request $request)
    {
        try {

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

            DB::beginTransaction();
            if($request->id){
                CustomReferralCode::where('id', $request->id)->update([
                    'referral_code' => $request->referral_code,
                ]);
            }else{
            CustomReferralCode::create([
                'referral_code' => $request->referral_code,
            ]);
        }
            DB::commit();
            return response()->json(['status_code' => 200]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Storing Referral Code function failed: ' . $e->getMessage());
            return response()->json(['error' => 'Something went wrong while storing Data.', 'status_code' => 500], 500);
        }
    }

    /*
        Created By : Sayali Parab
        Created at : 08 July 2024
        Use : To Get Excel.
        */


    // public function exportRecentTransactions(Request $request)
    // {
    //     try {
    //         if ($request->has('all_id')) {
    //             $recentTransaction = Subscriptions::with('subscription')->get()->toArray();
    //             return Excel::download(new DashboardExportUser($recentTransaction), 'recent_transactions.xlsx');
    //         }

    //         $ids = $request->input('selected_id');
    //         $fileName = 'selected_customer_transaction_data.xlsx';
    //         return Excel::download(new DashboardSelectedExportUser($ids), $fileName);
    //     } catch (\Exception $e) {
    //         return response()->json(['error' => 'Export failed. Something went wrong.'], 500);
    //     }
    // }


    public function exportRecentTransactions(Request $request)
    {
        try {
            if ($request->has('all_id')) {
                $recentTransaction = Subscriptions::with(['iamPrincipal', 'subscriptionProduct'])->get()->toArray();
                return Excel::download(new DashboardExportUser($recentTransaction), 'recent_transactions.xlsx');
            }

            $ids = $request->input('selected_id');
            if (!is_array($ids)) {
                $ids = explode(',', $ids);
            }
            $fileName = 'selected_customer_transaction_data.xlsx';
            return Excel::download(new DashboardSelectedExportUser($ids), $fileName);
        } catch (\Exception $e) {
            Log::error("Export Failed " . $e->getMessage());
            return response()->json(['error' => 'Export failed. Something went wrong.'], 500);
        }
    }



     /*
    Created By : Sayali parab
    Created at : 07 June 2024
    Use : To get the page.
    */

    public function index()
    {
        $referralCodes = CustomReferralCode::orderBy('id', 'desc')->get();
        // return $location;
        return view('Admin.pages.manage_referral_codes.index', compact('referralCodes'));
    }
    /*
    Created By : Sayali parab
    Created at : 07 June 2024
    Use : To store the location.
    */


    public function store(Request $request)
    {
        // dd($request);
        $request->validate([
            'referral_code' => 'required|string|max:15',

        ]);

        try {
            if (CustomReferralCode::where('referral_code', $request->referral_code)->exists()) {
                return response()->json(['success' => false, 'error' => 'Referral Code name already exists', 'status' => 422]);
            }

            // new location
            $storeCode = new CustomReferralCode();
            $storeCode->referral_code = $request->referral_code;
            $storeCode->save();



            return response()->json(['success' => true, 'status' => 200]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'error' => $e->getMessage(), 'status' => 500]);
        }
    }




    /*
    Created By : Sayali parab
    Created at : 07 June 2024
    Use : To change status.
    */
    public function change_referral_code_status(Request $request)
    {

        try {
            // dd($request->all());
            DB::beginTransaction();
            $status = CustomReferralCode::find($request->referral_id);
            $status->is_active = $request->status;
            $status->save();
            // return response()->json(['status' => 200]);
            DB::commit();

            return jsonResponseWithSuccessMessage(__('success.update_data'));
        } catch (\Exception $e) {
            Log::error("Update Status function Load Failed " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }


    /*
    Created By : Sayali parab
    Created at : 07 June 2024
    Use : To delete location.
    */
    public function delete_referral_code($id)
    {


        try {
            DB::beginTransaction();

            $passport = CustomReferralCode::find($id);
            $passport->delete();

            DB::commit();

            return response()->json(['success' => true, 'status' => 200]);
        } catch (\Exception $e) {
            DB::rollBack();
           Log::error("delete_location function Load Failed " . $e->getMessage());
            return response()->json(['success' => false, 'status' => 500, 'message' => __('auth.something_went_wrong')]);
        }
    }


    /*
    Created By : Sayali parab
    Created at : 07 June 2024
    Use : To update location.
    */



   public function update_referral_code(Request $request)
{
    try {
        DB::beginTransaction();

        // Find the location data
        $updateReferralCode = CustomReferralCode::find($request->id);
        if (!$updateReferralCode) {
            return response()->json(['success' => false, 'error' => 'Referral Code not found', 'status' => 404]);
        }

        // Update the location data
        $updateReferralCode->referral_code = $request->referral_code;
        $updateReferralCode->save();


        DB::commit();

        return response()->json(['success' => true, 'message' => __('success.update_data'), 'status' => 200]);
    } catch (\Exception $e) {
        DB::rollBack();
        Log::error("Failed to update Code: " . $e->getMessage());
        return response()->json(['success' => false, 'error' => __('auth.something_went_wrong'), 'status' => 500]);
    }
}




}
