<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Models\Discount;
use App\Models\Order;
use App\Models\Package;
use App\Models\SerialNumberCheck;
use App\Models\User;
use Modules\Admin\app\Http\Requests\DashboardRequest;

class DashboardController extends Controller
{
    public function get()
    {
        try {
            $packageTotal = Package::count();
            $discountTotal = Discount::count();
            $orderTotal = Order::count();
            $clientTotal = User::count();
            $contactTotal = Contact::count();

            return response()->json([
                'data' => [
                    "packages" => $packageTotal,
                    "discounts" => $discountTotal,
                    "orders" => $orderTotal,
                    "clients" => $clientTotal,
                    "contacts" => $contactTotal,
                ],
                'status' => true,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'status' => false,
            ], 500);
        }
    }

    public function statisticSearchSNByMonth(DashboardRequest $request)
    {
        $timezoneOffset = $request->input('timezone_offset', '+00:00');
        $month = $request->input('month', date('M'));
        $year = $request->input('year', date('Y'));
        $timezoneOffsetServer = date('P');
        $selectDateConvert = "CONVERT_TZ(`created_at`, '$timezoneOffsetServer', '$timezoneOffset')";

        $arrCreatedAt = SerialNumberCheck::selectRaw("
            $selectDateConvert AS date_convert,
            created_at
        ")->whereRaw("
            MONTH($selectDateConvert) = $month AND
            YEAR($selectDateConvert) = $year
        ")->groupBy('date_convert')->pluck('created_at');

        $statistic = SerialNumberCheck::whereIn('created_at', $arrCreatedAt)
            ->orderBy('created_at')
            ->get([
                'keyword',
                'status',
                'created_at',
            ])
            ->groupBy(function ($record) use ($timezoneOffset) {
                return $record
                    ->created_at
                    ->setTimezone($timezoneOffset)
                    ->toDateString();
            })
            ->map(function ($records) {
                $countPending = collect($records)
                    ->where('status', SerialNumberCheck::STATUS_PENDING)
                    ->count();
                $countComplete = collect($records)
                    ->where('status', SerialNumberCheck::STATUS_COMPLETE)
                    ->count();
                $countFail = collect($records)
                    ->where('status', SerialNumberCheck::STATUS_FAIL)
                    ->count();

                return [
                    'count' => count($records),
                    'count_pending' => $countPending,
                    'count_complete' => $countComplete,
                    'count_fail' => $countFail,
                ];
            });

        return response()->json([
            'data' => $statistic,
            'status' => true,
        ]);
    }

    public function statisticRevenuesByMonth(DashboardRequest $request)
    {
        $timezoneOffset = $request->input('timezone_offset', '+00:00');
        $month = $request->input('month', date('M'));
        $year = $request->input('year', date('Y'));
        $timezoneOffsetServer = date('P');
        $selectDateConvert = "CONVERT_TZ(`updated_at`, '$timezoneOffsetServer', '$timezoneOffset')";
        $statusCompleted = Order::STATUS_COMPLETED;

        $statisticInMonth = Order::selectRaw("
            DATE_FORMAT($selectDateConvert, '%Y-%m-%d') AS date_convert,
            SUM(total_price) as total_price,
            COUNT(*) as count
        ")->whereRaw("
            MONTH($selectDateConvert) = '$month' AND
            YEAR($selectDateConvert) = '$year' AND
            status = '$statusCompleted'
        ")
            ->groupBy('date_convert')
            ->orderBy('updated_at')
            ->get()
            ->groupBy('date_convert')
            ->map(function ($record) {
                return $record[0];
            });

        return response()->json([
            'data' => $statisticInMonth,
            'status' => true,
        ]);
    }
}
