<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Supplier;
use App\User;

class SupplierController extends Controller
{
    public function getSuppliers(Request $request)
    {
        $key = $request->query('key');

        $user = User::where('id_session', $key)->first();

        if (!$user) {
            return response()->json([
                'status'  => 'true',
                'errCode' => '00',
                'msg'     => 'User Not Found'
            ]);
        }

        $masterUser = User::where('phone_number', $user->master)->first();

        if (!$masterUser) {
            return response()->json([
                'status'  => 'true',
                'errCode' => '00',
                'msg'     => 'Master User Not Found'
            ]);
        }

        $suppliers = Supplier::where('user', $masterUser->phone_number)
                            ->where('active', '0')
                            ->get();

        if ($suppliers->isEmpty()) {
            return response()->json([
                'status'  => 'true',
                'errCode' => '02',
                'msg'     => 'No Supplier'
            ]);
        }

        return response()->json([
            'status'  => 'true',
            'errCode' => '01',
            'msg'     => 'Success',
            'data'    => $suppliers->map(function ($supplier) {
                return [
                    'id_supplier'   => $supplier->id_supplier,
                    'name_supplier' => $supplier->name_supplier,
                    'email'         => $supplier->email,
                    'telephone'     => $supplier->telephone,
                    'address'       => $supplier->address,
                    'profinsi'      => $supplier->profinsi,
                    'kota'          => $supplier->kota,
                ];
            })
        ]);
    }
}
