<?php
session_start();
include('../includes/config.php');

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];

// Get current profile picture
$stmt = $conn->prepare("SELECT profile_picture FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$result) {
    echo json_encode(['success' => false, 'message' => 'User not found.']);
    exit;
}

$current_pic = $result['profile_picture'];

// If current picture is not default and exists, delete it
if ($current_pic && $current_pic !== 'default.png') {
    $file_path = __DIR__ . '/../uploads/' . $current_pic;
    if (file_exists($file_path)) {
        @unlink($file_path);
    }
}

// Update DB to default picture
$stmt = $conn->prepare("UPDATE users SET profile_picture = 'default.png' WHERE id = ?");
$stmt->bind_param("i", $user_id);
if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Profile picture restored to default.']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to restore default picture.']);
}
$stmt->close();
$conn->close();
