<?php

namespace App\Controllers\Admin;

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

class Shop extends BaseController
{
    public function index()
    {
        $categories = model(ShopCategoryModel::class)->findAll();
        $productBuilder = model(InventoryModel::class)->where('item_type', 'shop');
        $q = $this->request->getGet('q');
        if ($q !== null && $q !== '') {
            $q = trim($q);
            $productBuilder->like('item_name', $q);
        }
        $products  = $productBuilder->findAll();
        $providers = model(ProviderModel::class)->findAll();
        $content   = view('admin/shop_list', [
            'categories' => $categories,
            'products' => $products,
            'providers' => $providers,
            'filter_q' => $q ?? '',
        ]);
        return view('admin/layout', ['title' => 'Shop', 'content' => $content]);
    }

    public function addCategory()
    {
        $name = trim((string) $this->request->getPost('name'));
        if (empty($name)) {
            return redirect()->to(base_url('admin/shop'))->with('error', 'Category name required.');
        }
        model(ShopCategoryModel::class)->insert(['name' => $name]);
        return redirect()->to(base_url('admin/shop'))->with('message', 'Category added.');
    }

    public function editCategory(int $id)
    {
        $cat = model(ShopCategoryModel::class)->find($id);
        if (! $cat) {
            return redirect()->to(base_url('admin/shop'))->with('error', 'Category not found.');
        }
        if ($this->request->getMethod() === 'post') {
            $name = trim((string) $this->request->getPost('name'));
            if (empty($name)) {
                return redirect()->back()->with('error', 'Name required.');
            }
            model(ShopCategoryModel::class)->update($id, ['name' => $name]);
            return redirect()->to(base_url('admin/shop'))->with('message', 'Category updated.');
        }
        $content = view('admin/shop_category_edit', ['category' => $cat]);
        return view('admin/layout', ['title' => 'Edit Category', 'content' => $content]);
    }

    public function deleteCategory(int $id)
    {
        model(InventoryModel::class)->where('category_id', $id)->set(['category_id' => null])->update();
        model(ShopCategoryModel::class)->delete($id);
        return redirect()->to(base_url('admin/shop'))->with('message', 'Category deleted.');
    }

    public function addProduct()
    {
        $name       = trim((string) $this->request->getPost('item_name'));
        $price      = (float) $this->request->getPost('price');
        $stock      = (int) $this->request->getPost('stock_count');
        $categoryId = (int) $this->request->getPost('category_id');
        $providerId = (int) $this->request->getPost('provider_id');
        $imageUrl   = trim((string) $this->request->getPost('image_url'));
        if (empty($name)) {
            return redirect()->to(base_url('admin/shop'))->with('error', 'Product name required.');
        }
        if ($providerId <= 0) {
            $first = model(ProviderModel::class)->first();
            $providerId = $first ? (int) $first->id : 0;
        }
        model(InventoryModel::class)->insert([
            'provider_id'  => $providerId,
            'item_type'    => 'shop',
            'category_id'  => $categoryId ?: null,
            'item_name'    => $name,
            'price'        => $price >= 0 ? $price : 0,
            'stock_count'  => $stock >= 0 ? $stock : 0,
            'image_url'    => $imageUrl !== '' ? $imageUrl : null,
        ]);
        return redirect()->to(base_url('admin/shop'))->with('message', 'Product added.');
    }

    public function editProduct(int $id)
    {
        $product = model(InventoryModel::class)->where('item_type', 'shop')->find($id);
        if (! $product) {
            return redirect()->to(base_url('admin/shop'))->with('error', 'Product not found.');
        }
        if ($this->request->getMethod() === 'post') {
            $name       = trim((string) $this->request->getPost('item_name'));
            $price      = (float) $this->request->getPost('price');
            $stock      = (int) $this->request->getPost('stock_count');
            $categoryId = (int) $this->request->getPost('category_id');
            $imageUrl   = trim((string) $this->request->getPost('image_url'));
            if (empty($name)) {
                return redirect()->back()->withInput()->with('error', 'Name required.');
            }
            $invModel = model(InventoryModel::class);
            $invModel->update($id, [
                'item_name'   => $name,
                'price'       => $price >= 0 ? $price : 0,
                'stock_count' => $stock >= 0 ? $stock : 0,
                'category_id' => $categoryId ?: null,
                'image_url'   => $imageUrl,
            ]);
            return redirect()->to(base_url('admin/shop/product/edit/' . $id))->with('message', 'Product updated.');
        }
        $categories = model(ShopCategoryModel::class)->findAll();
        $content = view('admin/shop_product_edit', ['product' => $product, 'categories' => $categories]);
        return view('admin/layout', ['title' => 'Edit Product', 'content' => $content]);
    }

    public function deleteProduct(int $id)
    {
        $product = model(InventoryModel::class)->where('item_type', 'shop')->find($id);
        if ($product) {
            model(InventoryModel::class)->delete($id);
        }
        return redirect()->to(base_url('admin/shop'))->with('message', 'Product deleted.');
    }
}
