<?php

class GalleryController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index($page = 1)
    {
        $page = (int)$page;
        $per_page = 24;

        $this->View->render('gallery/index', array(
            'images' => GalleryModel::getAllImages(null, $page, $per_page),
            'total_images' => GalleryModel::getImageCount(),
            'current_page' => $page,
            'per_page' => $per_page
        ));
    }

    public function my($page = 1)
    {
        Auth::checkAuthentication();

        $page = (int)$page;
        $per_page = 24;
        $user_id = Session::get('user_id');

        $this->View->render('gallery/my', array(
            'images' => GalleryModel::getAllImages($user_id, $page, $per_page),
            'total_images' => GalleryModel::getImageCount($user_id),
            'current_page' => $page,
            'per_page' => $per_page
        ));
    }

    public function view($image_id)
    {
        $image = GalleryModel::getImage($image_id);

        if (!$image) {
            Redirect::to('gallery');
            return;
        }

        if (!$image->is_public && $image->user_id != Session::get('user_id')) {
            Session::add('feedback_negative', 'This image is private');
            Redirect::to('gallery');
            return;
        }

        $this->View->render('gallery/view', array(
            'image' => $image
        ));
    }

    public function upload()
    {
        // Check if AJAX request first
        $isAjax = $this->isAjaxRequest();

        // Check authentication - return JSON error for AJAX
        if (!Session::userIsLoggedIn()) {
            if ($isAjax) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => 'You must be logged in to upload']);
                return;
            }
            Redirect::to('login/index');
            return;
        }

        // Handle POST request (form submission)
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            // Check if image was uploaded
            if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
                $errorMsg = 'Please select an image to upload';
                if (isset($_FILES['image'])) {
                    switch ($_FILES['image']['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            $errorMsg = 'File is too large';
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            $errorMsg = 'No file was uploaded';
                            break;
                    }
                }

                if ($isAjax) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => $errorMsg]);
                    return;
                }
                Session::add('feedback_negative', $errorMsg);
                $this->View->render('gallery/upload');
                return;
            }

            $title = Request::post('title');
            $description = Request::post('description');
            $is_public = Request::post('is_public') ? 1 : 0;

            $image_id = GalleryModel::uploadImage($_FILES['image'], $title, $description, $is_public);

            if ($isAjax) {
                header('Content-Type: application/json');
                if ($image_id) {
                    echo json_encode([
                        'success' => true,
                        'message' => 'Image uploaded successfully',
                        'image_id' => $image_id
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'message' => Session::get('feedback_negative')[0] ?? 'Failed to upload image'
                    ]);
                }
                return;
            }

            if ($image_id) {
                Redirect::to('gallery/success/' . $image_id);
                return;
            }
        }

        $this->View->render('gallery/upload');
    }

    public function success($image_id)
    {
        Auth::checkAuthentication();

        $image = GalleryModel::getImage($image_id);

        if (!$image || $image->user_id != Session::get('user_id')) {
            Redirect::to('gallery');
            return;
        }

        $this->View->render('gallery/success', array(
            'image' => $image
        ));
    }

    public function edit($image_id)
    {
        Auth::checkAuthentication();

        $image = GalleryModel::getImage($image_id);

        if (!$image || $image->user_id != Session::get('user_id')) {
            Session::add('feedback_negative', 'Image not found or access denied');
            Redirect::to('gallery/my');
            return;
        }

        if (Request::post('submit_edit')) {
            $title = Request::post('title');
            $description = Request::post('description');
            $is_public = Request::post('is_public') ? 1 : 0;

            if (GalleryModel::updateImage($image_id, $title, $description, $is_public)) {
                Session::add('feedback_positive', 'Image updated successfully');
                Redirect::to('gallery/view/' . $image_id);
                return;
            }
        }

        $this->View->render('gallery/edit', array(
            'image' => $image
        ));
    }

    public function delete($image_id)
    {
        Auth::checkAuthentication();

        $success = GalleryModel::deleteImage($image_id);

        if ($this->isAjaxRequest()) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => $success,
                'message' => $success ? 'Image deleted successfully' : 'Failed to delete image'
            ]);
            return;
        }

        if ($success) {
            Session::add('feedback_positive', 'Image deleted successfully');
        } else {
            Session::add('feedback_negative', 'Failed to delete image');
        }

        Redirect::to('gallery/my');
    }

    public function image($image_id, $type = 'full')
    {
        $thumbnail = ($type === 'thumb');
        $result = GalleryModel::getDecryptedImage($image_id, $thumbnail);

        if (!$result || !$result['data']) {
            header('HTTP/1.0 404 Not Found');
            exit;
        }

        header('Content-Type: ' . $result['mime_type']);
        header('Content-Length: ' . strlen($result['data']));
        header('Cache-Control: public, max-age=31536000');
        echo $result['data'];
        exit;
    }

    private function isAjaxRequest()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}
