<?php

namespace App\Repositories;

use App\Models\User;
use App\Models\Dashboard;

class DashboardRepository
{
    public function store($request)
    {
        $data      = $request->validated();
        $dashboard = Dashboard::create(
            [
                'user_id' => auth()->user()->user_ID,
                'name'    => $data['dashboard_name'],
                'title'   => $data['dashboard_title'],
                'icon'    => $data['dashboard_icon'],
                'url'     => "",
                'order'   => $this->getLastOrder(auth()->user()->user_ID) + 1
            ]
        );

        $dashboard->update(["url" => route('dashboards.show', $dashboard->id)]);
    }

    public function update($request, $dashboard)
    {
        $data = $request->validated();

        $dashboard->update([
            'name'  => $data['dashboard_name'],
            'icon'  => $data['dashboard_icon'],
            'title' => $data['dashboard_title']
        ]);

    }

    public function moveUp($dashboard)
    {
        $previousDashboard = Dashboard::where('user_id', intval($dashboard->user_id))
            ->where('order', '<', $dashboard->order)
            ->orderBy('order', 'desc')
            ->first();

        if ($previousDashboard) {

            $currentDashboard         = $dashboard->order;
            $dashboard->order         = $previousDashboard->order;
            $previousDashboard->order = $currentDashboard;

            $dashboard->save();
            $previousDashboard->save();

        }

    }

    public function moveDown($dashboard)
    {
        $nextDashboard = Dashboard::where('user_id', $dashboard->user_id)
            ->where('order', '>', $dashboard->order)
            ->orderBy('order', 'asc')
            ->first();

        if ($nextDashboard) {

            $currentDashboard     = $dashboard->order;
            $dashboard->order     = $nextDashboard->order;
            $nextDashboard->order = $currentDashboard;

            $dashboard->save();
            $nextDashboard->save();
        }

    }

    public function destory($dashboard)
    {
        $dashboard->delete();

    }

    private function getLastOrder($userId)
    {
        $lastOrder = Dashboard::where('user_id', $userId)->max('order');

        if (is_null($lastOrder)) {
            $lastOrder = 0;
        }

        return $lastOrder;
    }

    public function getRecentDashboard()
    {

// dd(auth()->user()->user_ID);
        // dd(Dashboard::where('user_id', 1)->first());
        return Dashboard::where('user_id', auth()->user()->user_ID)->first();
    }

}