<?php
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';

// Do not call session_start() manually; auth.php already sets the correct session name
$user = sparrow_require_backyard_login();

$grouped_orders = [];
$error = '';
$success_message = '';

/**
 * Helpers to parse wide CSV orders
 */
function sparrow_import_split_values(string $value): array {
    $value = trim($value);
    if ($value === '') return [];
    $parts = preg_split('/\s+\/\s+/', $value);
    return array_map('trim', $parts ?: [$value]);
}
function sparrow_import_get_value_for_index(array $values, int $index): string {
    if (isset($values[$index])) return $values[$index];
    if (count($values) === 1) return $values[0];
    return '';
}
function sparrow_import_combine_csv_row(array $headers, array $row): array {
    $header_count = count($headers);
    $row_count = count($row);
    if ($row_count < $header_count) $row = array_pad($row, $header_count, '');
    if ($row_count > $header_count) $row = array_slice($row, 0, $header_count);
    return array_combine($headers, $row) ?: [];
}

/**
 * Parse a single wide CSV order row into order_items
 */
function sparrow_parse_wide_order(array $row): array {
    $items = [];
    $get = fn($key) => trim((string)($row[$key] ?? ''));

    // Shirt
    $shirt_sizes = sparrow_import_split_values($get('Shirt Details - Size'));
    $shirt_quantities = sparrow_import_split_values($get('Shirt Details - Quantity'));
    $shirt_colors = sparrow_import_split_values($get('Shirt Details - Color'));
    $shirt_specialties = sparrow_import_split_values($get('Shirt Details - Specialty'));
    $shirt_placements = sparrow_import_split_values($get('Shirt Details - Design Placement'));
    $shirt_notes = trim($get('Shirt Details - Shirt Notes') . ' ' . $get('Shirt Details - Upload file'));

    $product_type = $get('Product Type');
    $looks_like_shirt = stripos($product_type, 'shirt') !== false || !empty($shirt_sizes) || !empty($shirt_colors) || !empty($shirt_placements);
    if ($looks_like_shirt) {
        $count = max(count($shirt_sizes), count($shirt_quantities), count($shirt_colors), count($shirt_specialties), count($shirt_placements), 1);
        for ($i = 0; $i < $count; $i++) {
            $size = sparrow_import_get_value_for_index($shirt_sizes, $i);
            $color = sparrow_import_get_value_for_index($shirt_colors, $i);
            $specialty = sparrow_import_get_value_for_index($shirt_specialties, $i);
            $placement = sparrow_import_get_value_for_index($shirt_placements, $i);
            $qty = (int)sparrow_import_get_value_for_index($shirt_quantities, $i);
            if ($qty <= 0) $qty = 1;
            if ($size === '' && $color === '' && $specialty === '' && $placement === '') continue;
            $items[] = [
                'item_type' => 'Shirt',
                'quantity' => $qty,
                'shirt_color' => $color,
                'shirt_size' => $size,
                'specialty' => $specialty,
                'print_location' => $placement,
                'item_notes' => $shirt_notes
            ];
        }
    }

    // Koozie
    $koozie_qty = (int)($get('Koozie Style - Quantity') ?: 0);
    $koozie_color = $get('Koozie Style - Color');
    $koozie_notes = trim($get('Koozie Style - Design Notes') . ' ' . $get('Koozie Style - Upload Design/Inspiration'));
    $looks_like_koozie = stripos($product_type, 'koozie') !== false || $koozie_color !== '' || $koozie_notes !== '';
    if ($looks_like_koozie) {
        if ($koozie_qty <= 0) $koozie_qty = 1;
        $items[] = [
            'item_type' => 'Koozie',
            'quantity' => $koozie_qty,
            'shirt_color' => $koozie_color,
            'shirt_size' => 'Regular',
            'specialty' => '',
            'print_location' => '',
            'item_notes' => $koozie_notes
        ];
    }

    return $items;
}

/**
 * Parse old meta-style Forminator CSV
 */
function sparrow_parse_meta_items(array $fields): array {
    $items = [];
    $choice_raw = $fields['_forminator_choice_values'] ?? '';
    $decoded = @unserialize($choice_raw);
    if (is_array($decoded)) {
        $grouped = [];
        foreach ($decoded as $key => $value) {
            if (!preg_match('/^(select-[1-4])(?:-(\d+))?$/', $key, $matches)) continue;
            $base_key = $matches[1]; $suffix = $matches[2] ?? '1';
            if (!isset($grouped[$suffix])) $grouped[$suffix] = [];
            $grouped[$suffix][$base_key] = $value;
        }
        ksort($grouped, SORT_NATURAL);
        foreach ($grouped as $suffix => $vals) {
            $qty_field = 'number-1' . ($suffix !== '1' ? '-' . $suffix : '');
            $qty = max(1,(int)($fields[$qty_field] ?? 1));
            $color = trim($vals['select-1'] ?? '');
            $specialty = trim($vals['select-2'] ?? '');
            $size = trim($vals['select-3'] ?? '');
            $placement = trim($vals['select-4'] ?? '');
            if ($color === '' && $specialty === '' && $size === '' && $placement === '') continue;
            $items[] = [
                'item_type'=>'Shirt',
                'quantity'=>$qty,
                'shirt_color'=>$color,
                'shirt_size'=>$size,
                'specialty'=>$specialty,
                'print_location'=>$placement,
                'item_notes'=>trim($fields['textarea-1'] ?? '')
            ];
        }
    }
    if (!empty($fields['select-5']) && stripos($fields['select-5'],'koozie')!==false) {
        $qty = max(1,(int)($fields['number-2']??1));
        $items[] = [
            'item_type'=>'Koozie',
            'quantity'=>$qty,
            'shirt_color'=>trim($fields['text-1']??''),
            'shirt_size'=>'Regular',
            'specialty'=>'',
            'print_location'=>'',
            'item_notes'=>trim(($fields['textarea-1']??'').' '.($fields['textarea-4']??''))
        ];
    }
    return $items;
}

/**
 * Detect CSV type and read orders
 */
function sparrow_read_orders_csv(string $file_path): array {
    $handle = fopen($file_path,'r');
    if(!$handle) throw new RuntimeException('Could not open CSV file');
    $headers = fgetcsv($handle);
    fclose($handle);
    if(!$headers) throw new RuntimeException('CSV is empty or invalid');
    $headers = array_map('trim',$headers);
    $is_meta = in_array('entry_id',$headers,true) && in_array('meta_key',$headers,true) && in_array('meta_value',$headers,true);
    if($is_meta) {
        $orders_tmp = [];
        $handle = fopen($file_path,'r'); fgetcsv($handle); // skip header
        while(($row=fgetcsv($handle))!==false){
            $entry_id = trim($row[array_search('entry_id',$headers,true)] ?? '');
            if(!$entry_id) continue;
            $meta_key = trim($row[array_search('meta_key',$headers,true)] ?? '');
            $meta_val = $row[array_search('meta_value',$headers,true)] ?? '';
            $date = $row[array_search('date_created',$headers,true)] ?? '';
            if(!isset($orders_tmp[$entry_id])) $orders_tmp[$entry_id] = ['entry_id'=>$entry_id,'date_created'=>$date,'fields'=>[]];
            $orders_tmp[$entry_id]['fields'][$meta_key]=$meta_val;
        }
        fclose($handle);
        $orders = [];
        foreach($orders_tmp as $order){
            $fields = $order['fields']??[];
            $orders[] = [
                'entry_id'=>$order['entry_id'],
                'date_created'=>$order['date_created'],
                'customer_name'=>$fields['name-1']??'',
                'customer_email'=>$fields['email-1']??'',
                'customer_phone'=>$fields['phone-1']??'',
                'status'=>$fields['hidden-1']??'Order Received',
                'order_notes'=>$fields['textarea-1']??'',
                'order_items'=>sparrow_parse_meta_items($fields),
                'raw_fields'=>$fields
            ];
        }
        return $orders;
    }
    // Wide CSV
    $handle = fopen($file_path,'r');
    $header_row = fgetcsv($handle);
    $orders=[];
    while(($row=fgetcsv($handle))!==false){
        $csv_row = sparrow_import_combine_csv_row($header_row,$row);
        $orders[] = [
            'entry_id'=>'',
            'date_created'=>$csv_row['Submission Time']??'',
            'customer_name'=>$csv_row['Name']??'',
            'customer_email'=>$csv_row['Email Address']??'',
            'customer_phone'=>$csv_row['Phone']??'',
            'status'=>$csv_row['Order Status']??'Order Received',
            'order_notes'=>$csv_row['Full Order Notes']??'',
            'order_items'=>sparrow_parse_wide_order($csv_row),
            'raw_fields'=>$csv_row
        ];
    }
    fclose($handle);
    return $orders;
}

// Handle import
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['confirm_import'] ?? '') === '1') {
    $orders_to_import = $_SESSION['sparrow_order_import_preview'] ?? [];

    if (!$orders_to_import) {
        $error = 'No previewed orders were found. Please upload and preview the CSV again before importing.';
    } else {
        $imported_count = 0;
        $skipped_count = 0;

        $seen_import_keys = [];

        foreach ($orders_to_import as $o) {
            if (empty($o['order_items'])) {
                $skipped_count++;
                continue;
            }

            $order_date = !empty($o['date_created'])
                ? date('Y-m-d H:i:s', strtotime(str_replace('@', '', $o['date_created'])))
                : date('Y-m-d H:i:s');

            $import_key = sparrow_make_order_import_key($o, $order_date);

            if (isset($seen_import_keys[$import_key])) {
                $skipped_count++;
                continue;
            }

            $seen_import_keys[$import_key] = true;

            if (sparrow_import_key_exists($import_key)) {
                $skipped_count++;
                continue;
            }

            $num = sparrow_get_next_order_number();

            $order_id = sparrow_create_order([
                'order_number' => $num,
                'customer_name' => $o['customer_name'] ?? '',
                'customer_email' => $o['customer_email'] ?? '',
                'customer_phone' => $o['customer_phone'] ?? '',
                'order_date' => $order_date,
                'status' => $o['status'] ?: 'Order Received',
                'notes' => $o['order_notes'] ?? '',
                'items' => $o['order_items'],
            ]);

            sparrow_set_order_import_key($order_id, $import_key);

            $imported_count++;
        }

        unset($_SESSION['sparrow_order_import_preview']);

        $success_message = 'Imported ' . $imported_count . ' order' . ($imported_count === 1 ? '' : 's') . ' into Backyard.';

if ($skipped_count > 0) {
    $success_message .= ' Skipped ' . $skipped_count . ' order' . ($skipped_count === 1 ? '' : 's') . '.';
}

$_SESSION['sparrow_import_notice'] = $success_message;

sparrow_redirect('/backyard/import.php');
    }
}

// Handle preview upload
elseif($_SERVER['REQUEST_METHOD']==='POST'){
    if(empty($_FILES['orders_csv']['tmp_name'])) $error='Please choose a CSV file.';
    else{
        try{
            $grouped_orders = sparrow_read_orders_csv($_FILES['orders_csv']['tmp_name']);
            $_SESSION['sparrow_order_import_preview'] = $grouped_orders;
        }catch(Throwable $e){$error=$e->getMessage();}
    }
}else{
    sparrow_redirect('/backyard/import.php');
}

sparrow_backyard_header('Preview Orders Import');
?>

<?php if ($error): ?>
    <section class="card">
        <h2>Import Error</h2>

        <p style="color:#b00020; font-weight:bold;">
            <?= sparrow_escape($error) ?>
        </p>

        <p>
            <a class="button button-secondary" href="<?= sparrow_escape(sparrow_url('/backyard/import.php')) ?>">
                Back to Imports
            </a>
        </p>
    </section>
<?php endif; ?>

<section class="card">
    <h1>Preview Orders Import</h1>
    <p class="muted">Review uploaded CSV. Nothing saved yet.</p>
    <p><a class="button button-secondary" href="<?=sparrow_escape(sparrow_url('/backyard/import.php'))?>">Back to Imports</a></p>
    <?php if($error):?><p style="color:#b00020;font-weight:bold;"><?=sparrow_escape($error)?></p><?php endif;?>
</section>
<?php if($grouped_orders):?>
<section class="card">
<h2>Import Summary</h2>
<p class="muted">Showing <?=count($grouped_orders)?> order<?=count($grouped_orders)===1?'':'s'?>. Preview only.</p>
</section>
<?php foreach($grouped_orders as $order):?>
<section class="card">
<h2><?=sparrow_escape($order['customer_name']?:'No Name')?></h2>
<p class="muted">Email: <?=sparrow_escape($order['customer_email'])?> | Phone: <?=sparrow_escape($order['customer_phone'])?><br>Status: <?=sparrow_escape($order['status'])?> | Date: <?=sparrow_escape($order['date_created'])?></p>
<?php if(!empty($order['order_items'])):?>
<div class="table-wrap">
<table>
<thead>
<tr><th>Qty</th><th>Type</th><th>Color</th><th>Size</th><th>Specialty</th><th>Print Location</th><th>Notes</th></tr>
</thead>
<tbody>
<?php foreach($order['order_items'] as $item):?>
<tr>
<td><?= (int)$item['quantity'] ?></td>
<td><?= sparrow_escape($item['item_type']) ?></td>
<td><?= sparrow_escape($item['shirt_color']) ?></td>
<td><?= sparrow_escape($item['shirt_size']) ?></td>
<td><?= sparrow_escape($item['specialty']) ?></td>
<td><?= sparrow_escape($item['print_location']) ?></td>
<td><?= sparrow_escape($item['item_notes']) ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
<?php else:?>
<p style="color:#b00020;">No items were found for this order.</p>
<?php endif;?>
</section>
<?php endforeach;?>
<section class="card">
    <h2>Import Orders</h2>

    <p class="muted">
        If the preview looks correct, click the button below to save these orders into Backyard.
    </p>

    <form method="post" action="import-orders.php">
        <input type="hidden" name="confirm_import" value="1">

        <button type="submit" class="button"
            onclick="return confirm('Import these previewed orders into Backyard?');">
            Import These Orders into Backyard
        </button>
    </form>
</section>

<?php endif; ?>

<?php sparrow_backyard_footer(); ?>