<?php
session_start();
header('Content-Type: application/json');
require_once '../../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'غير مصرح']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? 0;

$database = new Database();
$conn = $database->getConnection();

try {
    // Get image path before deleting
    $stmt = $conn->prepare("SELECT image FROM consultations WHERE id = ?");
    $stmt->execute([$id]);
    $consultation = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Delete from database
    $stmt = $conn->prepare("DELETE FROM consultations WHERE id = ?");
    $stmt->execute([$id]);
    
    // Delete image file if exists
    if ($consultation && $consultation['image'] && file_exists('../../' . $consultation['image'])) {
        unlink('../../' . $consultation['image']);
    }
    
    echo json_encode(['success' => true]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
