<?php

function uploadImage($file, $folder="uploads/temples", $maxSizeMB=10)
{
    if(empty($file['name'])){
        return "";
    }

    if($file['size'] > ($maxSizeMB * 1024 * 1024)){
        echo "<script>alert('Image too large');</script>";
        return false;
    }

    /* ✅ RELATIVE PATH (FINAL FIX) */
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . "/digital_panchayat/" . $folder . "/";

    if(!is_dir($target_dir)){
        mkdir($target_dir,0777,true);
    }

    if(!is_writable($target_dir)){
        echo "<script>alert('Folder not writable');</script>";
        return false;
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if(!$ext) $ext = "jpg";

    $filename = "img_".time().rand(100,999).".".$ext;

    $target_file = $target_dir.$filename;

    /* 🔥 CRITICAL FIX */
    if(is_uploaded_file($file['tmp_name'])){
        if(!move_uploaded_file($file['tmp_name'], $target_file)){
            echo "<script>alert('Move failed');</script>";
            return false;
        }
    } else {
        echo "<script>alert('Invalid upload');</script>";
        return false;
    }

    return $filename;
}