<?php
class GalleryController extends Controller {

    public function index() {
        $galleryModel = $this->model('Gallery');

        // Add
        if (isset($_POST['add'])) {
            $imageName = null;
            if (!empty($_FILES['image']['name'])) {
                $allowed = ['png','jpg','jpeg','webp'];
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, $allowed)) die("Invalid image format");

                $imageName = time().'_'.$_FILES['image']['name'];
                move_uploaded_file($_FILES['image']['tmp_name'], 'assets/images/gallery/'.$imageName);
            }

            $galleryModel->add(['image' => $imageName]);

            $_SESSION['message'] = "Image added successfully!";
            header('Location: '.BASE_URL.'/gallery');
            exit;
        }

        // Edit
        if (isset($_POST['edit'])) {
            $id = $_POST['id'];
            $imageName = $_POST['old_image'];

            if (!empty($_FILES['image']['name'])) {
                $allowed = ['png','jpg','jpeg','webp'];
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, $allowed)) die("Invalid image format");

                $imageName = time().'_'.$_FILES['image']['name'];
                move_uploaded_file($_FILES['image']['tmp_name'], 'assets/images/gallery/'.$imageName);
            }

            $galleryModel->update($id, ['image' => $imageName]);

            $_SESSION['message'] = "Image updated successfully!";
            header('Location: '.BASE_URL.'/gallery');
            exit;
        }

        // Delete
        if (isset($_GET['delete'])) {
            $id = $_GET['delete'];
            $image = $galleryModel->get($id);
            if ($image && file_exists('assets/images/gallery/'.$image['image'])) {
                unlink('assets/images/gallery/'.$image['image']);
            }
            $galleryModel->delete($id);

            $_SESSION['message'] = "Image deleted successfully!";
            header('Location: '.BASE_URL.'/gallery');
            exit;
        }

        $data['images'] = $galleryModel->getAll();
        $data['title'] = "Gallery";
        $this->view('templates/header', $data);
        $this->view('gallery', $data);
        $this->view('templates/footer', $data);
    }
}
