<?php

namespace App\Controllers\Admin;

use App\Models\ProductModel;
use App\Models\CategoryModel;

class Products extends AdminBaseController
{
    public function index()
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new ProductModel();
        // Join category name for display
        $data['products'] = $model->select('products.*, categories.name as category_name')
                                  ->join('categories', 'categories.id = products.category_id', 'left')
                                  ->findAll();
        $data['title'] = 'Manage Products';

        return view('admin/products/index', $data);
    }

    public function create()
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $categoryModel = new CategoryModel();
        $data['categories'] = $categoryModel->where('status', 1)->findAll();

        if ($this->request->getMethod() === 'POST') {
            $model = new ProductModel();
            
            $slug = strtolower(url_title($this->request->getPost('name')));
            
            // Handle File Upload
            $featuredImage = $this->request->getFile('featured_image');
            $imageName = null;
            if ($featuredImage && $featuredImage->isValid() && !$featuredImage->hasMoved()) {
                $imageName = $featuredImage->getRandomName();
                $featuredImage->move(ROOTPATH . 'public/uploads/products', $imageName);
                
                // Optimize Image
                $imagePath = ROOTPATH . 'public/uploads/products/' . $imageName;
                \Config\Services::image()
                    ->withFile($imagePath)
                    ->resize(1200, 1200, true, 'auto')
                    ->save($imagePath, 80);
            }

            $insertData = [
                'category_id' => $this->request->getPost('category_id'),
                'name' => $this->request->getPost('name'),
                'slug' => $slug,
                'short_description' => $this->request->getPost('short_description'),
                'specifications' => $this->request->getPost('specifications'),
                'featured_image' => $imageName,
                'is_featured' => $this->request->getPost('is_featured') ?? 0,
                'meta_title' => $this->request->getPost('meta_title'),
                'meta_description' => $this->request->getPost('meta_description'),
                'status' => $this->request->getPost('status') ?? 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            if ($model->insert($insertData)) {
                $this->session->setFlashdata('success', 'Product created successfully.');
                return redirect()->to('/admin/products');
            } else {
                $this->session->setFlashdata('error', 'Failed to create product.');
            }
        }

        $data['title'] = 'Add New Product';
        return view('admin/products/create', $data);
    }

    public function edit($id)
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new ProductModel();
        $product = $model->find($id);

        if (!$product) {
            $this->session->setFlashdata('error', 'Product not found.');
            return redirect()->to('/admin/products');
        }

        $categoryModel = new CategoryModel();
        $data['categories'] = $categoryModel->where('status', 1)->findAll();

        if ($this->request->getMethod() === 'POST') {
            $slug = strtolower(url_title($this->request->getPost('name')));
            
            // Handle File Upload
            $featuredImage = $this->request->getFile('featured_image');
            $imageName = $product['featured_image']; // Keep old image by default
            if ($featuredImage && $featuredImage->isValid() && !$featuredImage->hasMoved()) {
                $imageName = $featuredImage->getRandomName();
                $featuredImage->move(ROOTPATH . 'public/uploads/products', $imageName);
                
                // Optimize Image
                $imagePath = ROOTPATH . 'public/uploads/products/' . $imageName;
                \Config\Services::image()
                    ->withFile($imagePath)
                    ->resize(1200, 1200, true, 'auto')
                    ->save($imagePath, 80);
                
                // Optionally delete old image here if it exists
                if (!empty($product['featured_image']) && file_exists(ROOTPATH . 'public/uploads/products/' . $product['featured_image'])) {
                    unlink(ROOTPATH . 'public/uploads/products/' . $product['featured_image']);
                }
            }

            $updateData = [
                'category_id' => $this->request->getPost('category_id'),
                'name' => $this->request->getPost('name'),
                'slug' => $slug,
                'short_description' => $this->request->getPost('short_description'),
                'specifications' => $this->request->getPost('specifications'),
                'featured_image' => $imageName,
                'is_featured' => $this->request->getPost('is_featured') ?? 0,
                'meta_title' => $this->request->getPost('meta_title'),
                'meta_description' => $this->request->getPost('meta_description'),
                'status' => $this->request->getPost('status') ?? 1,
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            if ($model->update($id, $updateData)) {
                $this->session->setFlashdata('success', 'Product updated successfully.');
                return redirect()->to('/admin/products');
            } else {
                $this->session->setFlashdata('error', 'Failed to update product.');
            }
        }

        $data['product'] = $product;
        $data['title'] = 'Edit Product: ' . $product['name'];
        return view('admin/products/edit', $data);
    }

    public function delete($id)
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new ProductModel();
        $product = $model->find($id);
        
        if ($product) {
            if (!empty($product['featured_image']) && file_exists(ROOTPATH . 'public/uploads/products/' . $product['featured_image'])) {
                unlink(ROOTPATH . 'public/uploads/products/' . $product['featured_image']);
            }
            $model->delete($id);
            $this->session->setFlashdata('success', 'Product deleted successfully.');
        } else {
            $this->session->setFlashdata('error', 'Failed to delete product.');
        }
        return redirect()->to('/admin/products');
    }
}
