<?php

/**

 * Admin: upload an image to Shopify Files and return the CDN URL.

 * Requires Shopify app scope: write_files

 * POST multipart/form-data: file (required)

 */

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

ini_set('display_errors', '0');



header('Content-Type: application/json');

header('Access-Control-Allow-Methods: POST, OPTIONS');

header('Access-Control-Allow-Headers: Content-Type');

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

$allowed_origins = [

    'https://shopify.vintagedoors.com',

    'https://vintagedoors.com',

    'https://rice-123.myshopify.com',

    'https://vintage.espirevox.com',

];

if (in_array($origin, $allowed_origins, true)) {

    header('Access-Control-Allow-Origin: ' . $origin);

} elseif ($origin !== '') {

    header('Access-Control-Allow-Origin: ' . $origin);

}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {

    http_response_code(204);

    exit;

}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    http_response_code(405);

    echo json_encode(['success' => false, 'error' => 'Method not allowed']);

    exit;

}



$configPath = __DIR__ . '/../config.php';

if (!is_file($configPath)) {

    $configPath = __DIR__ . '/../admin/config.php';

}

if (!is_file($configPath)) {

    http_response_code(500);

    echo json_encode(['success' => false, 'error' => 'Config not found']);

    exit;

}

require_once $configPath;



$helpersPath = __DIR__ . '/../admin_config_helpers.php';

if (!is_file($helpersPath) && is_file(__DIR__ . '/../admin/admin_config_helpers.php')) {

    $helpersPath = __DIR__ . '/../admin/admin_config_helpers.php';

}

if (is_file($helpersPath)) {

    require_once $helpersPath;

}



if (!function_exists('admin_shopify_upload_image_file')) {

    http_response_code(500);

    echo json_encode(['success' => false, 'error' => 'Upload helper not available']);

    exit;

}



if (empty($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'No file uploaded']);

    exit;

}



$file = $_FILES['file'];

if (!empty($file['error']) && (int) $file['error'] !== UPLOAD_ERR_OK) {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'Upload failed (code ' . (int) $file['error'] . ')']);

    exit;

}



$maxBytes = 10 * 1024 * 1024;

if (!empty($file['size']) && (int) $file['size'] > $maxBytes) {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'File too large (max 10 MB)']);

    exit;

}



$mimeType = (string) ($file['type'] ?? '');

if ($mimeType === '' && function_exists('finfo_open')) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);

    if ($finfo) {

        $detected = finfo_file($finfo, $file['tmp_name']);

        if (is_string($detected) && $detected !== '') {

            $mimeType = $detected;

        }

        finfo_close($finfo);

    }

}

if (strpos($mimeType, 'image/') !== 0) {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'Only image uploads are allowed']);

    exit;

}



$filename = trim((string) ($file['name'] ?? 'upload.jpg'));

$filename = preg_replace('/[^a-zA-Z0-9._-]+/', '_', $filename);

if ($filename === '') {

    $filename = 'upload.jpg';

}



$result = admin_shopify_upload_image_file($file['tmp_name'], $filename, $mimeType);

if (empty($result['success'])) {

    http_response_code(500);

    echo json_encode([

        'success' => false,

        'error'   => (string) ($result['error'] ?? 'Upload failed'),

    ]);

    exit;

}



echo json_encode([

    'success' => true,

    'url'     => (string) ($result['url'] ?? ''),

]);


