<?php
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,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        ]);
        $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);
    }
}

$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;
//$customType = $_POST['custom_type'] ?? null;
$responsiblePersonsRaw = $_POST['responsible_persons'] ?? [];

//$projectType = ($rawProjectType === 'custom_type') ? $customType : $rawProjectType;
$responsiblePersons = [];
foreach ($responsiblePersonsRaw as $json) {
    $decoded = json_decode($json, true);
    if (!empty($decoded)) {
        $responsiblePersons[] = $decoded;
    }
}

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

$conn = Database::getInstance();
$checkStmt = $conn->prepare("SELECT id FROM projects WHERE project_name = ? AND bitrix24_user_id = ?");
$checkStmt->bind_param('si', $projectName, $bitrixUserId);
$checkStmt->execute();
$checkStmt->store_result();
if ($checkStmt->num_rows > 0) {
    http_response_code(409);
    echo json_encode(['error' => true, 'message' => 'Project with this name already exists.']);
    exit;
}
$checkStmt->close();

$tokenData = AccessToken::getAccessTokenByUserId($bitrixUserId);
$accessToken = $tokenData['access_token'];
$domainName = $tokenData['client_endpoint'];

$createGroupUrl = $domainName."/sonet_group.create.json";
$projectPayload = [
    'NAME' => $projectName."(".$flowType.")",
    'VISIBLE' => 'Y',
    'OPENED' => 'Y',
    'PROJECT' => 'Y',
    'INITIATE_PERMS' => 'K'
];
$response = ProjectSetting::callBitrixAPI($accessToken, $projectPayload, $createGroupUrl);
if (!isset($response['result'])) {
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => 'Failed to create Bitrix project.', 'details' => $response]);
    exit;
}
$projectId = $response['result'];

$getStorageUrl = $domainName."/disk.storage.getlist";
$storagePayload = [
    'filter[ENTITY_TYPE]' => 'group',
    'filter[ENTITY_ID]' => $projectId
];
$storageResponse = ProjectSetting::callBitrixAPI($accessToken, $storagePayload, $getStorageUrl);
if (!isset($storageResponse['result'][0])) {
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => 'Failed to get storage info.', 'details' => $storageResponse]);
    exit;
}
$storage = $storageResponse['result'][0];
$storageId = (int)$storage['ID'];
$folderName = $storage['NAME'] ?? $projectName;

$createFolderUrl = $domainName."/disk.storage.addfolder";
$folderPayload = [
    'id' => $storageId,
    'data[NAME]' => $folderName
];
$folderResponse = ProjectSetting::callBitrixAPI($accessToken, $folderPayload, $createFolderUrl);
if (!isset($folderResponse['result']['ID'])) {
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => 'Failed to create folder.', 'details' => $folderResponse]);
    exit;
}
$folderId = $folderResponse['result']['ID'];

$stmt = $conn->prepare("
    INSERT INTO projects (project_name, project_id, folder_id, project_type, query_email, flow_type, bitrix24_user_id)
    VALUES (?, ?, ?, ?, ?, ?, ?)
");
$stmt->bind_param('siisssi', $projectName, $projectId, $folderId, $projectType, $queryEmail, $flowType, $bitrixUserId);
$stmt->execute();
$localProjectId = $stmt->insert_id;
$stmt->close();

if (!empty($responsiblePersons)) {
    $stmt = $conn->prepare("
        INSERT INTO project_responsible_users (project_id, responsible_name, responsible_bitrix_id)
        VALUES (?, ?, ?)
    ");
    foreach ($responsiblePersons as $person) {
        $rId = $person['id'] ?? null;
        $rName = $person['name'] ?? null;
        if ($rId && $rName) {
            $stmt->bind_param('isi', $localProjectId, $rName, $rId);
            $stmt->execute();
        }
    }
    $stmt->close();
}

http_response_code(200);
echo json_encode([
    'success' => true,
    'message' => ($flowType === 'internal') 
        ? 'Internal project created successfully.'
        : 'Client project created successfully.',
    'bitrix_project_id' => $projectId,
    'folder_id' => $folderId,
    'local_project_id' => $localProjectId
]);
