<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller as ExController;
use App\Services\Dashboard\Stat\StatService;
use App\Models\User;
use App\Models\Order;
use App\Models\Billing;
use App\Models\Product;
use App\Helpers\DashboardStatic;
use Akaunting\Apexcharts\Chart;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;

class Controller extends ExController
{
    public function index(Request $request)
    {
        $daysToShow = 30;
        $from = $request->get('from');
        $to = $request->get('to');

        if (!$to) {
            $to = now()->format('Y-m-d');
        }

        if (!$from) {
            $from = now()->subDays($daysToShow)->format('Y-m-d');
        }

        $service = new StatService();

        // Create a new chart instance
        $chart = new Chart();

        // Set the chart type to 'line'
        $chart->setType('line');

        // Define the X-axis labels (months, dates, etc.)
        $chart->setLabels($service->getLabels($from, $to));

        // Add a dataset to the chart (e.g., sales data)
        $chart->setDataset('Orders', 'line', $service->getStatics('orders'));
        $chart->setDataset('Users', 'line', $service->getStatics('users'));
        $chart->setDataset('Sales', 'line', $service->getStatics('sales'));

        $users = User::count();
        $orders = Order::where('payment_type', '!=', 'credit')->count();
        $products = Product::where('child_id', null)->count();
        $billing = Billing::where('status', 'payed')->count();

        $statics = [
            'labels' => $this->getLabels(),
            'orders_count' => $this->getStatics(),
            'new_users' => $this->getUserStatics(),
            'transactions' => $this->getCountTransactions(),
            'sum' => $this->getAllSumStatic(),
        ];

        return view('dashboard.index', compact(
            'users',
            'orders',
            'products',
            'billing',
            'statics',
            'chart'
        ));
    }

    private function getLabels()
    {
        $start = now()->subDays(30);
        $days = [];
        for ($i = 0; $i <= 30; $i++) {
            $days[] = $start->copy()->addDays($i)->format('d.m');
        }
        return $days;
    }

    private function getUserStatics()
    {
        $users = DashboardStatic::getUserStatics();

        return [
            'data' => [
                [
                    'name' => 'Пользователи',
                    'values' => $users
                ]
            ]
        ];
    }

    public function changeLang($lang)
    {
        // validate
        if (!in_array($lang, ['en', 'ru', 'uz'])) {
            return response()->json([
                'message' => 'Language not supported'
            ], Response::HTTP_BAD_REQUEST);
        }

        session()->put('locale', $lang);
        App::setLocale($lang);

        return redirect()->back();
    }

    private function getStatics()
    {
        $processing = DashboardStatic::getCountProcessing();
        $collect = DashboardStatic::getCountCollected();
        $waiting = DashboardStatic::getCountInWay();
        $closed = DashboardStatic::getCountClosed();
        $cancelled = DashboardStatic::getCountCancelled();
        $replacement = DashboardStatic::getCountReplacement();
        $archived = DashboardStatic::getCountArchived();

        return [
            'data' => [
                [
                    'name' => 'В обработке',
                    'values' => $processing
                ],

                [
                    'name' => 'Собран',
                    'values' => $collect
                ],

                [
                    'name' => 'Ожидает',
                    'values' => $waiting
                ],

                [
                    'name' => 'Закрыт',
                    'values' => $closed
                ],

                [
                    'name' => 'Отменен',
                    'values' => $cancelled
                ],

                [
                    'name' => 'Замена',
                    'values' => $replacement
                ],

                [
                    'name' => 'Архиве',
                    'values' => $archived
                ],
            ]
        ];
    }

    private function getCountTransactions()
    {
        $payed = DashboardStatic::getSuccessTransactions();
        $waiting = DashboardStatic::getWaitingTransactions();
        $refused = DashboardStatic::getRefusedTransactions();

        return [
            'data' => [
                [
                    'name' => 'Оплачено',
                    'values' => $payed
                ],
                [
                    'name' => 'В ожидания',
                    'values' => $waiting
                ],

                [
                    'name' => 'Отказано',
                    'values' => $refused
                ],
            ]
        ];
    }

    private function getCountCredit()
    {
        $payed = DashboardStatic::getCreditPayed();
        $cancelled = DashboardStatic::getCancelledCredit();
        $review = DashboardStatic::getReviewCredit();
        $waiting = DashboardStatic::getWaitingCredit();

        return [
            'data' => [
                [
                    'name' => 'Оплачено',
                    'values' => $payed
                ],
                [
                    'name' => 'Отказано',
                    'values' => $cancelled
                ],
                [
                    'name' => 'Рассмотрение',
                    'values' => $review
                ],
                [
                    'name' => 'В ожидание',
                    'values' => $waiting
                ]
            ]
        ];
    }

    private function getAllSumStatic()
    {
        return [
            'data' => [
                [
                    'name' => 'Оплачено',
                    'values' => []
                ],
                [
                    'name' => 'Не оплачено',
                    'values' => []
                ],

                [
                    'name' => 'Отказано',
                    'values' => []
                ],
            ]
        ];
    }
}
