<?php
// File: profile_picture.php

function hasProfilePicture($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $profile_picture = $stmt->fetchColumn();

    return !empty($profile_picture);
}

function getProfilePictureUrl($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) {
        if (!$user->unique_id) {
            $unique_id = bin2hex(random_bytes(8));
            $updateStmt = $pdo->prepare("UPDATE $table_name SET unique_id = ? WHERE ID = ?");
            $updateStmt->execute([$unique_id, $userId]);
        } else {
            $unique_id = $user->unique_id;
        }
        return "/images/profiles/" . $unique_id . "/" . $user->profile_picture;
    }
    
    return false;
}

function handleProfilePictureUpload($userId) {
    global $pdo;
    $table_name = 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
            $stmt = $pdo->prepare("SELECT unique_id FROM $table_name WHERE ID = ?");
            $stmt->execute([$userId]);
            $unique_id = $stmt->fetchColumn();

            if(!$unique_id) {
                $unique_id = generateUniqueId();
                $stmt = $pdo->prepare("UPDATE $table_name SET unique_id = ? WHERE ID = ?");
                $stmt->execute([$unique_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
                $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 generateUniqueId($length = 16) {
    return bin2hex(random_bytes($length / 2));
}
?><?php
require_once '../includes/include_all.inc.php';

if (!isset($_SESSION['front_user_id'])) {
    echo json_encode(["success" => false, "message" => "User not logged in."]);
    exit;
}

$userId = $_SESSION['front_user_id'];

if (isset($_FILES["profile_picture"]) && $_FILES["profile_picture"]["error"] == 0) {
    $allowed = ["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)) {
        echo json_encode(["success" => false, "message" => "Error: Please select a valid file format."]);
        exit;
    }

    // Verify file size - 5MB maximum
    $maxsize = 5 * 1024 * 1024;
    if ($filesize > $maxsize) {
        echo json_encode(["success" => false, "message" => "Error: File size is larger than the allowed limit."]);
        exit;
    }

    // Verify MIME type of the file
    if (in_array($filetype, $allowed)) {
        // Check if user already has a unique_id
        $stmt = $pdo->prepare("SELECT unique_id FROM " . PREFIX . "users WHERE ID = ?");
        $stmt->execute([$userId]);
        $unique_id = $stmt->fetchColumn();

        if (!$unique_id) {
            $unique_id = bin2hex(random_bytes(8));
            $stmt = $pdo->prepare("UPDATE " . PREFIX . "users SET unique_id = ? WHERE ID = ?");
            $stmt->execute([$unique_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
            $stmt = $pdo->prepare("UPDATE " . PREFIX . "users SET profile_picture = ? WHERE ID = ?");
            $stmt->execute([$new_filename, $userId]);

            echo json_encode([
                "success" => true, 
                "message" => "Your profile picture was uploaded successfully.",
                "newImageUrl" => "/images/profiles/" . $unique_id . "/" . $new_filename
            ]);
        } else {
            echo json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Error: " . $_FILES["profile_picture"]["error"]]);
}
?>