<?php
use CAE\Lib\Database;
use CAE\Lib\Response;

$search = $_GET['search'] ?? '';
$date_range = $_GET['date_range'] ?? '';
$domain = $_GET['domain'] ?? '';

try {
    $db = Database::getInstance();
    $sql = "SELECT * FROM image_optimization_history WHERE 1=1";
    $params = [];

    if (!empty($domain)) {
        $sql .= " AND target_domain = ?";
        array_push($params, $domain);
    }

    if (!empty($search)) {
        $sql .= " AND (original_filename LIKE ? OR target_domain LIKE ? OR suggested_alt LIKE ? OR suggested_title LIKE ?)";
        $s = "%$search%";
        array_push($params, $s, $s, $s, $s);
    }

    if (!empty($date_range)) {
        $dates = explode(' to ', $date_range);
        if (count($dates) === 2) {
            $sql .= " AND created_at BETWEEN ? AND ?";
            array_push($params, $dates[0] . ' 00:00:00', $dates[1] . ' 23:59:59');
        }
    }

    $sql .= " ORDER BY created_at DESC LIMIT 100";
    
    $history = $db->fetchAll($sql, $params);

    Response::success(['history' => $history]);
} catch (Exception $e) {
    Response::error($e->getMessage());
}
