<?php

namespace App\Controllers\Admin;

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

class Providers extends BaseController
{
    public function index()
    {
        $builder = model(ProviderModel::class)->builder();
        $q = $this->request->getGet('q');
        if ($q !== null && $q !== '') {
            $q = trim($q);
            $builder->groupStart()
                ->like('name', $q)
                ->groupEnd();
        }
        $type = $this->request->getGet('type');
        if ($type !== null && $type !== '' && in_array($type, ['fuel', 'gas'], true)) {
            $builder->where('provider_type', $type);
        }
        $providers = $builder->get()->getResult();
        $inv       = model(InventoryModel::class);
        $content   = view('admin/providers_list', [
            'providers' => $providers,
            'inv' => $inv,
            'filter_q' => $q ?? '',
            'filter_type' => $type ?? '',
        ]);
        return view('admin/layout', ['title' => 'Providers & Prices', 'content' => $content]);
    }

    public function addProvider()
    {
        $name = trim((string) $this->request->getPost('name'));
        $type = $this->request->getPost('provider_type');
        if (empty($name)) {
            return redirect()->to(base_url('admin/providers'))->with('error', 'Name required.');
        }
        if (! in_array($type, ['fuel', 'gas'], true)) {
            $type = 'fuel';
        }
        model(ProviderModel::class)->insert(['name' => $name, 'provider_type' => $type]);
        return redirect()->to(base_url('admin/providers'))->with('message', 'Provider added.');
    }

    public function editProvider(int $id)
    {
        $provider = model(ProviderModel::class)->find($id);
        if (! $provider) {
            return redirect()->to(base_url('admin/providers'))->with('error', 'Provider not found.');
        }
        if ($this->request->getMethod() === 'post') {
            $name = trim((string) $this->request->getPost('name'));
            $type = $this->request->getPost('provider_type');
            if (empty($name)) {
                return redirect()->back()->with('error', 'Name required.');
            }
            if (! in_array($type, ['fuel', 'gas'], true)) {
                $type = 'fuel';
            }
            model(ProviderModel::class)->update($id, ['name' => $name, 'provider_type' => $type]);
            return redirect()->to(base_url('admin/providers'))->with('message', 'Provider updated.');
        }
        $content = view('admin/providers_edit', ['provider' => $provider]);
        return view('admin/layout', ['title' => 'Edit Provider', 'content' => $content]);
    }

    public function deleteProvider(int $id)
    {
        model(InventoryModel::class)->where('provider_id', $id)->delete();
        model(ProviderModel::class)->delete($id);
        return redirect()->to(base_url('admin/providers'))->with('message', 'Provider deleted.');
    }

    public function addItem()
    {
        $providerId = (int) $this->request->getPost('provider_id');
        $itemName   = trim((string) $this->request->getPost('item_name'));
        $price      = (float) $this->request->getPost('price');
        $itemType   = $this->request->getPost('item_type') ?: 'fuel';
        $stock      = (int) $this->request->getPost('stock_count');
        $imageUrl   = trim((string) $this->request->getPost('image_url'));
        if ($providerId <= 0 || $itemName === '') {
            return redirect()->to(base_url('admin/providers'))->with('error', 'Provider and item name required.');
        }
        if (! in_array($itemType, ['fuel', 'gas_size'], true)) {
            $itemType = 'fuel';
        }
        $priceKitRaw = $this->request->getPost('price_kit');
        $priceKit    = ($itemType === 'gas_size' && $priceKitRaw !== null && $priceKitRaw !== '') ? (float) $priceKitRaw : null;
        model(InventoryModel::class)->insert([
            'provider_id'  => $providerId,
            'item_type'    => $itemType,
            'category_id'  => null,
            'item_name'    => $itemName,
            'price'        => $price >= 0 ? $price : 0,
            'price_kit'    => $priceKit !== null && $priceKit >= 0 ? $priceKit : null,
            'stock_count'  => $stock >= 0 ? $stock : 0,
            'image_url'    => $imageUrl !== '' ? $imageUrl : null,
        ]);
        return redirect()->to(base_url('admin/providers'))->with('message', 'Item added.');
    }

    public function deleteItem(int $id)
    {
        model(InventoryModel::class)->delete($id);
        return redirect()->to(base_url('admin/providers'))->with('message', 'Item deleted.');
    }

    public function savePrice()
    {
        $inventoryId = (int) $this->request->getPost('inventory_id');
        $price       = (float) $this->request->getPost('price');
        $priceKitRaw = $this->request->getPost('price_kit');
        if ($inventoryId > 0) {
            $data = ['price' => $price >= 0 ? $price : 0];
            if ($priceKitRaw !== null) {
                $data['price_kit'] = $priceKitRaw === '' ? null : max(0, (float) $priceKitRaw);
            }
            model(InventoryModel::class)->update($inventoryId, $data);
        }
        return redirect()->to(base_url('admin/providers'))->with('message', 'Price updated.');
    }
}
