<?php
// assets/php/ImageHasher.php
class ImageHasher {
    /**
     * Generate Difference Hash (dHash) untuk gambar
     * Menghasilkan string hexadecimal 16 karakter (64 bit)
     */
    public static function generateHash($filePath) {
        if (!file_exists($filePath)) return null;

        // 1. Load Image
        try {
            $img = imagecreatefromstring(file_get_contents($filePath));
        } catch (Exception $e) {
            return null;
        }

        // 2. Resize ke 9x8 pixel (untuk dHash)
        $resized = imagecreatetruecolor(9, 8);
        imagecopyresampled($resized, $img, 0, 0, 0, 0, 9, 8, imagesx($img), imagesy($img));
        
        // 3. Konversi ke Grayscale dan hitung array
        $grayscale = [];
        for ($y = 0; $y < 8; $y++) {
            for ($x = 0; $x < 9; $x++) {
                $rgb = imagecolorat($resized, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                // Rumus grayscale
                $grayscale[] = intval(($r * 0.299) + ($g * 0.587) + ($b * 0.114));
            }
        }
        
        // 4. Hitung Difference Hash
        // Bandingkan pixel kiri dan kanan, jika kiri > kanan = 1, else 0
        $bits = [];
        for ($y = 0; $y < 8; $y++) {
            for ($x = 0; $x < 8; $x++) {
                $left = $grayscale[$y * 9 + $x];
                $right = $grayscale[$y * 9 + $x + 1];
                $bits[] = ($left > $right) ? 1 : 0;
            }
        }

        // 5. Konversi bits ke Hex
        $hash = '';
        for ($i = 0; $i < 16; $i++) {
            $nibble = 0;
            for ($j = 0; $j < 4; $j++) {
                $nibble = ($nibble << 1) | $bits[$i * 4 + $j];
            }
            $hash .= dechex($nibble);
        }

        imagedestroy($img);
        imagedestroy($resized);

        return $hash;
    }

    /**
     * Hitung jarak Hamming antara dua hash.
     * Semakin kecil nilainya, semakin mirip gambar (0 = identik, <10 = sangat mirip)
     */
    public static function compareHash($hash1, $hash2) {
        if (strlen($hash1) !== strlen($hash2)) return 100; // Fallback
        
        $count = 0;
        $len = strlen($hash1);
        for ($i = 0; $i < $len; $i++) {
            if ($hash1[$i] !== $hash2[$i]) {
                $count++;
            }
        }
        return $count;
    }
}
?>