<?php
require '/home/bigtimbe/config/config-constants.php';

$starttime = date("Y-m-d H:i:s");
$log       = "\n$starttime - ".$_SERVER['PHP_SELF']."\n";

require PATH_BASE.'/vendor/autoload.php';
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;

ini_set('memory_limit', '512M');
ini_set('max_execution_time', 0);

$blacklist = [
    '.',
    '..',
    'index.php',
    'thumbs'
];

$whitelist = [
    'jpg',
    'JPG',
    'jpeg',
    'JPEG',
    'png',
    'PNG',
    // 'gif',
    // 'GIF',
    // 'heic',
    // 'HEIC',
    // 'heif',
    // 'HEIF',
];

function createSmall($filename) {
    if ( file_exists(PATH_ATTACHMENTS."/small/$filename") ) {
$log .= "$i. small has already been created. image: $filename\n";
        return;
    }

    $manager = new ImageManager(new Driver());
    $img     = $manager->read(PATH_ATTACHMENTS."/$filename");
    $width   = $img->width();
    $height  = $img->height();
$log .= "$i. width: $width, height: $height\n";

    if ( $width == $height ) {
        $img->scaleDown(width: 1080);
$log .= "$i. createSmall() scaled square image\n";
    } else if ( $width > $height ) {
        $img->scaleDown(width: 1920);
$log .= "$i. createSmall() scaled wider image\n";
    } else {
        $img->scaleDown(width: 1080);
$log .= "$i. createSmall() scaled taller image\n";
    }

    $img->save(PATH_ATTACHMENTS."/small/$filename", quality: 60);
$log .= "$i. createSmall() saved image: $filename\n";
}

$images = scandir(PATH_ATTACHMENTS);
$log   .= print_r($images, true);

$i = 0;
foreach ( $images as $image ) {
    $i++;

    if ( in_array($image, $blacklist) ) {
$log .= "$i. image file in blacklist. continuing. image: $image\n";
        continue;
    }
        
    $ext = pathinfo(PATH_ATTACHMENTS."/$image")['extension'];
    if ( !in_array($ext, $whitelist) ) {
$log .= "$i. image extension not in whitelist. continuing. image: $image\n";
        continue;
    }
    if ( (filesize(PATH_ATTACHMENTS."/$image") / 1024) > 500 ) {
        createSmall($image);
    } else {
$log .= "$i. image less than 500KB. continuing. filesize: ".filesize($image / 1024)."KB\n";
    }
}

$endtime = date("Y-m-d H:i:s");
$log .= "done at $endtime\n";

$file = fopen(PATH_LOGS.'/btb.compress-images.log', "a");
fwrite($file, $log);
fclose($file);