<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal menghapus provider.'];

require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../includes/session.php';
require_once __DIR__ . '/../../../lib/Auth.php';
require_once __DIR__ . '/../../../includes/functions.php';

if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    $response['message'] = 'Akses ditolak.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in admin/delete_provider.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

$requestData = json_decode(file_get_contents('php://input'), true);
$providerIdToDelete = filter_var($requestData['provider_id'] ?? null, FILTER_VALIDATE_INT);

if (!$providerIdToDelete) {
    http_response_code(400);
    $response['message'] = 'ID provider tidak valid.';
    echo json_encode($response);
    exit;
}

try {
    $pdo->beginTransaction();

    $stmtCheckServices = $pdo->prepare("SELECT COUNT(id) FROM services WHERE provider_id = :provider_id");
    $stmtCheckServices->bindParam(':provider_id', $providerIdToDelete, PDO::PARAM_INT);
    $stmtCheckServices->execute();
    $serviceCount = (int)$stmtCheckServices->fetchColumn();

    if ($serviceCount > 0) {
        $pdo->rollBack();
        http_response_code(400); // Bad request
        $response['message'] = "Tidak dapat menghapus provider karena masih ada {$serviceCount} layanan yang terkait. Hapus atau pindahkan layanan terlebih dahulu.";
        echo json_encode($response);
        exit;
    }

    $sql = "DELETE FROM providers WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':id', $providerIdToDelete, PDO::PARAM_INT);

    if ($stmt->execute()) {
        if ($stmt->rowCount() > 0) {
            $pdo->commit();
            $response['success'] = true;
            $response['message'] = "Provider (ID: {$providerIdToDelete}) berhasil dihapus.";
        } else {
            $pdo->rollBack(); 
            http_response_code(404);
            $response['message'] = 'Provider tidak ditemukan.';
        }
    } else {
        $pdo->rollBack();
        http_response_code(500);
        $response['message'] = 'Gagal menghapus provider dari database.';
        error_log("Failed to delete provider ID {$providerIdToDelete}: " . implode(", ", $stmt->errorInfo()));
    }
} catch (\PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Admin Delete Provider DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat menghapus provider.";
    http_response_code(500);
} catch (\Throwable $e) {
     if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Admin Delete Provider General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
