GOOD SHELL MAS BOY
Server: Apache/2.4.52 (Ubuntu)
System: Linux vmi1836763.contaboserver.net 5.15.0-130-generic #140-Ubuntu SMP Wed Dec 18 17:59:53 UTC 2024 x86_64
User: www-data (33)
PHP: 8.4.10
Disabled: NONE
Upload Files
File: /var/www/html/app/Livewire/Gig/Add.php
<?php

namespace App\Livewire\Gig;

use Livewire\Component;
use Illuminate\Support\Str;
use Livewire\WithFileUploads;
use App\Services\ApiEndpoints;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

class Add extends Component
{
    use WithFileUploads;

    public $subcategory_id;
    public $shop_id;
    public $user_id;
    public $category_id;
    public $title;
    public $price;
    public $delivery_number;
    public $description;
    public $portfolio;
    public $requirement;
    public $image_urls;

    public $formattedPrice;
    public $currency;
    public $delivery_unit = 'day'; // Default time unit

    protected $rules = [
        'subcategory_id' => 'required|exists:categories,id',
        'shop_id' => 'required|exists:shops,id',
        'user_id' => 'required|exists:users,id',
        'category_id' => 'required|exists:categories,id',
        'title' => 'required|string|max:100',
        'price' => 'required|string|min:0',
        'delivery_number' => 'required|string',
        'delivery_unit' => 'nullable|string|in:minutes,hours,days,weeks,months,years',
        'description' => 'required|string|max:1000',
        'portfolio' => 'nullable|url',
        'requirement' => 'nullable|string',
        'image_urls.*' => 'nullable|image|mimes:jpg,jpeg,png|max:1024',
    ];

    protected $messages = [
        'subcategory_id.required' => 'Please select a subcategory.',
        'subcategory_id.exists' => 'The selected subcategory is invalid.',

        'shop_id.required' => 'Please select a shop.',
        'shop_id.exists' => 'The selected shop is invalid.',

        'user_id.required' => 'A user must be associated with this service.',
        'user_id.exists' => 'The selected user is invalid.',

        'category_id.required' => 'Please select a category.',
        'category_id.exists' => 'The selected category is invalid.',

        'title.required' => 'Please provide a title for your service.',
        'title.string' => 'The title must be a valid string.',
        'title.max' => 'The title should not exceed 100 characters.',

        'price.required' => 'Please provide a price for your service.',
        'price.string' => 'The price must be a valid string.',
        'price.min' => 'The price must be a positive number.',

        'delivery_number.required' => 'Please specify the delivery time.',
        'delivery_number.string' => 'The delivery time must be a valid string.',

        'delivery_unit.string' => 'The delivery unit must be a valid string.',
        'delivery_unit.in' => 'The delivery unit must be one of the following: minutes, hours, days, weeks, months, or years.',

        'description.required' => 'Please provide a description of your service.',
        'description.string' => 'The description must be a valid string.',
        'description.max' => 'The description should not exceed 1000 characters.',

        'portfolio.url' => 'The portfolio URL must be a valid URL.',

        'requirement.string' => 'The requirements field must be a valid string.',

        'image_urls.*.image' => 'Each uploaded image must be an image file.',
        'image_urls.*.mimes' => 'Images must be in jpg, jpeg, or png format.',
        'image_urls.*.max' => 'Each image should not exceed 1MB.',
    ];

    public function mount()
    {
        $shop = Session::get('shop');
        if ($shop) {
            $this->shop_id = $shop['id'] ?? [];
            $this->user_id = $shop['user_id'];
            $this->category_id = $shop['category_id'];

            $country = $shop['country_id'];
            $this->currency = DB::table('countries')->where('id', $country)->value('symbol');
            $this->formattedPrice = $this->formatPrice($this->price);
        } else {
            Session::flash('error', 'Add your shop to continue');
        }
    }

    public function updatedPrice($value)
    {
        $this->formattedPrice = $this->formatPrice($value);
    }

    public function formatPrice($value)
    {
        // Ensure the value is numeric before formatting
        if (is_numeric($value)) {
            return number_format((float)$value, 0, '.', ',');
        }
        return $value;
    }


    public function addService()
    {
        try {
            $this->validate();


            $image_urls = [];
            $image_public_ids = [];

            if ($this->image_urls) {
                // Check that the number of images does not exceed the limit
                if (count($this->image_urls) > 4) {
                    $this->addError('image_urls', 'You can upload a maximum of 4 images.');
                }
                // Handle image uploads
                if ($this->image_urls) {
                    foreach ($this->image_urls as $photo) {
                        $uploadedPhoto = $photo->getRealPath();
                        $uploadResult = cloudinary()->upload($uploadedPhoto, ['folder' => 'gigPhotos']);
                        $image_urls[] = $uploadResult->getSecurePath();
                        $image_public_ids[] = $uploadResult->getPublicId();
                    }
                }
            }

            $body = [
                'user_id' => $this->user_id,
                'shop_id' => $this->shop_id,
                'category_id' => $this->category_id,
                'subcategory_id' => $this->subcategory_id,
                'title' => $this->title,
                'delivery_number' => $this->delivery_number,
                'delivery_unit' => $this->delivery_unit,
                'description' => $this->description,
                'image_urls' => $image_urls,
                'image_public_ids' => $image_public_ids,
                'price' => preg_replace('/[^0-9.]/', '', $this->price),
            ];
            $apiEndpoints = new ApiEndpoints();
            $headers = $apiEndpoints->header();
            $response = Http::withHeaders($headers)
                ->withBody(json_encode($body), 'application/json')
                ->post(ApiEndpoints::saveGig());

            if ($response->successful()) {
                $gig = $response->json()['data'];
                Session::put('gig', $gig);
                $gig = Session::get('gig');
                Session::flash('success', 'Service added successfully.');
                return redirect()->to('/dashboard-faq');
            } else {
                Log::error('Failed to add a new service ' . $response->json()['data']);
                $this->addError('image_urls', $response->json('data'));
            }
        } catch (\Throwable $th) {
            $this->addError('image_urls', $th->getMessage());
        }
    }

    public function render()
    {
        // Get the children of the selected category
        $subcategories = DB::table('categories')
            ->where('parent_id', $this->category_id)
            ->orderBy('name', 'asc')
            ->get();
        // Combine the results if needed
        return view('livewire.gig.add', ["subcategories" => $subcategories]);
    }
}