<?php
/**
 * Admin: create one draft order from one or more folders, then redirect back to folder with success message and "Open draft order" button.
 * GET: ?folder_id=1  or  ?folder_id=1&folder_id=2
 * Add ?debug=1 to see error details (API URL, response, HTTP code).
 *
 * Optional in config.php: define('DRAFT_ORDER_API_URL', 'https://your-domain.com/api/draft_order_from_folders.php');
 * If not set: admin under /admin/ calls site root /api/draft_order_from_folders.php (not /admin/api/).
 *
 * Line item properties + price overrides are applied in api/draft_order_from_folders.php
 * (admin_config_helpers.php: _admin_line_item_properties_override, _admin_order_total_override).
 */
$configPath = __DIR__ . '/config.php';
if (!is_file($configPath) && is_file(dirname(__DIR__) . '/config.php')) {
    $configPath = dirname(__DIR__) . '/config.php';
}
if (!is_file($configPath)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Config not found. Expected config.php in admin or site root.';
    exit;
}
require_once $configPath;
$helpersPath = __DIR__ . '/admin_config_helpers.php';
if (!is_file($helpersPath) && is_file(dirname(__DIR__) . '/admin_config_helpers.php')) {
    $helpersPath = dirname(__DIR__) . '/admin_config_helpers.php';
}
if (is_file($helpersPath)) {
    require_once $helpersPath;
}

$folder_ids = [];
$config_ids = [];
$debug = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $folder_id = isset($_POST['folder_id']) ? (int) $_POST['folder_id'] : 0;
    if ($folder_id > 0) {
        $folder_ids = [$folder_id];
    }
    if (!empty($_POST['config_ids']) && is_array($_POST['config_ids'])) {
        $config_ids = array_values(array_unique(array_filter(array_map('intval', $_POST['config_ids']))));
    }
    $debug = !empty($_POST['debug']);
    if (empty($config_ids)) {
        header('Location: folder_detail.php?id=' . (int) $folder_id . '&error=' . rawurlencode('Select at least one project to include in the draft order.'));
        exit;
    }
} else {
    if (!empty($_GET['folder_id'])) {
        $folder_ids = is_array($_GET['folder_id']) ? array_map('intval', $_GET['folder_id']) : [(int) $_GET['folder_id']];
    }
    if (!empty($_GET['config_id'])) {
        $config_ids = array_values(array_unique(array_filter(array_map('intval', (array) $_GET['config_id']))));
    }
    $debug = isset($_GET['debug']) && $_GET['debug'] === '1';
}

$folder_ids = array_unique(array_filter($folder_ids));
if (empty($folder_ids)) {
    header('Location: folders.php');
    exit;
}

$payloadData = [
    'folder_ids' => array_values($folder_ids),
    'debug'      => $debug,
];
if (!empty($config_ids)) {
    $payloadData['config_ids'] = array_values($config_ids);
}
$payload = json_encode($payloadData);

$scriptDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
$isAdminDeploy = ($scriptDir !== '' && $scriptDir !== '.' && preg_match('#(?:^|/)admin$#', $scriptDir));

// Under /admin/: always HTTP to site root /api/ (avoid local include double-loading config.php).
$local_api = __DIR__ . '/api/draft_order_from_folders.php';
if (!$isAdminDeploy && !is_file($local_api) && is_file(dirname(__DIR__) . '/api/draft_order_from_folders.php')) {
    $local_api = dirname(__DIR__) . '/api/draft_order_from_folders.php';
}
$use_local_api = !$isAdminDeploy && is_file($local_api) && !(defined('DRAFT_ORDER_API_URL') && DRAFT_ORDER_API_URL !== '');

$curl_error = '';
if ($use_local_api) {
    $api_url = $local_api . ' (local include)';
    if (!defined('DRAFT_ORDER_FROM_FOLDERS_INCLUDED')) {
        define('DRAFT_ORDER_FROM_FOLDERS_INCLUDED', true);
    }
    $GLOBALS['DRAFT_ORDER_FROM_FOLDERS_INPUT'] = $payload;
    ob_start();
    try {
        include $local_api;
        $response = ob_get_clean();
    } catch (Throwable $e) {
        ob_end_clean();
        $response = json_encode(['success' => false, 'error' => $e->getMessage()]);
        $http_code = 500;
    }
    unset($GLOBALS['DRAFT_ORDER_FROM_FOLDERS_INPUT']);
    if (!isset($http_code)) {
        $http_code = http_response_code();
        if ($http_code === false || $http_code === 0) {
            $http_code = 200;
        }
    }
} else {
    if (defined('DRAFT_ORDER_API_URL') && DRAFT_ORDER_API_URL !== '') {
        $api_url = DRAFT_ORDER_API_URL;
    } else {
        $base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
            . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
        if ($isAdminDeploy || $scriptDir === '' || $scriptDir === '.') {
            $apiPath = '/api/draft_order_from_folders.php';
        } else {
            $apiPath = $scriptDir . '/api/draft_order_from_folders.php';
        }
        $api_url = rtrim($base, '/') . $apiPath;
    }
    $ch = curl_init($api_url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_POSTREDIR      => 3,
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
}

$data = $response ? json_decode($response, true) : null;
if ($http_code >= 200 && $http_code < 300 && $data && !empty($data['success']) && !empty($data['invoice_url'])) {
    if ($debug) {
        header('Content-Type: text/html; charset=utf-8');
        echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Draft order debug</title></head><body>';
        echo '<h1>Draft order – success</h1>';
        echo '<p><strong>Invoice URL:</strong> <a href="' . htmlspecialchars($data['invoice_url']) . '">' . htmlspecialchars($data['invoice_url']) . '</a></p>';
        echo '<p><strong>API URL:</strong> <code>' . htmlspecialchars($api_url) . '</code></p>';
        echo '<p><strong>HTTP code:</strong> ' . (int)$http_code . '</p>';
        if (!empty($data['line_items_debug'])) {
            echo '<h2>Line items / properties sent to Shopify</h2><pre>' . htmlspecialchars(json_encode($data['line_items_debug'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . '</pre>';
        }
        if (!empty($data['shopify_line_items'])) {
            echo '<h2>Properties stored on Shopify draft (returned by API)</h2><pre>' . htmlspecialchars(json_encode($data['shopify_line_items'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . '</pre>';
        }
        echo '</body></html>';
        exit;
    }
    $invoice_url = $data['invoice_url'];
    $draft_order_id = isset($data['draft_order_id']) ? $data['draft_order_id'] : '';
    $back_id = (int) $folder_ids[0];
    $removed_ids = isset($data['config_ids']) && is_array($data['config_ids'])
        ? array_values(array_filter(array_map('intval', $data['config_ids'])))
        : $config_ids;
    if (!empty($removed_ids) && isset($pdo)) {
        admin_remove_configurations_from_folder($pdo, $back_id, $removed_ids);
    }
    header('Location: folder_detail.php?id=' . $back_id . '&draft_created=1&invoice_url=' . rawurlencode($invoice_url) . '&draft_order_id=' . rawurlencode($draft_order_id));
    exit;
}

$err = 'Could not create draft order.';
if ($curl_error) {
    $err = 'Request failed: ' . $curl_error;
} elseif ($data && !empty($data['error'])) {
    $err = $data['error'];
}

if ($debug) {
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Draft order debug</title></head><body>';
    echo '<h1>Draft order from folder – debug</h1>';
    echo '<p><strong>Error:</strong> ' . htmlspecialchars($err) . '</p>';
    echo '<p><strong>API URL called:</strong> <code>' . htmlspecialchars($api_url) . '</code></p>';
    echo '<p><strong>HTTP code:</strong> ' . (int)$http_code . '</p>';
    echo '<p><strong>Request body:</strong> <pre>' . htmlspecialchars($payload) . '</pre></p>';
    echo '<p><strong>Response body:</strong> <pre>' . htmlspecialchars($response !== false ? $response : '(empty)') . '</pre></p>';
    if ($data && !empty($data['line_items_debug'])) {
        echo '<h2>Line items / properties (debug)</h2><pre>' . htmlspecialchars(json_encode($data['line_items_debug'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . '</pre>';
    }
    echo '<p><a href="folder_detail.php?id=' . (int)$folder_ids[0] . '">Back to folder</a></p>';
    echo '</body></html>';
    exit;
}

header('Location: folder_detail.php?id=' . $folder_ids[0] . '&error=' . urlencode($err));
exit;
