<?php
require_once __DIR__ . "/../magic/DataBase.php";
require_once __DIR__ . "/../op/wanted.php";

$archive = in_array("--archive", $argv ?? array(), true);
$photoDir = realpath(__DIR__ . "/../photo/check");
$archiveDir = __DIR__ . "/../photo/arc_check";

if ($photoDir === false || !is_dir($photoDir)) {
    fwrite(STDERR, "photo/check folder was not found." . PHP_EOL);
    exit(1);
}

if ($archive && !is_dir($archiveDir)) {
    mkdir($archiveDir, 0700, true);
}
$archiveDirReal = realpath($archiveDir);

$database = new DataBase();
$db = $database->getConnection();

$files = array();
$contractIds = array();

foreach (new DirectoryIterator($photoDir) as $file) {
    if (!$file->isFile()) {
        continue;
    }

    $baseName = pathinfo($file->getFilename(), PATHINFO_FILENAME);
    if (!ctype_digit($baseName) || strlen($baseName) <= 3) {
        $contractId = null;
    } else {
        $contractId = substr($baseName, 0, -3);
        $contractIds[$contractId] = true;
    }

    $files[] = array(
        "path" => $file->getPathname(),
        "name" => $file->getFilename(),
        "contract_id" => $contractId,
        "mtime" => $file->getMTime(),
        "size" => $file->getSize(),
    );
}

$contractToCar = array();
if (!empty($contractIds)) {
    $ids = array_keys($contractIds);
    foreach (array_chunk($ids, 500) as $chunk) {
        $placeholders = implode(",", array_fill(0, count($chunk), "?"));
        $sql = $db->prepare("SELECT contract_id, carid FROM contracts WHERE contract_id IN ($placeholders)");
        foreach ($chunk as $index => $id) {
            $sql->bindValue($index + 1, $id);
        }
        $sql->execute();
        while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
            $contractToCar[(string)$row["contract_id"]] = (string)$row["carid"];
        }
    }
}

$wantedContracts = array();
foreach (array_keys($contractIds) as $contractId) {
    try {
        $wanted = new Wanted($db, $contractId);
        $data = $wanted->wanted();
        if (isset($data["wanted"]) && (float)$data["wanted"] > 0) {
            $wantedContracts[$contractId] = true;
        }
    } catch (Throwable $e) {
        error_log("cleanup_check_photos wanted error for contract {$contractId}: " . $e->getMessage());
    }
}

$photosByCar = array();
foreach ($files as $index => $photo) {
    $contractId = $photo["contract_id"];
    if ($contractId !== null && isset($contractToCar[$contractId])) {
        $carId = $contractToCar[$contractId];
        if (!isset($photosByCar[$carId])) {
            $photosByCar[$carId] = array();
        }
        $photosByCar[$carId][] = $index;
    }
}

$keep = array();
foreach ($photosByCar as $carId => $indexes) {
    usort($indexes, function ($a, $b) use ($files) {
        if ($files[$a]["mtime"] === $files[$b]["mtime"]) {
            return strcmp($files[$b]["name"], $files[$a]["name"]);
        }
        return $files[$b]["mtime"] <=> $files[$a]["mtime"];
    });

    foreach (array_slice($indexes, 0, 4) as $index) {
        $keep[$index] = "last_4_for_car";
    }
}

foreach ($files as $index => $photo) {
    $contractId = $photo["contract_id"];
    if ($contractId !== null && isset($wantedContracts[$contractId])) {
        $keep[$index] = "wanted_contract";
    }
}

$archiveCount = 0;
$keepCount = 0;
$archiveBytes = 0;

foreach ($files as $index => $photo) {
    if (isset($keep[$index])) {
        $keepCount++;
        continue;
    }

    $archiveCount++;
    $archiveBytes += $photo["size"];
    if ($archive) {
        $target = $archiveDir . DIRECTORY_SEPARATOR . $photo["name"];
        if (file_exists($target)) {
            $baseName = pathinfo($photo["name"], PATHINFO_FILENAME);
            $extension = pathinfo($photo["name"], PATHINFO_EXTENSION);
            $suffix = 1;
            do {
                $targetName = $baseName . "_" . $suffix . ($extension !== "" ? "." . $extension : "");
                $target = $archiveDir . DIRECTORY_SEPARATOR . $targetName;
                $suffix++;
            } while (file_exists($target));
        }
        rename($photo["path"], $target);
    }
}

echo "Mode: " . ($archive ? "ARCHIVE" : "DRY RUN") . PHP_EOL;
echo "Folder: " . $photoDir . PHP_EOL;
echo "Archive folder: " . ($archiveDirReal ?: $archiveDir) . PHP_EOL;
echo "Total files: " . count($files) . PHP_EOL;
echo "Contracts from filenames: " . count($contractIds) . PHP_EOL;
echo "Contracts with wanted money: " . count($wantedContracts) . PHP_EOL;
echo "Cars with photos: " . count($photosByCar) . PHP_EOL;
echo "Keep files: " . $keepCount . PHP_EOL;
echo "Archive files: " . $archiveCount . PHP_EOL;
echo "Archive size MB: " . round($archiveBytes / 1024 / 1024, 2) . PHP_EOL;

if (!$archive) {
    echo PHP_EOL . "Dry run only. To archive, run:" . PHP_EOL;
    echo "php tools/cleanup_check_photos.php --archive" . PHP_EOL;
}
