<?php
// File: inc/profile_picture_admin.php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');


function getProfilePictureUrlAdmin($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT unique_id, profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_OBJ);

    if ($user && $user->profile_picture) {
        return "/images/profiles/" . $user->unique_id . "/" . $user->profile_picture;
    }
    
    return false;
}

function handleProfilePictureUploadAdmin($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';

    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"];
    
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) {
            return json_encode(["success" => false, "message" => "Error: Please select a valid file format."]);
        }
    
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) {
            return json_encode(["success" => false, "message" => "Error: File size is larger than the allowed limit."]);
        }
    
        if(in_array($filetype, $allowed)){
            $stmt = $pdo->prepare("SELECT unique_id FROM $table_name WHERE ID = ?");
            $stmt->execute([$userId]);
            $unique_id = $stmt->fetchColumn();

            if(!$unique_id) {
                $unique_id = bin2hex(random_bytes(8));
                $stmt = $pdo->prepare("UPDATE $table_name SET unique_id = ? WHERE ID = ?");
                $stmt->execute([$unique_id, $userId]);
            }

            $user_folder = $_SERVER['DOCUMENT_ROOT'] . "/images/profiles/" . $unique_id . "/";
            if (!file_exists($user_folder)) {
                mkdir($user_folder, 0777, true);
            }

            $new_filename = bin2hex(random_bytes(8)) . "." . $ext;

            if(move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $user_folder . $new_filename)){
                $stmt = $pdo->prepare("UPDATE $table_name SET profile_picture = ? WHERE ID = ?");
                $stmt->execute([$new_filename, $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 removeProfilePictureAdmin($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';

    $stmt = $pdo->prepare("SELECT unique_id, profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_OBJ);

    if ($user && $user->profile_picture) {
        $file_path = $_SERVER['DOCUMENT_ROOT'] . "/images/profiles/" . $user->unique_id . "/" . $user->profile_picture;
        if (file_exists($file_path)) {
            unlink($file_path);
        }

        $stmt = $pdo->prepare("UPDATE $table_name SET profile_picture = NULL WHERE ID = ?");
        $stmt->execute([$userId]);

        return json_encode(["success" => true, "message" => "Profile picture removed successfully"]);
    } else {
        return json_encode(["success" => false, "message" => "No profile picture found"]);
    }
}