<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\Database\Config;
use App\Models\CategoryModel;
use App\Models\ProductModel;
use App\Models\UnitModel;
use App\Models\AuditModel;
use App\Models\ProductImageModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\IncomingRequest;
use Config\Services;


use App\Controllers\BaseController;


class Admin extends BaseController
{
protected $CategoryModel;
protected $ProductModel;
protected $UnitModel;
protected $AuditModel;
protected $session;
protected $db;
protected $request;

public function __construct()
{
    $this->categorymodel = new CategoryModel();
    $this->auditmodel = new AuditModel();
    $this->unitmodal = new UnitModel();
    $this->productmodal = new ProductModel();
    $this->session = session();
    $this->db      = \Config\Database::connect();
    $this->request = service('request');
    
}
public function index()
{
  return view('admin/dashboard');
}

public function createproduct()
{
    
  $data['units'] = $this->unitmodal->where('unit_status', 'Active')->findAll();
  $data['categories'] = $this->categorymodel->where('category_status', 'Active')->findAll(); 
  return view('admin/createproduct',$data);

}

public function productcategories()
{
 $editId = $this->request->getGet('edit');
  $data['categories'] = $this->categorymodel->getActiveCategories();
  return view('admin/productcategories',$data);
}
public function updatecategory()
    {
        $id = $this->request->getPost('category_id');
       
        $data = [
            'category_name'       => $this->request->getPost('category_name'),
            'category_status'        => $this->request->getPost('category_status'),
            'category_edited_by'  => session()->get('user_id'),
        ];
         $description = 'Edit category with id - ' . $this->request->getPost('category_id');
        $auditdata = [
        'creator'       => session()->get('user_id'),
        'action'        => 'Edit Categories',
        'description'   => $description,
        'ip'            => $this->request->getIPAddress()
      ];
        $this->categorymodel->update($id, $data);
        $this->auditmodel->save($auditdata);
        return redirect()->back()->with('success', 'Category Updated successfully!');
    }
public function updatunit()
    {
        $id = $this->request->getPost('unit_id');
        $data = [
            'unit_name'       => $this->request->getPost('unit_name'),
            'unit_status'        => $this->request->getPost('unit_status'),
            'unit_short_name'        => $this->request->getPost('unit_short_name'),
            'unit_created_by'  => session()->get('user_id'),
        ];
         $description = 'Edit Unit with id - ' . $this->request->getPost('unit_id');
        $auditdata = [
        'creator'       => session()->get('user_id'),
        'action'        => 'Edit Unit',
        'description'   => $description,
        'ip'            => $this->request->getIPAddress()
      ];
        $this->unitmodal->update($id, $data);
        $this->auditmodel->save($auditdata);
        return redirect()->back()->with('success', 'Unit Updated successfully!');
    }    
    
public function productunits()
{
   $editId = $this->request->getGet('edit');
  $data['units'] = $this->unitmodal->getUnits();
  return view('admin/productunits',$data);
}
public function addcategory()
{
$data = [
            'category_name'       => $this->request->getPost('category_name'),
            'category_created_by' =>  session()->get('user_id'),
        ];

 $description = 'Adding category named - ' . $this->request->getPost('category_name');
        $auditdata = [
        'creator'       => session()->get('user_id'),
        'action'        => 'Add Category',
        'description'   => $description,
        'ip'            => $this->request->getIPAddress()
      ];
$this->categorymodel->save($data);
$this->auditmodel->save($auditdata);
return redirect()->back()->with('success', 'Category successfully Added!');
}
public function addunit()
{

$data = [
            'unit_name'       => $this->request->getPost('unit_name'),
            'unit_short_name'       => $this->request->getPost('unit_short_name'),
            'unit_created_by' =>  session()->get('user_id'),
        ];

 $description = 'Adding Unit named - ' . $this->request->getPost('unit_name');
        $auditdata = [
        'creator'       => session()->get('user_id'),
        'action'        => 'Add Unit',
        'description'   => $description,
        'ip'            => $this->request->getIPAddress()
      ];
$this->unitmodal->save($data);
$this->auditmodel->save($auditdata);
return redirect()->back()->with('success', 'Unit successfully Added!');
}
public function createproducts()
{
    $productModel = new ProductModel();
    $imageModel   = new ProductImageModel();
    
    

    // Insert product data
    $productData = [
        'product_name' => $this->request->getPost('product_name'),
        'product_code' => $this->request->getPost('product_code'),
        'product_category' => $this->request->getPost('product_category'),
        'product_unit' => $this->request->getPost('product_unit'),
        'product_size' => $this->request->getPost('product_size'),
        'product_description' => $this->request->getPost('product_description'),
        'product_price' => $this->request->getPost('product_price'),
        'product_tax_type' => $this->request->getPost('product_tax_type'),
        'product_tax_percent' => $this->request->getPost('product_tax_percent'),
        'product_discount_type' => $this->request->getPost('product_discount_type'),
        'product_discount_value_percentage' => $this->request->getPost('product_discount_value_percentage'),
        'product_quantity_alert_level' => $this->request->getPost('product_quantity_alert_level'),
        'product_created_by'=>session()->get('user_id'),
    ];
 $description = 'creating produt named - ' . $this->request->getPost('product_name');
        $auditdata = [
        'creator'       => session()->get('user_id'),
        'action'        => 'Create Product',
        'description'   => $description,
        'ip'            => $this->request->getIPAddress()
      ];
    $productId = $productModel->insert($productData);
$this->auditmodel->save($auditdata);

    //  Handle image uploads
    $files = $this->request->getFiles();

    if (!empty($files['images'])) {
        foreach ($files['images'] as $img) {
            if ($img->isValid() && !$img->hasMoved()) {
                $newName = $img->getRandomName();
                $img->move(FCPATH . 'uploads/productimages', $newName);

                // save image name
                $imageModel->insert([
                    'product_id' => $productId,
                    'image_name' => $newName
                ]);
            }
        }
    }

    return redirect()->back()->with('success', 'Product created successfully!');
}

public function productlist2()
{
    $productModel = new ProductModel();
    $imageModel   = new ProductImageModel();

    $data['product'] = $productModel->find();
   // $data['images']  = $imageModel->getImagesByProduct($id);

    return view('admin/productlist', $data);
}
public function productlist()
{
    $productModel = new \App\Models\ProductModel();
    $imageModel   = new \App\Models\ProductImageModel();

    // Get all products
    $products = $productModel->findAll();
    $products = $productModel
        ->select('tbproducts.*, tbcategories.category_name, tbunits.unit_name')
        ->join('tbcategories', 'tbproducts.product_category = tbcategories.category_id', 'left')
        ->join('tbunits', 'tbproducts.product_unit = tbunits.unit_id', 'left')
        ->orderBy('tbproducts.product_created_at', 'DESC')
        ->findAll();

    // Attach images for each product
    foreach ($products as &$product) {
        $product['images'] = $imageModel->where('product_id', $product['product_id'])->findAll();
    }
    $data['units'] = $this->unitmodal->where('unit_status', 'Active')->findAll();
  $data['categories'] = $this->categorymodel->where('category_status', 'Active')->findAll(); 

    $data['products'] = $products;

    return view('admin/productlist', $data);
}
public function productdetails($id)
{
    $productModel = new \App\Models\ProductModel();
    $imageModel   = new \App\Models\ProductImageModel();

    // Get all products
    //$products = $productModel->findAll();
    $product = $productModel
    ->select('tbproducts.*, tbcategories.category_name, tbunits.unit_name')
    ->join('tbcategories', 'tbproducts.product_category = tbcategories.category_id', 'left')
    ->join('tbunits', 'tbproducts.product_unit = tbunits.unit_id', 'left')
    ->find($id);

$product['images'] = $imageModel
    ->where('product_id', $product['product_id'])
    ->findAll();


    $data['units'] = $this->unitmodal->where('unit_status', 'Active')->findAll();
  $data['categories'] = $this->categorymodel->where('category_status', 'Active')->findAll(); 

 
    $data['product'] = $product;

    return view('admin/productdetails', $data);
}
public function editproduct($id)
{
    $productModel = new \App\Models\ProductModel();
    $imageModel   = new \App\Models\ProductImageModel();

    // Get all products
    //$products = $productModel->findAll();
    $product = $productModel
    ->select('tbproducts.*, tbcategories.category_name, tbunits.unit_name')
    ->join('tbcategories', 'tbproducts.product_category = tbcategories.category_id', 'left')
    ->join('tbunits', 'tbproducts.product_unit = tbunits.unit_id', 'left')
    ->find($id);

$product['images'] = $imageModel
    ->where('product_id', $product['product_id'])
    ->findAll();


    $data['units'] = $this->unitmodal->where('unit_status', 'Active')->findAll();
  $data['categories'] = $this->categorymodel->where('category_status', 'Active')->findAll(); 

 
    $data['product'] = $product;

    return view('admin/editproduct', $data);
}
public function updateproduct()
{
    $productModel = new ProductModel();
    $imageModel   = new ProductImageModel();
    $id=$this->request->getPost('product_id');
    

    // Insert product data
    $productData = [
        'product_name' => $this->request->getPost('product_name'),
        'product_code' => $this->request->getPost('product_code'),
        'product_category' => $this->request->getPost('product_category'),
        'product_unit' => $this->request->getPost('product_unit'),
        'product_size' => $this->request->getPost('product_size'),
        'product_description' => $this->request->getPost('product_description'),
        'product_price' => $this->request->getPost('product_price'),
        'product_tax_type' => $this->request->getPost('product_tax_type'),
        'product_tax_percent' => $this->request->getPost('product_tax_percent'),
        'product_discount_type' => $this->request->getPost('product_discount_type'),
        'product_discount_value_percentage' => $this->request->getPost('product_discount_value_percentage'),
        'product_quantity_alert_level' => $this->request->getPost('product_quantity_alert_level'),
        'product_created_by'=>session()->get('user_id'),
    ];
 $description = 'creating produt named - ' . $this->request->getPost('product_name');
        $auditdata = [
        'creator'       => session()->get('user_id'),
        'action'        => 'Create Product',
        'description'   => $description,
        'ip'            => $this->request->getIPAddress()
      ];
    $productId = $productModel->update($id,$productData);
$this->auditmodel->save($auditdata);

    //  Handle image uploads
    // $files = $this->request->getFiles();

    // if (!empty($files['images'])) {
    //     foreach ($files['images'] as $img) {
    //         if ($img->isValid() && !$img->hasMoved()) {
    //             $newName = $img->getRandomName();
    //             $img->move(FCPATH . 'uploads/productimages', $newName);

    //             // save image name
    //             $imageModel->insert([
    //                 'product_id' => $productId,
    //                 'image_name' => $newName
    //             ]);
    //         }
    //     }
    // }

    return redirect()->back()->with('success', 'Product Edited successfully!');
}


public function logout()
{
    session()->destroy(); // Clears all session data
    return redirect()->to('/');
}


}


