<?php
require __DIR__ . '/vendor/autoload.php'; // Adjust the path as necessary
use Firebase\JWT\JWT; // Import the JWT class

define('BASE_URL', 'https://api.appstoreconnect.apple.com/v1'); // Base URL for the App Store Connect API

function generate_jwt($private_key) {
    $key_id = getenv('APPLE_KEY_ID') ?: '77HLG2C29P';
    $issuer_id = getenv('APPLE_ISSUER_ID') ?: 'a1ead579-73d7-4227-b9d6-1aeccf17edb4';

    // Header
    $headers = [
        'kid' => $key_id,
        'alg' => 'ES256'
    ];

    // Payload
    $payload = [
        'iss' => $issuer_id,
        'iat' => time(),
        'exp' => time() + (20 * 60), // Token valid for 20 minutes
        'aud' => 'appstoreconnect-v1'
    ];

    try {
        // Generate JWT using ES256 algorithm
        return JWT::encode($payload, $private_key, 'ES256', null, $headers);
    } catch (Exception $e) {
        error_log("Error generating JWT: " . $e->getMessage());
        return null;
    }
}

function api_request($method, $endpoint, $token, $data = null) {
    $url = BASE_URL . '/' . $endpoint; // Construct the URL

    // Set up the headers
    $headers = [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ];

    // Initialize cURL
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as string
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Set headers

    // Set the request method
    switch (strtoupper($method)) {
        case 'GET':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            break;
        case 'POST':
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Set the data for POST
            }
            break;
        case 'PUT':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Set the data for PUT
            }
            break;
        case 'DELETE':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
        default:
            throw new Exception('Unsupported HTTP method');
    }

    // Execute the request
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        error_log('cURL error: ' . curl_error($ch));
        return null;
    }

    // Get the HTTP status code
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Close cURL session
    curl_close($ch);

    // Handle the response
    if ($httpCode >= 200 && $httpCode < 300) {
        return json_decode($response, true); // Decode JSON response to associative array
    } elseif ($httpCode == 204) {
        return []; // No content
    } else {
        error_log("HTTP error occurred: " . $httpCode . " - " . $response);
        return null;
    }
}

function checkBundleIdExists($token, $identifier) {
    $bundleIds = api_request('GET', 'bundleIds', $token);

    if ($bundleIds && isset($bundleIds['data'])) {
        foreach ($bundleIds['data'] as $bundleId) {
            if ($bundleId['attributes']['identifier'] === $identifier) {
                error_log("Bundle identifier '$identifier' exists.");
                return $bundleId['id'];
            }
        }
    }

    error_log("Bundle identifier '$identifier' does not exist.");
    return null;
}

function createBundleId($token, $identifier, $name) {
    $data = [
        'data' => [
            'type' => 'bundleIds',
            'attributes' => [
                'identifier' => $identifier,
                'name' => $name,
                'platform' => 'IOS'
            ]
        ]
    ];

    $response = api_request('POST', 'bundleIds', $token, $data);

    if ($response) {
        error_log("Bundle ID created successfully.");
        return $response;
    } else {
        error_log("Failed to create bundle ID.");
        return null;
    }
}

function checkAppExists($token, $bundleId) {
    $apps = api_request('GET', 'apps', $token);

    if ($apps && isset($apps['data'])) {
        foreach ($apps['data'] as $app) {
            if ($app['attributes']['bundleId'] === $bundleId) {
                error_log("App with bundle ID '$bundleId' exists.");
                return true;
            }
        }
    }

    error_log("No app found with bundle ID '$bundleId'.");
    return false;
}

function checkProfileExists($token, $profileId) {
    $profiles = api_request('GET', 'profiles', $token);

    if ($profiles && isset($profiles['data'])) {
        foreach ($profiles['data'] as $profile) {
            if ($profile['attributes']['name'] === $profileId) {
                error_log("Provisioning profile '$profileId' exists.");
                return $profile['id'];
            }
        }
    }

    error_log("Provisioning profile '$profileId' does not exist.");
    return null;
}

function deleteProfile($token, $profileId) {
    api_request('DELETE', "profiles/$profileId", $token);
    error_log("Provisioning profile '$profileId' deleted successfully.");
}


function getDistributionCertificateForDeletion($token) {
    // Fetch all certificates from the API
    $certificates = api_request('GET', 'certificates', $token);

    if ($certificates && isset($certificates['data'])) {
        // Filter for distribution certificates only
        $distributionCerts = array_filter(
            array_map(function($cert) {
                return [
                    'ID' => $cert['id'],
                    'Name' => $cert['attributes']['name'],
                    'Type' => $cert['attributes']['certificateType'],
                    'Platforms' => isset($cert['attributes']['platforms']) ? $cert['attributes']['platforms'] : 'N/A'
                ];
            }, $certificates['data']),
            function($cert) {
                return $cert['Type'] === 'DISTRIBUTION';
            }
        );

        // Count the number of distribution certificates
        $distributionCount = count($distributionCerts);
        error_log("Number of DISTRIBUTION certificates: $distributionCount");

        // Check if there are more than 2 distribution certificates
        if ($distributionCount >= 2) {
            // Log the certificates
            foreach ($distributionCerts as $cert) {
                error_log("Distribution Certificate: {$cert['Name']} (ID: {$cert['ID']})");
            }

            // Return the ID of one certificate to delete (pick the first one)
            return $distributionCerts[0]['ID'];
        } else {
            // Log that there are not enough distribution certificates for deletion
            error_log("Less than 2 distribution certificates found. No deletion needed.");
            return null;
        }
    }

    // Log and return null if no certificates are fetched
    error_log("No certificates found.");
    return null;
}

function deleteCertificate($token, $certificateId) {
    api_request('DELETE', "certificates/$certificateId", $token);
    error_log("Certificate $certificateId deleted successfully.");
}

function main($identifier) {
    // Step 1: Load private key
    $private_key = file_get_contents(getenv('APPLE_KEY_PATH') ?: 'AuthKey_77HLG2C29P.p8');
    if (!$private_key) {
        return;
    }

    // Step 2: Generate JWT token
    $token = generate_jwt($private_key);
    if (!$token) {
        error_log("Failed to generate JWT token.");
        return;
    }

    // Step 3: Check if the bundle identifier exists
    $bundleId = checkBundleIdExists($token, $identifier);

    // Step 4: If bundle identifier does not exist, create it
    if (!$bundleId) {
        $bundleId = createBundleId($token, $identifier, 'Appza App');
        if (!$bundleId) {
            error_log("Failed to create a new bundle identifier. Exiting.");
            return;
        }
    }

    // Step 5: Check if an app with the bundle identifier exists
    if (!checkAppExists($token, $identifier)) {
        error_log("No app exists with this bundle identifier. Exiting.");
        return;
    }

    error_log("Valid identifier with app exists.");

    // Step 6: Check for provisioning profiles
    $profileName = "match AppStore $identifier";
    $profileId = checkProfileExists($token, $profileName);

    if ($profileId) {
        deleteProfile($token, $profileId);
    } else {
        error_log("Provisioning profile '$profileName' not found.");
    }

    // Step 7: Check for distribution certificates
    $distributionCertId = getDistributionCertificateForDeletion($token);
    if ($distributionCertId) {
        deleteCertificate($token, $distributionCertId);
    } else {
        error_log("No distribution certificates available. Please create one.");
    }

    // Final Step: Print info
    print($token);
}




main('com.lazycoders.appzademo');


?>
