<?php

defined('ABSPATH') or die('No script kiddies please!!');

// Check if the 'code' and 'state' parameters exist in the URL
if (!isset($_GET['code']) || !isset($_GET['state'])) {
    die("Error: Missing authorization code or state.");
}

// Validate state parameter
if (!isset($_COOKIE['oauth_state']) || $_COOKIE['oauth_state'] !== $_GET['state']) {
    die("Error: Invalid state parameter. Possible CSRF attack.");
}

// Extract authorization code
$authorization_code = $_GET['code'];

// Optional: Expire the state cookie after validation
setcookie('oauth_state', '', time() - 3600, "/");
$std_settings = get_option('std_settings');
// Your Constant Contact API credentials
$client_id = $std_settings['constant_contact_v3']['client_id'];
$client_secret = $std_settings['constant_contact_v3']['client_secret'];
$redirect_uri = site_url() . '?std_constant_contact_authorize';

// Exchange authorization code for access token
$request_body = array(
    'grant_type'    => 'authorization_code',
    'code'          => $authorization_code,
    'redirect_uri'  => $redirect_uri,
    'client_id'     => $client_id,
    'client_secret' => $client_secret
);

// Make the API request
$response = wp_remote_post('https://authz.constantcontact.com/oauth2/default/v1/token', array(
    'body'    => $request_body,
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
));

if (is_wp_error($response)) {
    die("Error: " . $response->get_error_message());
}

// Decode API response
$body = json_decode(wp_remote_retrieve_body($response), true);


if (!isset($body['access_token'])) {
    die("Error: Failed to retrieve access token. " . print_r($body, true));
}
$std_settings['constant_contact_v3']['access_token'] = $body['access_token'];
$std_settings['constant_contact_v3']['refresh_token'] = $body['refresh_token'];
$std_settings['constant_contact_v3']['token_expires'] = time() + $body['expires_in'];



// API URL to fetch contact lists
$api_url = "https://api.cc.email/v3/contact_lists";
$access_token = $std_settings['constant_contact_v3']['access_token'];
// Make the API request
$response = wp_remote_get($api_url, array(
    'headers' => array(
        'Authorization' => "Bearer $access_token",
        'Content-Type'  => 'application/json',
    ),
));

if (is_wp_error($response)) {
    die("Error: " . $response->get_error_message());
}

// Decode API response
$body = json_decode(wp_remote_retrieve_body($response), true);

if (isset($body['error_key'])) {
    die("API Error: " . $body['error_message']);
}
$std_settings['constant_contact_v3']['lists'] = $body['lists'];
update_option('std_settings', $std_settings);
wp_redirect(admin_url('admin.php?page=std-settings&tab=constant_contact_v3&message=3'));
exit;

