<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Device;
use Illuminate\Http\Request;

class MobileStockController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $query = Device::query();

        /*
        |--------------------------------------------------------------------------
        | Sales Stock
        |--------------------------------------------------------------------------
        */
        if ($user->hasRole('Sales')) {

            $query->where('status', 'sales_stock')
                ->where(
                    'sales_user_id',
                    $user->id
                );
        }

        /*
        |--------------------------------------------------------------------------
        | Border Stock
        |--------------------------------------------------------------------------
        */ elseif ($user->hasRole('Border Staff')) {

            $query->where('status', 'border_stock')
                ->where(
                    'border_station_id',
                    $user->border_station_id
                );
        }

        if ($request->filled('search')) {

            $query->where(
                'serial_number',
                'like',
                '%' . $request->search . '%'
            );
        }

        $devices = $query
            ->orderBy('serial_number')
            ->get();

        return response()->json([
            'success' => true,
            'total'   => $devices->count(),
            'devices' => $devices,
        ]);
    }
}
