<?php
namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\ProductModel;
use Config\Database;

class Products extends Controller
{
    public function index()
    {
        helper(['form']);
        $db = Database::connect();
        $categories = $db->table('categories')->select('id, category_name')->get()->getResultArray();
        return view('products', ['categories' => $categories]);
    }

    public function save()
    {
        $productModel = new ProductModel();

        $imgName = null;
        $img = $this->request->getFile('image');
        if($img && $img->isValid() && !$img->hasMoved()){
            $imgName = $img->getRandomName();
            $img->move(FCPATH.'uploads', $imgName);
        }

        $productData = [
            'category_id' => $this->request->getPost('category_id'),
            'name'        => $this->request->getPost('name'),
            'image'       => $imgName,
            'created_at'  => date('Y-m-d H:i:s')
        ];

        $variants = [];
        $sku_names    = $this->request->getPost('sku_name');
        $units        = $this->request->getPost('unit');
        $prices       = $this->request->getPost('price');
        $offer_prices = $this->request->getPost('offer_price');
        $quantities   = $this->request->getPost('quantity');

        if($sku_names){
            foreach($sku_names as $i => $sku){
                if(!empty($sku)){
                    $variants[] = [
                        'sku_name'   => $sku,
                        'unit'       => $units[$i] ?? '',
                        'price'      => $prices[$i] ?? 0,
                        'offer_price'=> $offer_prices[$i] ?? 0,
                        'quantity'   => $quantities[$i] ?? 0
                    ];
                }
            }
        }

        $productId = $productModel->insertProductWithVariants($productData, $variants);

        if($productId){
            // return success as flashdata
            session()->setFlashdata('sweetalert', ['type'=>'success','msg'=>'Product and variants added successfully!']);
        } else {
            session()->setFlashdata('sweetalert', ['type'=>'error','msg'=>'Insert failed!']);
        }

        return redirect()->to(site_url('products'));
    }
}
