<?php

namespace App\Controllers\Admin;

use App\Models\CertificationModel;

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

        $model = new CertificationModel();
        $data['certifications'] = $model->orderBy('sort_order', 'ASC')->findAll();
        $data['title'] = 'Manage Certifications';

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

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

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

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

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

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

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

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

        $model = new CertificationModel();
        $certification = $model->find($id);

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

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

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

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

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

        $data['certification'] = $certification;
        $data['title'] = 'Edit Certification';
        return view('admin/certifications/edit', $data);
    }

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

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