<?php
require_once("config.php");
require_once("user/protect.php");
require_once("user/user-lib.php");

$response = array("status" => false, "message" => "", "imageUrl" => "");

if (isset($_FILES['croppedImage'])) {
    $imageName = $_POST['imageName'];

    // Validate that the file is a PNG
    $fileExtension = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));
    $fileMimeType = strtolower($_FILES['croppedImage']['type']);
    
    if ($fileExtension != 'png' || $fileMimeType != 'image/png') {
        $response['message'] = "Only PNG files are allowed.";
        echo json_encode($response);
        exit;
    }

    $targetPath = 'u_img/'.$userid.'/' . $imageName;
    $u_filename = $userid . uniqid() . '.png'; // Set the extension to .png
    $fileDestination = 'u_img/' . $userid . '/' . $u_filename;

    // Full URL construction
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    $scriptPath = $_SERVER['PHP_SELF'];
    $scriptDir = str_replace(basename($scriptPath), '', $scriptPath);
    $fullUrl = $protocol . $domainName . $scriptDir . $fileDestination;

    // Delete the original file
    if (file_exists($targetPath)) {
        if (!unlink($targetPath)) {
            $response['message'] = "Error deleting the original image.";
            echo json_encode($response);
            exit;
        }
    }

    // Move the uploaded file
    if (move_uploaded_file($_FILES['croppedImage']['tmp_name'], $fileDestination)) {
        $response['status'] = true;
        $response['message'] = "Image successfully uploaded.";
        $response['imageUrl'] = $fullUrl;
    } else {
        $response['message'] = "Error uploading the new image.";
    }
} else {
    $response['message'] = "No image received.";
}

header('Content-Type: application/json');
echo json_encode($response);
?>
