<?php
session_start();

// Check if user is connected
if (!isset($_SESSION['shopify_access_token'])) {
    header('Location: index.php');
    exit;
}

$shop = $_SESSION['shopify_shop'];
$token_file = "shopify_access_token.txt";
$token = '';

// Check if token file exists
if (file_exists($token_file)) {
    $file_content = file_get_contents($token_file);
    
    // Extract token using regex
    if (preg_match('/Access Token:\s*(shpat_[a-zA-Z0-9]+)/', $file_content, $matches)) {
        $token = $matches[1];
    }
    // Alternative: Extract using string functions if regex fails
    else {
        $lines = explode("\n", $file_content);
        foreach ($lines as $line) {
            if (strpos($line, 'Access Token:') !== false) {
                $parts = explode(':', $line, 2);
                if (isset($parts[1])) {
                    $token = trim($parts[1]);
                    break;
                }
            }
        }
    }
}

// Check if token was found
if (empty($token)) {
    http_response_code(400);
    echo json_encode(array(
        "success" => false, 
        "errors" => array("Missing access token. Token file not found or invalid format.")
    ));
    exit();
}
    $api_version = '2024-10';

// Handle product creation
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_product'])) {
    $title = $_POST['title'] ?: 'Demo Product ' . date('H:i:s');
    $price = $_POST['price'] ?: '19.99';
    
    // Product data
    $product_data = [
        'product' => [
            'title' => $title,
            'body_html' => $_POST['description'] ?: '<p>Product created via PHP API</p>',
            'vendor' => $_POST['vendor'] ?: 'Demo Vendor',
            'product_type' => $_POST['product_type'] ?: 'General',
            'status' => 'active',
            'variants' => [[
                'price' => $price,
                'sku' => $_POST['sku'] ?: 'PROD-' . time(),
                'inventory_quantity' => $_POST['quantity'] ?: 100
            ]]
        ]
    ];
    
    // Send request to Shopify
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://$shop/admin/api/$api_version/products.json");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($product_data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-Shopify-Access-Token: ' . $token
    ]);
    
    $response = curl_exec($ch);
    
    echo "<pre>";
    print_r($response);
    echo "</pre>";

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if ($http_code == 201) {
        $result = json_decode($response, true);
        $message = "✅ Product created successfully! ID: " . $result['product']['id'];
    } else {
        $message = "❌ Error creating product (HTTP $http_code)";
    }
    
    curl_close($ch);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Upload Product to Shopify</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
        }
        .header {
            background: #96bf48;
            color: white;
            padding: 20px;
            border-radius: 10px 10px 0 0;
        }
        .content {
            border: 1px solid #ddd;
            border-top: none;
            padding: 30px;
            border-radius: 0 0 10px 10px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        textarea {
            height: 100px;
        }
        .btn {
            background: #96bf48;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        .message {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>
    <div class="header">
        <h1>Upload Product to Shopify</h1>
        <p>Connected to: <?php echo htmlspecialchars($shop); ?></p>
        <a href="index.php" style="color:white;">← Back to Dashboard</a>
    </div>
    
    <div class="content">
        <?php if ($message): ?>
            <div class="message <?php echo strpos($message, '✅') !== false ? 'success' : 'error'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="form-group">
                <label>Product Title *</label>
                <input type="text" name="title" value="Demo Product <?php echo date('H:i:s'); ?>" required>
            </div>
            
            <div class="form-group">
                <label>Description</label>
                <textarea name="description">This product was created via Shopify PHP API</textarea>
            </div>
            
            <div class="form-group">
                <label>Price *</label>
                <input type="number" name="price" step="0.01" value="19.99" required>
            </div>
            
            <div class="form-group">
                <label>Vendor</label>
                <input type="text" name="vendor" value="Demo Vendor">
            </div>
            
            <div class="form-group">
                <label>Product Type</label>
                <input type="text" name="product_type" value="General">
            </div>
            
            <div class="form-group">
                <label>SKU</label>
                <input type="text" name="sku" value="PROD-<?php echo time(); ?>">
            </div>
            
            <div class="form-group">
                <label>Quantity</label>
                <input type="number" name="quantity" value="100">
            </div>
            
            <button type="submit" name="create_product" value="1" class="btn">Create Product</button>
        </form>
    </div>
</body>
</html>