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

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',
];

$manager = new ImageManager(new Driver());

$images = scandir('/home/bigtimbe/public_html/clients/assets/images/attachments');
$log .= print_r($images, true);

$i = 0;
foreach ( $images as $image ) {
$i++;
    if ( file_exists("/home/bigtimbe/public_html/clients/assets/images/attachments/thumbs/$image") ) {
$log .= "$i. image has already been compressed. continuing. image: $image\n";
        continue;
    }

    if ( in_array($image, $blacklist) ) {
$log .= "$i. image file in blacklist. continuing. image: $image\n";
        continue;
    }

    $ext = pathinfo("/home/bigtimbe/public_html/clients/assets/images/attachments/$image")['extension'];
    if ( !in_array($ext, $whitelist) ) {
$log .= "$i. image extension not in whitelist. continuing. image: $image\n";
        continue;
//         if ( $ext == 'heic' || $ext == 'heif' ) {
//             Maestroerror\HeicToJpg::convert("/home/bigtimbe/public_html/clients/assets/images/attachments/$image")->saveAs("/home/bigtimbe/public_html/clients/assets/images/attachments/$image");
//         } else {
// $log .= image extension not in whitelist. continuing. image: $image\n";
//             continue;
//         }
    }

    $img    = $manager->read("/home/bigtimbe/public_html/clients/assets/images/attachments/$image");
    $width  = $img->width();
$log .= "$i. width: $width\n";
    $height = $img->height();
$log .= "$i. height: $height\n";

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

    $img->save("/home/bigtimbe/public_html/clients/assets/images/attachments/thumbs/$image", quality: 50);
$log .= "$i. saved image: $image\n";
}

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

$file = fopen("/home/bigtimbe/logs/btb.compress-images.log", "a");
fwrite($file, $log);
fclose($file);