<?php

namespace App\Controllers\Admin;

use App\Models\GalleryModel;
use App\Models\GalleryCategoryModel;

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

        $model = new GalleryModel();
        $data['images'] = $model->select('gallery.*, gallery_categories.name as category_name')
                                ->join('gallery_categories', 'gallery_categories.id = gallery.category_id', 'left')
                                ->findAll();
        $data['title'] = 'Manage Gallery';

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

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

        $categoryModel = new GalleryCategoryModel();
        
        if ($this->request->getMethod() === 'POST') {
            $model = new GalleryModel();
            
            // Check if we are creating a new category
            $categoryId = $this->request->getPost('category_id');
            $newCategory = $this->request->getPost('new_category');
            
            if (!empty($newCategory)) {
                $catInsert = [
                    'name' => $newCategory,
                    'slug' => strtolower(url_title($newCategory))
                ];
                $categoryId = $categoryModel->insert($catInsert);
            }

            if (!$categoryId) {
                $this->session->setFlashdata('error', 'Please select or create a category.');
                return redirect()->to('/admin/gallery/create');
            }

            $images = $this->request->getFileMultiple('images');
            $successCount = 0;

            if ($images) {
                foreach ($images as $image) {
                    if ($image->isValid() && !$image->hasMoved()) {
                        $imageName = $image->getRandomName();
                        $image->move(ROOTPATH . 'public/uploads/gallery', $imageName);
                        
                        // Optimize Image
                        $imagePath = ROOTPATH . 'public/uploads/gallery/' . $imageName;
                        \Config\Services::image()
                            ->withFile($imagePath)
                            ->resize(1200, 1200, true, 'auto')
                            ->save($imagePath, 80);
                        
                        $model->insert([
                            'category_id' => $categoryId,
                            'image' => $imageName,
                            'title' => $this->request->getPost('title') // Optional
                        ]);
                        $successCount++;
                    }
                }
            }

            if ($successCount > 0) {
                $this->session->setFlashdata('success', "$successCount images uploaded successfully.");
                return redirect()->to('/admin/gallery');
            } else {
                $this->session->setFlashdata('error', 'Failed to upload images.');
            }
        }

        $data['categories'] = $categoryModel->findAll();
        $data['title'] = 'Upload Gallery Images';
        return view('admin/gallery/create', $data);
    }

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

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