<?php

namespace App\Controllers\Admin;

use App\Models\BannerModel;

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

        $model = new BannerModel();
        $data['banners'] = $model->orderBy('sort_order', 'ASC')->findAll();
        $data['title'] = 'Manage Banners';

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

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

        if ($this->request->getMethod() === 'POST') {
            $model = new BannerModel();

            $image = $this->request->getFile('image');
            $imageName = null;
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $imageName = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/banners', $imageName);
                
                // Optimize Image
                $imagePath = ROOTPATH . 'public/uploads/banners/' . $imageName;
                \Config\Services::image()
                    ->withFile($imagePath)
                    ->resize(1920, 1080, true, 'auto')
                    ->save($imagePath, 80);
            } else {
                $this->session->setFlashdata('error', 'Please upload a valid image.');
                return redirect()->to('/admin/banners/create');
            }

            $insertData = [
                'image' => $imageName,
                'title' => $this->request->getPost('title'),
                'subtitle' => $this->request->getPost('subtitle'),
                'button_text' => $this->request->getPost('button_text'),
                'button_link' => $this->request->getPost('button_link'),
                'sort_order' => $this->request->getPost('sort_order') ?? 0,
                'status' => $this->request->getPost('status') ?? 1,
            ];

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

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

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

        $model = new BannerModel();
        $banner = $model->find($id);

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

        if ($this->request->getMethod() === 'POST') {
            $image = $this->request->getFile('image');
            $imageName = $banner['image'];

            if ($image && $image->isValid() && !$image->hasMoved()) {
                $imageName = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/banners', $imageName);
                
                // Optimize Image
                $imagePath = ROOTPATH . 'public/uploads/banners/' . $imageName;
                \Config\Services::image()
                    ->withFile($imagePath)
                    ->resize(1920, 1080, true, 'auto')
                    ->save($imagePath, 80);
                
                if (!empty($banner['image']) && file_exists(ROOTPATH . 'public/uploads/banners/' . $banner['image'])) {
                    unlink(ROOTPATH . 'public/uploads/banners/' . $banner['image']);
                }
            }

            $updateData = [
                'image' => $imageName,
                'title' => $this->request->getPost('title'),
                'subtitle' => $this->request->getPost('subtitle'),
                'button_text' => $this->request->getPost('button_text'),
                'button_link' => $this->request->getPost('button_link'),
                'sort_order' => $this->request->getPost('sort_order') ?? 0,
                'status' => $this->request->getPost('status') ?? 1,
            ];

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

        $data['banner'] = $banner;
        $data['title'] = 'Edit Banner';
        return view('admin/banners/edit', $data);
    }

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

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