<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

register_shutdown_function(function () {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        http_response_code(500);
        echo json_encode([
            'error' => true,
            'message' => 'Fatal error occurred',
            'details' => $error
        ]);
        exit;
    }
});

require_once './src/Database.php';
require_once './src/AccessToken.php';

class ProjectSetting {
    public static function callBitrixAPI($accessToken, $data, $url) {
        $data['auth'] = $accessToken;

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($data),
            CURLOPT_TIMEOUT => 10,
        ]);
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            $error = curl_error($curl);
            curl_close($curl);
            return ['error' => true, 'message' => $error];
        }
        curl_close($curl);
        return json_decode($response, true);
    }
}

$localProjectId = $_POST['local_project_id'] ?? null;
$bitrixProjectId = $_POST['bitrix_project_id'] ?? null;
$bitrixUserId = $_POST['bitrix_user_id'] ?? null;
$flowType = $_POST['flow_type'] ?? null;
$projectName = $_POST['project_name'] ?? null;
$queryEmail = $_POST['query_email'] ?? null;
$projectType = $_POST['project_type'] ?? null;
$responsiblePersonsRaw = $_POST['responsible_persons'] ?? [];

$responsiblePersons = [];
foreach ($responsiblePersonsRaw as $json) {
    $decoded = json_decode($json, true);
    if (!empty($decoded)) {
        $responsiblePersons[] = $decoded;
    }
}

if (!$bitrixUserId || !$projectName || !$bitrixProjectId || !$localProjectId) {
    http_response_code(400);
    echo json_encode(['error' => true, 'message' => 'Missing required project data.']);
    exit;
}

$conn = Database::getInstance();
$tokenData = AccessToken::getAccessTokenByUserId($bitrixUserId);

if (!$tokenData || empty($tokenData['access_token']) || empty($tokenData['client_endpoint'])) {
    http_response_code(401);
    echo json_encode(['error' => true, 'message' => 'Access token or endpoint not found.']);
    exit;
}

$accessToken = $tokenData['access_token'];
$domainName = rtrim($tokenData['client_endpoint'], '/');

$updateGroupUrl = $domainName . "/sonet_group.update.json";
$updatePayload = [
    'GROUP_ID' => $bitrixProjectId,
    'NAME' => $projectName . " (" . $flowType . ")"
];

$response = ProjectSetting::callBitrixAPI($accessToken, $updatePayload, $updateGroupUrl);

if (!isset($response['result'])) {
    http_response_code(500);
    echo json_encode([
        'error' => true,
        'message' => 'Failed to update Bitrix project.',
        'bitrix_response' => $response
    ]);
    exit;
}

$stmt = $conn->prepare("
    UPDATE projects 
    SET project_name = ?, flow_type = ?, project_type = ?, query_email = ? 
    WHERE id = ?
");

if (!$stmt) {
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => 'Prepare failed: ' . $conn->error]);
    exit;
}

$stmt->bind_param('ssssi', $projectName, $flowType, $projectType, $queryEmail, $localProjectId);
$stmt->execute();
$stmt->close();

$del = $conn->prepare("DELETE FROM project_responsible_users WHERE project_id = ?");
$del->bind_param('i', $localProjectId);
$del->execute();
$del->close();

if (!empty($responsiblePersons)) {
    $stmt = $conn->prepare("
        INSERT INTO project_responsible_users (project_id, responsible_name, responsible_bitrix_id) 
        VALUES (?, ?, ?)
    ");

    if (!$stmt) {
        http_response_code(500);
        echo json_encode(['error' => true, 'message' => 'Prepare failed (responsibles): ' . $conn->error]);
        exit;
    }

    foreach ($responsiblePersons as $person) {
        $rId = $person['id'] ?? null;
        $rName = $person['name'] ?? null;

        if ($rId && $rName) {
            $stmt->bind_param('iss', $localProjectId, $rName, $rId);
            $stmt->execute();
        }
    }

    $stmt->close();
}

http_response_code(200);
echo json_encode([
    'success' => true,
    'message' => 'Project updated successfully.',
    'bitrix_project_id' => $bitrixProjectId,
    'local_project_id' => $localProjectId
]);
exit;
