<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Lib\ApiAuthHelper;
use App\Models\Category;
use App\Models\Invoice;

use App\Models\User;
use Illuminate\Http\Request;
use Mockery\Exception;
use MongoDB\Driver\Exception\ExecutionTimeoutException;


class InvoiceController extends Controller
{
    use ApiAuthHelper;
    public function getUserInvoices(Request $request)
    {
        $currentUserId = $request->id;

        $categories = Category::all();

        $invoices = [];

        try {
            foreach ($categories as $category) {

                $invoices[$category->slug] = Invoice::orderBy('updated_at', 'desc')
                    ->where('user_id', $currentUserId)
                    ->where('category_id', $category->id)
                    ->limit(20)
                    ->get()
                    ->reverse();
                $invoices['images'][$category->slug] = $category->categoryImage;
            }
            return response($invoices);

        } catch (ExecutionTimeoutException $e) {
            return response()->json($e);
        }
    }

    public function getLastUserInvoices(Request $request, $count)
    {
        $user = User::find($request->id);

        $invoices =  Invoice::orderBy('updated_at', 'desc')
            ->where('user_id', $user->id)
            ->limit($count)
            ->get()
            ->reverse();
        foreach ($invoices as $invoice) {
             $invoice->category;
        }
       return response()->json($invoices);
    }

    public function show($id)
    {
        try {
            $invoice = Invoice::find($id);
            $invoice->categoryName = $invoice->category->name;

            return response()->json($invoice);
        } catch (Exception $e) {
            return $this->apiResponse(true, $e->getMessage(), ['Не удалось получить счет '. $id], null, null, 500);
        }
    }

    public function setVisited($id)
    {
        $invoice = Invoice::find($id);
        $invoice->visited = true;
        $invoice->save();
    }
}
