<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ProductModel;

/**
 * كتالوج المنتجات/الخدمات الإضافية القابلة لإعادة الاستخدام في الفواتير
 * (زي: رسوم تركيب، شهادة SSL، خصوصية نطاق...) - يفصل عن "خدمات العميل"
 * المتكررة (استضافة/نطاقات) الموجودة في شاشة الخدمات.
 */
class ProductController extends BaseController
{
    public function index()
    {
        $model = new ProductModel();
        $products = $model->forCompany($this->currentCompanyId())->orderBy('name', 'ASC')->findAll();

        return view('admin/products/index', ['products' => $products]);
    }

    public function create()
    {
        return view('admin/products/form', ['product' => null, 'currencies' => $this->activeCurrencies()]);
    }

    public function store()
    {
        $data = $this->productData();
        $data['company_id'] = $this->currentCompanyId();
        (new ProductModel())->insert($data);

        return redirect()->to('/admin/products')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $product = (new ProductModel())->forCompany($this->currentCompanyId())->find($id);
        if (! $product) return redirect()->to('/admin/products');

        return view('admin/products/form', ['product' => $product, 'currencies' => $this->activeCurrencies()]);
    }

    public function update($id)
    {
        (new ProductModel())->update($id, $this->productData());
        return redirect()->to('/admin/products')->with('message', lang('App.saved_successfully'));
    }

    public function delete($id)
    {
        (new ProductModel())->delete($id);
        return redirect()->to('/admin/products')->with('message', lang('App.deleted_successfully'));
    }

    private function productData(): array
    {
        return [
            'name' => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
            'cost_price' => $this->request->getPost('cost_price') ?: 0,
            'price' => $this->request->getPost('price'),
            'currency' => $this->request->getPost('currency'),
            'is_active' => $this->request->getPost('is_active') ? 1 : 0,
        ];
    }
}
