<?php
header('Content-Type: application/json');
require_once './src/Database.php';
require_once './src/AccessToken.php';

$input = $_POST;
$localProjectId = $input['local_project_id'] ?? null;
$bitrixProjectId = $input['bitrix_project_id'] ?? null;
$bitrixUserId = $input['bitrix_user_id'] ?? null;

if (!$localProjectId || !$bitrixProjectId || !$bitrixUserId) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters.']);
    exit;
}

$conn = Database::getInstance();

// Delete from local DB
$stmt = $conn->prepare("DELETE FROM projects WHERE id = ?");
$stmt->bind_param("i", $localProjectId);
$stmt->execute();
$stmt->close();

// Delete responsible persons (optional)
$conn->query("DELETE FROM project_responsible_users WHERE project_id = $localProjectId");

// Delete from Bitrix (optional)
$tokenData = AccessToken::getAccessTokenByUserId($bitrixUserId);
if ($tokenData && $tokenData['access_token'] && $tokenData['client_endpoint']) {
    $accessToken = $tokenData['access_token'];
    $url = rtrim($tokenData['client_endpoint'], '/') . "/sonet_group.delete.json";
    $postData = [
        'GROUP_ID' => $bitrixProjectId,
        'auth' => $accessToken
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($postData)
    ]);
    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);
    if (!isset($response['result']) || !$response['result']) {
        echo json_encode(['success' => false, 'message' => 'Failed to delete project from Bitrix.', 'bitrix' => $response]);
        exit;
    }
}

echo json_encode(['success' => true, 'message' => 'Project deleted successfully.']);
