<?php
// File: profile_picture.php

function hasProfilePicture($userId) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'users';
    
    $profile_picture = $wpdb->get_var($wpdb->prepare(
        "SELECT profile_picture FROM $table_name WHERE ID = %d",
        $userId
    ));

    return !empty($profile_picture);
}

function getProfilePictureUrl($userId) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'users';
    
    $user = $wpdb->get_row($wpdb->prepare(
        "SELECT unique_id, profile_picture FROM $table_name WHERE ID = %d",
        $userId
    ));

    if ($user && $user->profile_picture) {
        return "/images/profiles/" . $user->unique_id . "/" . $user->profile_picture;
    }
    
    return ''; // Return empty string if no profile picture is set
}

function handleProfilePictureUpload($userId) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'users';

    // Check if file was uploaded without errors
    if(isset($_FILES["profile_picture"]) && $_FILES["profile_picture"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["profile_picture"]["name"];
        $filetype = $_FILES["profile_picture"]["type"];
        $filesize = $_FILES["profile_picture"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) {
            return json_encode(["success" => false, "message" => "Error: Please select a valid file format."]);
        }
    
        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) {
            return json_encode(["success" => false, "message" => "Error: File size is larger than the allowed limit."]);
        }
    
        // Verify MIME type of the file
        if(in_array($filetype, $allowed)){
            // Check if user already has a unique_id
            $unique_id = $wpdb->get_var($wpdb->prepare(
                "SELECT unique_id FROM $table_name WHERE ID = %d",
                $userId
            ));

            if(!$unique_id) {
                $unique_id = generateUniqueId();
                $wpdb->update($table_name, array('unique_id' => $unique_id), array('ID' => $userId));
            }

            // Create user folder if it doesn't exist
            $user_folder = $_SERVER['DOCUMENT_ROOT'] . "/images/profiles/" . $unique_id . "/";
            if (!file_exists($user_folder)) {
                mkdir($user_folder, 0777, true);
            }

            // Generate new filename
            $new_filename = bin2hex(random_bytes(8)) . "." . $ext;

            // Save the file
            if(move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $user_folder . $new_filename)){
                // Update database
                $wpdb->update(
                    $table_name,
                    array('profile_picture' => $new_filename),
                    array('ID' => $userId)
                );
                return json_encode([
                    "success" => true, 
                    "message" => "Your profile picture was uploaded successfully.",
                    "newImageUrl" => "/images/profiles/" . $unique_id . "/" . $new_filename
                ]);
            } else {
                return json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
            }
        } else {
            return json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
        }
    } else {
        return json_encode(["success" => false, "message" => "Error: " . $_FILES["profile_picture"]["error"]]);
    }
}

function generateUniqueId($length = 16) {
    return bin2hex(random_bytes($length / 2));
}
?>