<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ServiceModel;
use App\Models\ProviderModel;
use App\Models\InventoryModel;

class ServiceImages extends BaseController
{
    public function index()
    {
        $services   = model(ServiceModel::class)->orderBy('id')->findAll();
        $providers  = model(ProviderModel::class)->orderBy('name')->findAll();
        $invModel   = model(InventoryModel::class);
        $gasSizes   = $invModel->where('item_type', 'gas_size')->orderBy('provider_id')->orderBy('item_name')->findAll();
        $shopProducts = $invModel->where('item_type', 'shop')->orderBy('provider_id')->orderBy('item_name')->findAll();
        $providerById = [];
        foreach ($providers as $p) {
            $providerById[(int) $p->id] = $p;
        }
        $content = view('admin/service_images', [
            'services'      => $services,
            'providers'     => $providers,
            'gasSizes'      => $gasSizes,
            'shopProducts'  => $shopProducts,
            'providerById'  => $providerById,
        ]);
        return view('admin/layout', ['title' => 'Service images', 'content' => $content]);
    }

    public function save()
    {
        $serviceId = (int) $this->request->getPost('service_id');
        $imageUrl  = trim((string) $this->request->getPost('image_url'));
        if ($serviceId > 0) {
            model(ServiceModel::class)->update($serviceId, [
                'image_url' => $imageUrl !== '' ? $imageUrl : null,
            ]);
        }
        return redirect()->to(base_url('admin/service-images'))->with('message', 'Image URL saved.');
    }

    public function saveProviderLogo()
    {
        $providerId = (int) $this->request->getPost('provider_id');
        $logoUrl    = trim((string) $this->request->getPost('logo_url'));
        if ($providerId > 0) {
            model(ProviderModel::class)->update($providerId, [
                'logo_url' => $logoUrl !== '' ? $logoUrl : null,
            ]);
        }
        return redirect()->to(base_url('admin/service-images'))->with('message', 'Brand logo saved.');
    }

    public function saveInventoryImage()
    {
        $inventoryId = (int) $this->request->getPost('inventory_id');
        $imageUrl    = trim((string) $this->request->getPost('image_url'));
        if ($inventoryId > 0) {
            model(InventoryModel::class)->update($inventoryId, [
                'image_url' => $imageUrl !== '' ? $imageUrl : null,
            ]);
        }
        return redirect()->to(base_url('admin/service-images'))->with('message', 'Image URL saved.');
    }
}
