<?php
require_once 'db/config.php';
session_start();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['person_id'])) {
        $id = $_POST['person_id'];

        try {
            $pdo = db();
            $stmt = $pdo->prepare("DELETE FROM people WHERE id = ?");
            $stmt->execute([$id]);

            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Osoba usunięta pomyślnie.']);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Nie znaleziono osoby.']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            // Log the real error to a secure log file
            error_log("Database error on person delete: " . $e->getMessage());
            // Send a generic error message to the client
            echo json_encode(['success' => false, 'error' => 'Błąd serwera podczas usuwania osoby.']);
        }
        exit;
    }
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Brak ID osoby.']);
    exit;
}

// Keep GET for backwards compatibility or simple cases, but it redirects.
if (isset($_GET['id'])) {
    $id = $_GET['id'];

    $pdo = db();
    $stmt = $pdo->prepare("DELETE FROM people WHERE id = ?");
    $stmt->execute([$id]);

    $_SESSION['success_message'] = 'Osoba usunięta pomyślnie.';
    header('Location: persons.php');
    exit;
}

http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Nieprawidłowa metoda żądania.']);
?>