<?php
require 'functions.php';

if (!empty($_FILES['image']['name'])) {
    $filename = uniqid() . '_' . basename($_FILES['image']['name']);
    $target = 'uploads/' . $filename;

    $crop = isset($_POST['crop']); // checkbox check

    if ($crop) {
        // Auto crop logic to 1080x540
        $tmpPath = $_FILES['image']['tmp_name'];
        $imageInfo = getimagesize($tmpPath);

        if (!$imageInfo) {
            die('Invalid image.');
        }

        $mime = $imageInfo['mime'];

        // Create image resource from uploaded file
        switch ($mime) {
            case 'image/jpeg':
                $srcImage = imagecreatefromjpeg($tmpPath);
                break;
            case 'image/png':
                $srcImage = imagecreatefrompng($tmpPath);
                break;
            case 'image/webp':
                $srcImage = imagecreatefromwebp($tmpPath);
                break;
            default:
                die('Unsupported image type.');
        }

        $dstWidth = 1080;
        $dstHeight = 540;
        $dstImage = imagecreatetruecolor($dstWidth, $dstHeight);

        // Resize and crop
        imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $dstWidth, $dstHeight, imagesx($srcImage), imagesy($srcImage));

        // Save cropped image
        switch ($mime) {
            case 'image/jpeg':
                imagejpeg($dstImage, $target, 90);
                break;
            case 'image/png':
                imagepng($dstImage, $target, 9);
                break;
            case 'image/webp':
                imagewebp($dstImage, $target, 90);
                break;
        }

        imagedestroy($srcImage);
        imagedestroy($dstImage);
    } else {
        // Just move original
        move_uploaded_file($_FILES['image']['tmp_name'], $target);
    }

    // Save data
    $data = loadData();
    $data[] = ['filename' => $filename, 'published' => true];
    saveData($data);

    header('Location: index.php');
    exit;
}
?>
