<?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 || !$result['profile_picture'] || $result['profile_picture'] === 'default.png') {
    echo json_encode(['success' => false, 'message' => 'No profile picture to delete.']);
    exit;
}

$profile_picture_path = __DIR__ . '/../uploads/' . $result['profile_picture'];

// Delete file if exists
if (file_exists($profile_picture_path)) {
    @unlink($profile_picture_path);
}

// Update DB to remove profile picture (set to default.png)
$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 deleted.']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete profile picture.']);
}
$stmt->close();
$conn->close();
