<?php

namespace App\Services\WS;

use App\Models\WS\Contact;
use App\Traits\DataTable;
use Exception;
use Illuminate\Support\Facades\Storage;

class ContactUsService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private Contact $contact)
    {
        //
    }

    public function dataTable()
    {
        return $this->generate($this->contact->query());
    }

    public function create($data): Contact
    {
        $maps = $data->maps;
        return $this->contact->create([
            'email'     => $data->email,
            'phone'     => $data->phone,
            'address'   => $data->address,
            'lat'       => @$maps['lat'],
            'long'      => @$maps['lng'],
            'location'  => @$maps['location']
        ]);
    }

    public function count()
    {
        return $this->contact->count();
    }

    public function detail($id)
    {
        $contact = $this->contact->findOr($id, fn () => throw new Exception("Data not found"));
        $contact->maps = ['lat' => floatval($contact->lat), 'lng' => floatval($contact->long), 'address' => $contact->location];
        return $contact;
    }

    public function update($id, $data)
    {
        $contact    = $this->contact->findOr($id, fn () => throw new Exception("Row not found"));
        $maps       = $data->maps;
        $contact->update([
            'email'     => $data->email,
            'phone'     => $data->phone,
            'address'   => $data->address,
            'lat'       => @$maps['lat'],
            'long'      => @$maps['lng'],
            'location'  => @$maps['location']
        ]);

        return $contact;
    }
}
