<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\ProductsModel;
use App\Models\ProductTempModel;
use App\Models\ProductCatalogModel;


class ProductTemp extends BaseController
{
    public function index() {
        $productsModel = new ProductsModel();
        $productTempModel = new ProductTempModel();

        $productTypeIds = [3, 10, 11, 12, 13, 14, 21];
        $productTemps = $productTempModel
        ->select('producttemp.*, productcatalog.producttypeid')
        ->join('productcatalog', 'producttemp.catalognumber = productcatalog.catalognumber')
        ->whereIn('productcatalog.producttypeid', $productTypeIds)
        ->where('producttemp.logdate >=', date('Y-m-d', strtotime('-30 days')))
        ->where('producttemp.logdate <=', date('Y-m-d', strtotime('+3 days')))
        ->findAll();

        $merged_data = [];
        foreach ($productTemps as $productTemp) {
            $productnumber = $productTemp['productnumber'];
            $catalognumber = $productTemp['catalognumber'];

            $duplicates = $productsModel
            ->select('products.*, productcatalog.catalognumber')
            ->join('productcatalog', 'products.catalogid = productcatalog.catalogid')
            ->where('products.productnumber', $productnumber)
            ->where('productcatalog.catalognumber', $catalognumber)
            ->findAll();

            if ($duplicates) {
                $productTemp['duplicates'] = $duplicates;
            } else {
                $productTemp['duplicates'] = null;
            }

            $merged_data[] = $productTemp;
        }

        $data['products'] = $merged_data;
        // dd($data);
        return view('producttemp_index', $data);
    }

    public function getdata($id) {
        $model = new ProductTempModel();
        $result = $model->find($id);

        if ($result) {
            return $this->response->setJSON($result);
        } else {
            return $this->response->setStatusCode(404)->setJSON(['error' => 'Data not found']);
        }
    }

    public function edit() {
        $id = $this->request->getPost('edit-productid');

        $data = [
            'productnumber' => $this->request->getPost('edit-productnumber'),
            'productname' => $this->request->getPost('edit-productname'),
            'catalognumber' => $this->request->getPost('edit-catalognumber'),
            'locationstartdate' => $this->request->getPost('edit-locationstartdate') ?: null,
            'locationenddate' => $this->request->getPost('edit-locationenddate') ?: null,
            'warrantystartdate' => $this->request->getPost('edit-warrantystartdate') ?: null,
            'warrantyenddate' => $this->request->getPost('edit-warrantyenddate') ?: null,
            'active' => $this->request->getPost('edit-active'),
            'statusservice' => $this->request->getPost('edit-statusservice'),
            'statusparts' => $this->request->getPost('edit-statusparts'),
        ];
        // dd($data);
        $model = new ProductTempModel();
        $model->update($id, $data);
        return redirect()->to('/producttemp')->with('success', 'Product updated');
    }

    public function deleteItem($productid) {
        $model = new ProductTempModel();
        $result = $model->find($productid);
        if($result) {
            $model->delete($productid);
            return redirect()->to('/producttemp')->with('success', 'Product deleted');
        }
    }

    public function validateItem() {
        $productTempModel = new ProductTempModel();
        $productsModel = new ProductsModel();
        $productCatalogModel = new ProductCatalogModel();

        $productTempId = $this->request->getPost('producttemp-productid');
        $productId = $this->request->getPost('product-productid') ?? null;

        $dataProductTemp = $productTempModel->find($productTempId);

        $catalognumber = $dataProductTemp['catalognumber'];
        $productCatalogData = $productCatalogModel->where('catalognumber', $catalognumber)->first();

        if ($productId) {
            if ($productCatalogData) {
                $data = [
                    'productnumber' => $dataProductTemp['productnumber'],
                    // 'productname' => $dataProductTemp['productname'],
                    'catalogid' => $productCatalogData['catalogid'],
                    'siteid' => $dataProductTemp['siteid'],
                    'locationstartdate' => $dataProductTemp['locationstartdate'],
                    'locationenddate' => $dataProductTemp['locationenddate'],
                    'warrantystartdate' => $dataProductTemp['warrantystartdate'],
                    'warrantyenddate' => $dataProductTemp['warrantyenddate'],
                    'productowner' => $dataProductTemp['owner'],
                ];
                $productsModel->update($productId, $data);
                $productTempModel->delete($productTempId);
                session()->setFlashdata('success', 'Product updated in product table!');
            } else {
                session()->setFlashdata('error', 'Data not exist on Product Catalog table');
            }
        } else {
            if ($productCatalogData) {
                $data = [
                    'productnumber' => $dataProductTemp['productnumber'],
                    // 'productname' => $dataProductTemp['productname'],
                    'catalogid' => $productCatalogData['catalogid'],
                    'siteid' => $dataProductTemp['siteid'],
                    'locationstartdate' => $dataProductTemp['locationstartdate'],
                    'locationenddate' => $dataProductTemp['locationenddate'],
                    'warrantystartdate' => $dataProductTemp['warrantystartdate'],
                    'warrantyenddate' => $dataProductTemp['warrantyenddate'],
                    'productowner' => $dataProductTemp['owner'],
                    'createdate' => date('Y-m-d'),
                ];
                $productsModel->insert($data);
                $productTempModel->delete($productTempId);
                session()->setFlashdata('success', 'Product moved to product table!');
            } else {
                session()->setFlashdata('error', 'Data not exist on Product Catalog table');
            }
        }

        return redirect()->to('/producttemp');
    }
}