<?php
session_start();

// Your Shopify App Credentials
$client_id = 'f8dd1e89905a9a919fc369b4085ad49d';
$client_secret = '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';

// File to store access token (in same directory)
$token_file = 'shopify_access_token.txt';

// Simple helper function to check if variable exists
function getValue($array, $key, $default = '') {
    return isset($array[$key]) ? $array[$key] : $default;
}

// Check if we have the authorization code
if (isset($_GET['code']) && isset($_GET['shop'])) {
    $shop = $_GET['shop'];
    $code = $_GET['code'];
    
    // Validate shop domain
    if (!preg_match('/^[a-zA-Z0-9\-]+\.myshopify\.com$/', $shop)) {
        die("<h2>Error: Invalid Shopify store domain</h2>");
    }
    
    echo "<h2>Processing Shopify Connection...</h2>";
    echo "<p>Store: <strong>$shop</strong></p>";
    
    // Build the URL to get access token
    $token_url = "https://$shop/admin/oauth/access_token";
    
    // Prepare POST data
    $post_data = array(
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'code' => $code
    );
    
    // Initialize cURL
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $token_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json'
    ));
    
    // Disable SSL verification for older PHP
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
    // Execute the request
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // Check for cURL errors
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        die("<h2>cURL Error:</h2><p>$error_msg</p>");
    }
    
    curl_close($ch);
    
    // Decode the response
    $token_data = json_decode($response, true);
    
    $file_content = "";
    
    if (isset($token_data['access_token'])) {
        // Success! Store the access token in session
        $_SESSION['shopify_access_token'] = $token_data['access_token'];
        $_SESSION['shopify_shop'] = $shop;
        
        // Save access token to text file (overwrite if exists)
        $file_content .= "Access Token: " . $token_data['access_token'] . "\n";

        // Write to file (this will create or overwrite the file)
        $result = file_put_contents($token_file, $file_content);
        
        if ($result === false) {
            echo "<h2>Warning: Could not save token to file</h2>";
            echo "<p>Check file permissions for directory.</p>";
        } else {
            echo "<p>✅ Access token $file_content saved to <strong>$token_file</strong></p>";
        }
        
        exit;
        
    } else {
        echo "<h2>Error: Failed to get access token</h2>";
        echo "<p>HTTP Code: $http_code</p>";
        echo "<p>Response: " . htmlspecialchars($response) . "</p>";
        echo "<p><a href='index.php'>Go Back</a></p>";
    }
    
} elseif (isset($_GET['error'])) {
    // OAuth error
    $error = $_GET['error'];
    $error_description = getValue($_GET, 'error_description', 'No description');
    
    echo "<h2>OAuth Error</h2>";
    echo "<p>Error: $error</p>";
    echo "<p>Description: $error_description</p>";
    echo "<p><a href='index.php'>Go Back</a></p>";
    
} else {
    echo "<h2>Invalid Request</h2>";
    echo "<p>No authorization code received.</p>";
    echo "<p><a href='index.php'>Go to Connection Page</a></p>";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Shopify Callback</title>
    <style>
        body { font-family: Arial; max-width: 600px; margin: 50px auto; padding: 20px; }
        .success { background: #d4edda; padding: 20px; border-radius: 5px; }
        .error { background: #f8d7da; padding: 20px; border-radius: 5px; }
        .btn { background: #96bf48; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; }
        .info { background: #d1ecf1; padding: 15px; border-radius: 5px; margin: 10px 0; }
    </style>
</head>
<body>
    <h1>Shopify Connection Status</h1>
    
    <?php
    // Display saved token info if file exists
    if (file_exists($token_file)) {
        $file_content = file_get_contents($token_file);
        if ($file_content !== false) {
            echo "<div class='info'>";
            echo "<h3>📁 Token File Contents:</h3>";
            echo "<pre>" . htmlspecialchars($file_content) . "</pre>";
            echo "</div>";
        }
    }
    ?>
    
    <?php if (isset($_SESSION['shopify_access_token'])): ?>
        <div class="success">
            <h3>✅ Connected!</h3>
            <p>Store: <?php echo htmlspecialchars($_SESSION['shopify_shop']); ?></p>
            <p>Token stored in: <strong><?php echo htmlspecialchars($token_file); ?></strong></p>
            <p><a href="index.php" class="btn">Go to Dashboard</a></p>
        </div>
    <?php endif; ?>
</body>
</html>