<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $summaryPrice = DB::table('auto_orders')
            ->whereNotNull('cost')
            ->sum('cost')
            + DB::table('estate_orders')
            ->whereNotNull('cost')
            ->sum('cost');

        $autoOrders = DB::table('auto_orders')->count();
        $estateOrders = DB::table('estate_orders')->count();

        $recentOrders = DB::table('auto_orders')
            ->selectRaw('*, ordered_customer as customer')
            ->latest()->limit(10)->get()
            ->map(fn($o) => (object)array_merge((array)$o, ['type' => 'auto_']));

        $forModerate = collect(
            DB::table('auto_orders')->selectRaw('*, ordered_customer as customer')->where('status', 'moderated')->latest()->limit(10)->get()->map(fn($o) => (object)array_merge((array)$o, ['type' => 'auto_']))
        )->merge(
            DB::table('estate_orders')->selectRaw('*, ordered_customer as customer')->where('status', 'moderated')->latest()->limit(10)->get()->map(fn($o) => (object)array_merge((array)$o, ['type' => 'estate_']))
        )->sortByDesc('updated_at')->take(10)->values();

        $actions = DB::table('tracking_actions')->latest()->limit(20)->get();

        $appraiserChart = [[], []];
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->get();
        foreach ($appraisers as $appraiser) {
            $appraiserChart[0][] = $appraiser->name;
            $count = DB::table('order_members')->where('user_id', $appraiser->id)->count();
            $appraiserChart[1][] = $count;
        }

        return view('index', compact(
            'summaryPrice',
            'autoOrders',
            'estateOrders',
            'recentOrders',
            'forModerate',
            'actions',
            'appraiserChart'
        ));
    }

    public function lang($locale)
    {
        session()->put('locale', $locale);
        return redirect()->back();
    }

    public function pages($any = null)
    {
        return view('pages.index');
    }
}
