<?php
// process.php
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors',1);

function ensure_dir($d){ if(!is_dir($d)) mkdir($d,0777,true); }
ensure_dir(__DIR__ . '/uploads');
ensure_dir(__DIR__ . '/output');

function load_image_resource($path){
    $info = getimagesize($path);
    if(!$info) return false;
    switch($info['mime']){
        case 'image/jpeg': return imagecreatefromjpeg($path);
        case 'image/png': return imagecreatefrompng($path);
        case 'image/gif': return imagecreatefromgif($path);
        case 'image/webp': return imagecreatefromwebp($path);
        default: return false;
    }
}

function save_image_resource($im, $path, $format='auto', $quality=90){
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));

    if($format === 'auto'){
        if(in_array($ext,['jpg','jpeg'])) $format='jpg';
        elseif($ext==='png') $format='png';
        elseif($ext==='webp') $format='webp';
        else $format='jpg';
    }

    if($format === 'jpg'){
        imagejpeg($im, $path, $quality);
    } elseif($format === 'png'){
        imagesavealpha($im, true);
        imagepng($im, $path);
    } elseif($format === 'webp'){
        imagewebp($im, $path, $quality);
    } else {
        imagejpeg($im, $path, $quality);
    }
}

function merge_with_opacity($dest, $src, $x, $y, $opacity){
    $w = imagesx($src);
    $h = imagesy($src);

    $tmp = imagecreatetruecolor($w, $h);
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
    $transparent = imagecolorallocatealpha($tmp, 0,0,0,127);
    imagefill($tmp,0,0,$transparent);

    imagecopy($tmp, $src, 0,0,0,0, $w,$h);

    for($i=0;$i<$w;$i++){
        for($j=0;$j<$h;$j++){
            $rgba = imagecolorat($tmp,$i,$j);
            $a = ($rgba >> 24) & 0x7F;

            $currentAlphaPct = 100 - round(($a / 127) * 100);
            $targetAlphaPct  = $currentAlphaPct * ($opacity/100);
            $newAlpha = 127 - round($targetAlphaPct / 100 * 127);

            $c = imagecolorsforindex($tmp, $rgba);
            $col = imagecolorallocatealpha($tmp, $c['red'],$c['green'],$c['blue'],$newAlpha);

            imagesetpixel($tmp,$i,$j,$col);
        }
    }

    imagecopy($dest, $tmp, $x, $y, 0,0,$w,$h);
    imagedestroy($tmp);
}



// ===================================================
// TEXT WATERMARK (with ROTATION)
// ===================================================
function apply_text_watermark($img, $text, $size, $colorHex, $opacityPct,
                              $position, $customX=null, $customY=null, $rotation=0){

    $w = imagesx($img);
    $h = imagesy($img);

    $overlay = imagecreatetruecolor($w, $h);
    imagesavealpha($overlay,true);
    $trans = imagecolorallocatealpha($overlay,0,0,0,127);
    imagefill($overlay,0,0,$trans);

    // Color
    $hex = ltrim($colorHex,"#");
    if(strlen($hex)==3){
        $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    }
    $r = hexdec(substr($hex,0,2));
    $g = hexdec(substr($hex,2,2));
    $b = hexdec(substr($hex,4,2));

    $fontFile = __DIR__."/fonts/roboto-regular.ttf";
    $useTtf = file_exists($fontFile);

    if($useTtf){
        $bbox = imagettfbbox($size,0,$fontFile,$text);
        $txtW = abs($bbox[2]-$bbox[0]);
        $txtH = abs($bbox[7]-$bbox[1]);
    } else {
        $txtW = strlen($text)*($size*0.6);
        $txtH = $size;
    }

    // Positioning
    switch($position){
        case 'top-left':    $x=10; $y=10+$txtH; break;
        case 'top-right':   $x=$w-$txtW-10; $y=10+$txtH; break;
        case 'bottom-left': $x=10; $y=$h-10; break;
        case 'center':      $x = ($w-$txtW)/2; $y = ($h+$txtH)/2; break;
        case 'custom':      $x = intval($customX); $y=intval($customY); break;
        default:            $x=$w-$txtW-10; $y=$h-10;
    }

    $col = imagecolorallocatealpha($overlay,$r,$g,$b, 127 - round($opacityPct/100*127));

    // Rotation apply
    imagettftext($overlay, $size, -$rotation, $x, $y, $col, $fontFile, $text);

    imagecopy($img,$overlay,0,0,0,0,$w,$h);
    imagedestroy($overlay);

    return $img;
}



// ===================================================
// IMAGE / LOGO WATERMARK (with ROTATION)
// ===================================================
function apply_image_watermark($img, $logoPath, $scalePct, $opacityPct,
                               $position, $customX=null, $customY=null, $rotation=0){

    if(!file_exists($logoPath)) return $img;

    $logo = load_image_resource($logoPath);
    if(!$logo) return $img;

    $iw = imagesx($img);
    $ih = imagesy($img);

    $lw = imagesx($logo);
    $lh = imagesy($logo);

    // Resize
    $destW = intval($iw*($scalePct/100));
    $destH = intval($destW * ($lh / $lw));

    $resized = imagecreatetruecolor($destW,$destH);
    imagesavealpha($resized,true);
    $trans = imagecolorallocatealpha($resized,0,0,0,127);
    imagefill($resized,0,0,$trans);

    imagecopyresampled($resized,$logo,0,0,0,0,$destW,$destH,$lw,$lh);

    // Rotation
    if($rotation != 0){
        $rot = imagerotate($resized, -$rotation, imagecolorallocatealpha($resized,0,0,0,127));
        imagesavealpha($rot,true);
        imagedestroy($resized);
        $resized = $rot;
    }

    $rw = imagesx($resized);
    $rh = imagesy($resized);

    // Position
    switch($position){
        case 'top-left':    $x=10; $y=10; break;
        case 'top-right':   $x=$iw-$rw-10; $y=10; break;
        case 'bottom-left': $x=10; $y=$ih-$rh-10; break;
        case 'center':      $x=($iw-$rw)/2; $y=($ih-$rh)/2; break;
        case 'custom':      $x=intval($customX); $y=intval($customY); break;
        default:            $x=$iw-$rw-10; $y=$ih-$rh-10;
    }

    merge_with_opacity($img,$resized,$x,$y,$opacityPct);

    imagedestroy($logo);
    imagedestroy($resized);

    return $img;
}



// ===================================================
// HANDLE INPUTS
// ===================================================
$position = $_POST['position'] ?? 'center';
$custom_x = $_POST['custom_x'] ?? 0;
$custom_y = $_POST['custom_y'] ?? 0;
$opacity  = intval($_POST['opacity'] ?? 70);
$out_format = $_POST['out_format'] ?? 'auto';
$rotation = floatval($_POST['rotation'] ?? 0);

$wm_type = $_POST['wm_type'] ?? 'image';
$wm_text = $_POST['wm_text'] ?? '';
$wm_fontsize = intval($_POST['wm_fontsize'] ?? 36);
$wm_color = $_POST['wm_color'] ?? '#FFFFFF';
$wm_scale = intval($_POST['wm_scale'] ?? 20);


// Logo upload
$logoPath = null;
if($wm_type === 'image' && isset($_FILES['wm_logo']) && $_FILES['wm_logo']['error'] === UPLOAD_ERR_OK){
    $tmp = $_FILES['wm_logo']['tmp_name'];
    $name = basename($_FILES['wm_logo']['name']);
    $dest = __DIR__."/uploads/logo_".time()."_".preg_replace('/[^A-Za-z0-9\._-]/','_',$name);
    move_uploaded_file($tmp,$dest);
    $logoPath = $dest;
}


// Multiple file upload
if(!isset($_FILES['images'])) die("No images uploaded.");

$files = $_FILES['images'];
$outFiles = [];

for($i=0;$i<count($files['name']);$i++){

    if($files['error'][$i] !== UPLOAD_ERR_OK) continue;

    $tmp = $files['tmp_name'][$i];
    $origName = basename($files['name'][$i]);

    // Save uploaded file temporarily
    $srcPath = __DIR__."/uploads/".time()."_".$i."_".preg_replace('/[^A-Za-z0-9\._-]/','_',$origName);
    move_uploaded_file($tmp,$srcPath);

    $im = load_image_resource($srcPath);
    if(!$im) continue;

    // Apply watermark
    if($wm_type === 'text'){
        $im = apply_text_watermark($img=$im, $wm_text, $wm_fontsize, $wm_color,
                                   $opacity, $position, $custom_x, $custom_y, $rotation);
    } else {
        $im = apply_image_watermark($img=$im, $logoPath, $wm_scale,
                                    $opacity, $position, $custom_x, $custom_y, $rotation);
    }

    // ===============================
    // KEEP ORIGINAL FILE NAME
    // ===============================
    $ext = ($out_format === "auto")
            ? pathinfo($origName, PATHINFO_EXTENSION)
            : $out_format;

    $outName = pathinfo($origName, PATHINFO_FILENAME) . "." . $ext;

    $outPath = __DIR__."/output/".preg_replace('/[^A-Za-z0-9\._-]/','_',$outName);

    save_image_resource($im, $outPath, $out_format);
    imagedestroy($im);

    $outFiles[] = $outPath;
}



// ===================================================
// RESULT HTML
// ===================================================
?>
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Watermark Results</title></head>
<body style="font-family:Arial;padding:20px">

<h2>Processed <?= count($outFiles) ?> image(s)</h2>

<?php if(count($outFiles) > 0): ?>
<ul>
<?php foreach($outFiles as $f): ?>
    <li><a href="output/<?= basename($f) ?>" download><?= basename($f) ?></a></li>
<?php endforeach; ?>
</ul>

<?php if(count($outFiles) > 1): ?>
<?php
$zipPath = __DIR__."/output/watermarked_".time().".zip";
$zip = new ZipArchive();
if($zip->open($zipPath, ZipArchive::CREATE)){
    foreach($outFiles as $f){
        $zip->addFile($f,basename($f));
    }
    $zip->close();
}
?>
<p><a href="output/<?= basename($zipPath) ?>" download>Download ZIP</a></p>
<?php endif; ?>

<?php else: ?>
<p>No images processed.</p>
<?php endif; ?>

<p><a href="index.php">← Back</a></p>

</body>
</html>
