<?php
// File: includes/upload_profile_picture.php
require_once 'include_all.inc.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['profile_picture'])) {
    $userId = $_SESSION['front_user_id'];
    $file = $_FILES['profile_picture'];

    // Get or generate 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)); // Generate a 16-character unique_id
        $stmt = $pdo->prepare("UPDATE " . PREFIX . "users SET unique_id = ? WHERE ID = ?");
        $stmt->execute([$unique_id, $userId]);
    }

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

    $fileName = uniqid() . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
    $targetFile = $uploadDir . $fileName;

    if (move_uploaded_file($file['tmp_name'], $targetFile)) {
        $stmt = $pdo->prepare("UPDATE " . PREFIX . "users SET profile_picture = ? WHERE ID = ?");
        if ($stmt->execute([$fileName, $userId])) {
            echo json_encode([
                'success' => true,
                'message' => 'Profile picture updated successfully.',
                'newImageUrl' => "/images/profiles/" . $unique_id . "/" . $fileName
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update database.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request.']);
}