<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';

billing_require_auth();

$user = billing_current_user();
$organization = billing_current_organization();
if (!$user) {
    billing_redirect('signin.php');
}
if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

$stats = billing_dashboard_stats((int) $user['id']);
$organizationName = (string) ($organization['organization_name'] ?? 'bala');
$userLabel = (string) ($user['email'] ?? 'billing-user');
$billingTopbarOrganizationName = $organizationName;
$billingTopbarUserLabel = $userLabel;

$defaults = [
    'customer_type' => 'Business',
    'salutation' => '',
    'first_name' => '',
    'last_name' => '',
    'company_name' => '',
    'display_name' => '',
    'email' => '',
    'work_phone' => '',
    'mobile' => '',
    'customer_language' => 'English',
    'pan' => '',
    'currency' => 'INR- Indian Rupee',
    'payment_terms' => 'Due on Receipt',
    'enable_portal' => '',
    'website_url' => '',
    'department' => '',
    'designation' => '',
    'x_handle' => '',
    'skype' => '',
    'facebook' => '',
    'billing_attention' => '',
    'billing_country' => '',
    'billing_address_1' => '',
    'billing_address_2' => '',
    'billing_city' => '',
    'billing_state' => '',
    'billing_pin' => '',
    'billing_phone' => '',
    'billing_fax' => '',
    'shipping_attention' => '',
    'shipping_country' => '',
    'shipping_address_1' => '',
    'shipping_address_2' => '',
    'shipping_city' => '',
    'shipping_state' => '',
    'shipping_pin' => '',
    'shipping_phone' => '',
    'shipping_fax' => '',
    'remarks' => '',
];

function billing_import_session_key(): string
{
    return 'billing_customer_import_wizard';
}

function billing_import_temp_dir(): string
{
    $dir = dirname(__DIR__) . '/assets/tmp_imports';
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    return $dir;
}

function billing_import_normalize_header(string $header): string
{
    $header = strtolower(trim($header));
    $header = preg_replace('/[^a-z0-9]+/', '_', $header) ?? '';
    return trim($header, '_');
}

function billing_import_column_map(): array
{
    return [
        'display_name' => 'display_name',
        'customer_name' => 'display_name',
        'name' => 'display_name',
        'customer_sub_type' => 'customer_type',
        'customer_type' => 'customer_type',
        'type' => 'customer_type',
        'company_name' => 'company_name',
        'company' => 'company_name',
        'salutation' => 'salutation',
        'first_name' => 'first_name',
        'firstname' => 'first_name',
        'last_name' => 'last_name',
        'lastname' => 'last_name',
        'email' => 'email',
        'email_address' => 'email',
        'work_phone' => 'work_phone',
        'phone' => 'work_phone',
        'mobile' => 'mobile',
        'mobile_phone' => 'mobile',
        'customer_language' => 'customer_language',
        'language' => 'customer_language',
        'pan' => 'pan',
        'currency' => 'currency',
        'payment_terms' => 'payment_terms',
        'enable_portal' => 'enable_portal',
        'portal_access' => 'enable_portal',
        'website_url' => 'website_url',
        'website' => 'website_url',
        'department' => 'department',
        'designation' => 'designation',
        'x' => 'x_handle',
        'x_handle' => 'x_handle',
        'twitter' => 'x_handle',
        'skype_name_number' => 'skype',
        'skype' => 'skype',
        'facebook' => 'facebook',
        'billing_attention' => 'billing_attention',
        'billing_country' => 'billing_country',
        'billing_address' => 'billing_address_1',
        'billing_address_1' => 'billing_address_1',
        'billing_address1' => 'billing_address_1',
        'billing_address_2' => 'billing_address_2',
        'billing_address2' => 'billing_address_2',
        'billing_city' => 'billing_city',
        'billing_state' => 'billing_state',
        'billing_pin_code' => 'billing_pin',
        'billing_pin' => 'billing_pin',
        'billing_postal_code' => 'billing_pin',
        'billing_phone' => 'billing_phone',
        'billing_fax_number' => 'billing_fax',
        'billing_fax' => 'billing_fax',
        'shipping_attention' => 'shipping_attention',
        'shipping_country' => 'shipping_country',
        'shipping_address' => 'shipping_address_1',
        'shipping_address_1' => 'shipping_address_1',
        'shipping_address1' => 'shipping_address_1',
        'shipping_address_2' => 'shipping_address_2',
        'shipping_address2' => 'shipping_address_2',
        'shipping_city' => 'shipping_city',
        'shipping_state' => 'shipping_state',
        'shipping_pin_code' => 'shipping_pin',
        'shipping_pin' => 'shipping_pin',
        'shipping_postal_code' => 'shipping_pin',
        'shipping_phone' => 'shipping_phone',
        'shipping_fax_number' => 'shipping_fax',
        'shipping_fax' => 'shipping_fax',
        'remarks' => 'remarks',
        'notes' => 'remarks',
    ];
}

function billing_import_target_fields(): array
{
    return [
        'display_name' => 'Display Name *',
        'customer_type' => 'Customer Sub Type',
        'company_name' => 'Company Name',
        'salutation' => 'Salutation',
        'first_name' => 'First Name',
        'last_name' => 'Last Name',
        'facebook' => 'Facebook',
        'email' => 'Email Address',
        'work_phone' => 'Work Phone',
        'mobile' => 'Mobile',
        'customer_language' => 'Customer Language',
        'pan' => 'PAN',
        'currency' => 'Currency',
        'payment_terms' => 'Payment Terms',
        'enable_portal' => 'Portal Access',
        'website_url' => 'Website URL',
        'department' => 'Department',
        'designation' => 'Designation',
        'x_handle' => 'X',
        'skype' => 'Skype Name/Number',
        'billing_attention' => 'Billing Attention',
        'billing_country' => 'Billing Country/Region',
        'billing_address_1' => 'Billing Address Street 1',
        'billing_address_2' => 'Billing Address Street 2',
        'billing_city' => 'Billing City',
        'billing_state' => 'Billing State',
        'billing_pin' => 'Billing Pin Code',
        'billing_phone' => 'Billing Phone',
        'billing_fax' => 'Billing Fax Number',
        'shipping_attention' => 'Shipping Attention',
        'shipping_country' => 'Shipping Country/Region',
        'shipping_address_1' => 'Shipping Address Street 1',
        'shipping_address_2' => 'Shipping Address Street 2',
        'shipping_city' => 'Shipping City',
        'shipping_state' => 'Shipping State',
        'shipping_pin' => 'Shipping Pin Code',
        'shipping_phone' => 'Shipping Phone',
        'shipping_fax' => 'Shipping Fax Number',
        'remarks' => 'Remarks',
    ];
}

function billing_import_encoding_options(): array
{
    return [
        'UTF-8' => 'UTF-8 (Unicode)',
        'UTF-16' => 'UTF-16 (Unicode)',
        'ISO-8859-1' => 'ISO-8859-1',
        'ISO-8859-2' => 'ISO-8859-2',
        'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
        'GB2312' => 'GB2312 (Simplified Chinese)',
        'Big5' => 'Big5 (Traditional Chinese)',
        'Shift_JIS' => 'Shift_JIS (Japanese)',
    ];
}

function billing_import_delimiter_options(): array
{
    return [
        ',' => 'Comma ( , )',
        ';' => 'Semi-Colon ( ; )',
    ];
}

function billing_import_convert_contents(string $contents, string $encoding): string
{
    $encoding = strtoupper(trim($encoding));
    if ($encoding === 'UTF-8' || $contents === '') {
        return $contents;
    }

    if (function_exists('mb_convert_encoding')) {
        $converted = @mb_convert_encoding($contents, 'UTF-8', $encoding);
        if (is_string($converted) && $converted !== '') {
            return $converted;
        }
    }

    if (function_exists('iconv')) {
        $converted = @iconv($encoding, 'UTF-8//IGNORE', $contents);
        if (is_string($converted) && $converted !== '') {
            return $converted;
        }
    }

    return $contents;
}

function billing_import_read_rows(string $path, string $delimiter, string $encoding): array
{
    if (!is_file($path)) {
        return [];
    }

    $contents = (string) file_get_contents($path);
    $contents = billing_import_convert_contents($contents, $encoding);
    $stream = fopen('php://temp', 'r+');
    if ($stream === false) {
        return [];
    }

    fwrite($stream, $contents);
    rewind($stream);

    $rows = [];
    while (($row = fgetcsv($stream, 0, $delimiter)) !== false) {
        if ($row === [null]) {
            continue;
        }
        $rows[] = $row;
    }

    fclose($stream);
    return $rows;
}

function billing_import_auto_map(array $headers): array
{
    $aliases = billing_import_column_map();
    $targets = array_keys(billing_import_target_fields());
    $mapped = array_fill_keys($targets, '');

    foreach ($headers as $header) {
        $normalized = billing_import_normalize_header($header);
        $targetKey = $aliases[$normalized] ?? null;
        if ($targetKey !== null && isset($mapped[$targetKey]) && $mapped[$targetKey] === '') {
            $mapped[$targetKey] = $header;
        }
    }

    return $mapped;
}

function billing_import_truthy(string $value): string
{
    $value = strtolower(trim($value));
    return in_array($value, ['1', 'yes', 'y', 'true', 'enabled'], true) ? '1' : '';
}

function billing_import_build_record(array $headers, array $row, array $fieldMap, array $defaults): array
{
    $record = $defaults;
    $headerIndex = [];
    foreach ($headers as $index => $header) {
        $headerIndex[$header] = $index;
    }

    foreach ($fieldMap as $targetKey => $header) {
        if ($header === '' || !isset($headerIndex[$header])) {
            continue;
        }

        $value = billing_clean((string) ($row[$headerIndex[$header]] ?? ''));
        if ($targetKey === 'enable_portal') {
            $record[$targetKey] = billing_import_truthy($value);
            continue;
        }
        if ($targetKey === 'customer_type') {
            $record[$targetKey] = strtolower($value) === 'individual' ? 'Individual' : 'Business';
            continue;
        }

        $record[$targetKey] = $value;
    }

    if ($record['display_name'] === '') {
        $contactName = trim($record['first_name'] . ' ' . $record['last_name']);
        $record['display_name'] = $record['company_name'] !== '' ? $record['company_name'] : $contactName;
    }

    return $record;
}

function billing_import_cleanup(?array $wizard): void
{
    if (!$wizard) {
        return;
    }
    $path = (string) ($wizard['stored_path'] ?? '');
    if ($path !== '' && is_file($path)) {
        @unlink($path);
    }
}

$sessionKey = billing_import_session_key();
$wizard = is_array($_SESSION[$sessionKey] ?? null) ? $_SESSION[$sessionKey] : null;
$errors = [];
$importSummary = null;
$previewRows = [];
$currentStep = 1;

if (isset($_GET['reset']) && $_GET['reset'] === '1') {
    billing_import_cleanup($wizard);
    unset($_SESSION[$sessionKey]);
    $wizard = null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['import_action'] ?? '');

    if ($action === 'configure') {
        billing_import_cleanup($wizard);
        unset($_SESSION[$sessionKey]);
        $wizard = null;

        $duplicateHandling = in_array($_POST['duplicate_handling'] ?? 'skip', ['skip', 'overwrite', 'add'], true)
            ? (string) $_POST['duplicate_handling']
            : 'skip';
        $selectedEncoding = array_key_exists((string) ($_POST['character_encoding'] ?? 'UTF-8'), billing_import_encoding_options())
            ? (string) $_POST['character_encoding']
            : 'UTF-8';
        $selectedDelimiter = array_key_exists((string) ($_POST['file_delimiter'] ?? ','), billing_import_delimiter_options())
            ? (string) $_POST['file_delimiter']
            : ',';

        $upload = $_FILES['customer_file'] ?? null;
        if (!$upload || !isset($upload['tmp_name']) || !is_uploaded_file($upload['tmp_name'])) {
            $errors[] = 'Choose a CSV, TSV, TXT, or XLS file to continue.';
        } elseif (($upload['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
            $errors[] = 'The file upload did not complete. Please try again.';
        } else {
            $extension = strtolower(pathinfo((string) ($upload['name'] ?? ''), PATHINFO_EXTENSION));
            if (!in_array($extension, ['csv', 'txt', 'tsv', 'xls'], true)) {
                $errors[] = 'The selected file format is not supported in this demo import flow.';
            }
        }

        if ($errors === []) {
            $token = session_id() . '_' . bin2hex(random_bytes(6));
            $storedPath = billing_import_temp_dir() . '/' . $token . '.txt';
            if (!move_uploaded_file((string) $upload['tmp_name'], $storedPath)) {
                $errors[] = 'Unable to save the uploaded file right now.';
            } else {
                $readDelimiter = $extension === 'tsv' ? "\t" : $selectedDelimiter;
                $rows = billing_import_read_rows($storedPath, $readDelimiter, $selectedEncoding);
                if ($rows === []) {
                    $errors[] = 'The uploaded file is empty or could not be parsed.';
                } else {
                    $headers = array_map(static fn($value) => billing_clean((string) $value), $rows[0]);
                    $recognized = array_intersect(
                        array_map('billing_import_normalize_header', $headers),
                        array_keys(billing_import_column_map())
                    );

                    if ($recognized === []) {
                        $errors[] = 'No supported customer columns were found in the file header row.';
                    } else {
                        $wizard = [
                            'token' => $token,
                            'stored_path' => $storedPath,
                            'original_name' => (string) ($upload['name'] ?? 'customer-import.csv'),
                            'duplicate_handling' => $duplicateHandling,
                            'character_encoding' => $selectedEncoding,
                            'file_delimiter' => $selectedDelimiter,
                            'parse_delimiter' => $readDelimiter,
                            'headers' => $headers,
                            'field_map' => billing_import_auto_map($headers),
                        ];
                        $_SESSION[$sessionKey] = $wizard;
                        $currentStep = 2;
                    }
                }
            }
        }
    }

    if ($action === 'map' && $wizard) {
        $fieldMap = [];
        foreach (billing_import_target_fields() as $key => $label) {
            $selectedHeader = billing_clean((string) ($_POST['field_map'][$key] ?? ''));
            $fieldMap[$key] = in_array($selectedHeader, $wizard['headers'], true) ? $selectedHeader : '';
        }

        if ($fieldMap['display_name'] === '') {
            $errors[] = 'Map the required Display Name field before continuing.';
            $currentStep = 2;
        } else {
            $wizard['field_map'] = $fieldMap;
            $_SESSION[$sessionKey] = $wizard;
            $currentStep = 3;

            $rows = billing_import_read_rows((string) $wizard['stored_path'], (string) $wizard['parse_delimiter'], (string) $wizard['character_encoding']);
            foreach (array_slice($rows, 1, 5) as $row) {
                if ($row === [null] || implode('', array_map('trim', $row)) === '') {
                    continue;
                }
                $previewRows[] = billing_import_build_record($wizard['headers'], $row, $wizard['field_map'], $defaults);
            }
        }
    }

    if ($action === 'import' && $wizard) {
        $currentStep = 3;
        $rows = billing_import_read_rows((string) $wizard['stored_path'], (string) $wizard['parse_delimiter'], (string) $wizard['character_encoding']);
        $importSummary = [
            'total' => 0,
            'created' => 0,
            'updated' => 0,
            'skipped' => 0,
            'ignored' => 0,
            'failed' => 0,
            'details' => [],
        ];

        foreach (array_slice($rows, 1) as $row) {
            if ($row === [null] || implode('', array_map('trim', $row)) === '') {
                continue;
            }

            $record = billing_import_build_record($wizard['headers'], $row, $wizard['field_map'], $defaults);
            $status = billing_import_customer_record(
                (int) $user['id'],
                (int) $organization['id'],
                $record,
                (string) $wizard['duplicate_handling']
            );

            $importSummary['total']++;
            if (isset($importSummary[$status])) {
                $importSummary[$status]++;
            }

            if (count($importSummary['details']) < 8) {
                $importSummary['details'][] = [
                    'name' => $record['display_name'] !== '' ? $record['display_name'] : 'Unnamed row',
                    'email' => $record['email'],
                    'status' => $status,
                ];
            }
        }

        foreach (array_slice($rows, 1, 5) as $row) {
            if ($row === [null] || implode('', array_map('trim', $row)) === '') {
                continue;
            }
            $previewRows[] = billing_import_build_record($wizard['headers'], $row, $wizard['field_map'], $defaults);
        }

        if ($importSummary['total'] === 0) {
            $errors[] = 'There were no data rows to import.';
        } else {
            billing_flash('success', 'Customer import completed successfully.');
        }
    }
}

if ($wizard && $currentStep === 1) {
    $currentStep = 2;
}

if ($wizard && $currentStep === 3 && $previewRows === []) {
    $rows = billing_import_read_rows((string) $wizard['stored_path'], (string) $wizard['parse_delimiter'], (string) $wizard['character_encoding']);
    foreach (array_slice($rows, 1, 5) as $row) {
        if ($row === [null] || implode('', array_map('trim', $row)) === '') {
            continue;
        }
        $previewRows[] = billing_import_build_record($wizard['headers'], $row, $wizard['field_map'], $defaults);
    }
}

$stepDone = static function (int $step, int $currentStep): bool {
    return $step < $currentStep;
};
$stepCurrent = static function (int $step, int $currentStep): bool {
    return $step === $currentStep;
};
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title>Import | Contacts | Zoho Billing</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css">
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php $billingActiveNav = 'customers'; include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="customer-import-page">
            <section class="customer-import-wizard">
                <div class="customer-import-wizard-head">
                    <h1><?php echo $currentStep === 2 ? 'Map Fields' : ($currentStep === 3 ? 'Preview Import' : 'Customers - Select File'); ?></h1>
                    <a class="customer-import-close" href="customers.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                </div>

                <div class="customer-import-steps customer-import-steps--wizard">
                    <span class="<?php echo $stepDone(1, $currentStep) ? 'is-done' : ($stepCurrent(1, $currentStep) ? 'is-active' : ''); ?>">
                        <i class="fa-solid <?php echo $stepDone(1, $currentStep) ? 'fa-check' : 'fa-1'; ?>"></i> Configure
                    </span>
                    <span class="<?php echo $stepDone(2, $currentStep) ? 'is-done' : ($stepCurrent(2, $currentStep) ? 'is-active' : ''); ?>">
                        <i class="fa-solid <?php echo $stepDone(2, $currentStep) ? 'fa-check' : 'fa-2'; ?>"></i> Map Fields
                    </span>
                    <span class="<?php echo $stepDone(3, $currentStep) ? 'is-done' : ($stepCurrent(3, $currentStep) ? 'is-active' : ''); ?>">
                        <i class="fa-solid <?php echo $stepDone(3, $currentStep) ? 'fa-check' : 'fa-3'; ?>"></i> Preview
                    </span>
                </div>

                <?php if ($errors !== []): ?>
                    <div class="customer-import-alert customer-import-alert--error">
                        <?php foreach ($errors as $error): ?>
                            <div><?php echo billing_escape($error); ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <?php if ($currentStep === 1): ?>
                    <form method="post" enctype="multipart/form-data" class="customer-import-stage">
                        <input type="hidden" name="import_action" value="configure">
                        <div class="customer-upload-dropzone customer-upload-dropzone--wizard">
                            <label class="customer-upload-area" for="customer_file">
                                <div class="customer-upload-icon"><i class="fa-solid fa-arrow-down"></i></div>
                                <h2>Drag and drop file to import</h2>
                                <div class="customer-upload-buttons">
                                    <span class="customer-btn customer-btn--green">Choose File <i class="fa-solid fa-caret-down"></i></span>
                                </div>
                                <p>Maximum File Size: 25 MB <span>&bull;</span> File Format: CSV or TSV or XLS</p>
                                <input id="customer_file" name="customer_file" type="file" accept=".csv,.tsv,.txt,.xls" hidden>
                            </label>
                        </div>

                        <div class="customer-import-sample-copy">
                            Download a <a href="assets/customer-import-template.csv" download>sample csv file</a> and compare it to your import file to ensure you have the file perfect for the import.
                        </div>

                        <div class="customer-import-config-grid">
                            <label>Duplicate Handling: <span>*</span></label>
                            <div class="customer-import-choice-list">
                                <label class="customer-import-radio">
                                    <input type="radio" name="duplicate_handling" value="skip" checked>
                                    <span><strong>Skip Duplicates</strong><small>Retains the customers in Zoho Billing and does not import the duplicates in the import file.</small></span>
                                </label>
                                <label class="customer-import-radio">
                                    <input type="radio" name="duplicate_handling" value="overwrite">
                                    <span><strong>Overwrite customers</strong><small>Imports the duplicates in the import file and overwrites the existing customers in Zoho Billing.</small></span>
                                </label>
                                <label class="customer-import-radio">
                                    <input type="radio" name="duplicate_handling" value="add">
                                    <span><strong>Add duplicates as new customers</strong><small>Imports the duplicates in the import file and adds them as new customers in Zoho Billing.</small></span>
                                </label>
                            </div>

                            <label>Character Encoding</label>
                            <select name="character_encoding" class="customer-import-select">
                                <?php foreach (billing_import_encoding_options() as $value => $label): ?>
                                    <option value="<?php echo billing_escape($value); ?>"><?php echo billing_escape($label); ?></option>
                                <?php endforeach; ?>
                            </select>

                            <label>File Delimiter</label>
                            <select name="file_delimiter" class="customer-import-select">
                                <?php foreach (billing_import_delimiter_options() as $value => $label): ?>
                                    <option value="<?php echo billing_escape($value); ?>"><?php echo billing_escape($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="customer-import-tips">
                            <h3><i class="fa-solid fa-lightbulb"></i> Page Tips</h3>
                            <ul>
                                <li>Import data with the details of GST Treatment by referring to these accepted formats.</li>
                                <li>You can download the sample CSV file to get detailed information about the data fields used while importing.</li>
                                <li>If you have files in other formats, you can convert it to an accepted file format using any online or offline converter.</li>
                                <li>You can configure your import settings and save them for future too.</li>
                            </ul>
                        </div>

                        <div class="customer-import-actions">
                            <button class="customer-btn customer-btn--green" type="submit">Next <i class="fa-solid fa-angle-right"></i></button>
                            <a class="customer-btn" href="customers.php">Cancel</a>
                        </div>
                    </form>
                <?php elseif ($currentStep === 2 && $wizard): ?>
                    <form method="post" class="customer-import-stage">
                        <input type="hidden" name="import_action" value="map">
                        <div class="customer-import-file-meta">
                            Your Selected File : <strong><?php echo billing_escape((string) $wizard['original_name']); ?></strong>
                        </div>
                        <div class="customer-import-info-bar">
                            <i class="fa-solid fa-circle-info"></i>
                            <span>The best match to each field on the selected file have been auto-selected.</span>
                        </div>

                        <div class="customer-map-section">
                            <h2>Contact Details</h2>
                            <div class="customer-map-table">
                                <div class="customer-map-head">
                                    <span>Zoho Billing Field</span>
                                    <span>Imported File Headers</span>
                                </div>
                                <?php foreach (billing_import_target_fields() as $key => $label): ?>
                                    <label class="customer-map-row">
                                        <span><?php echo billing_escape($label); ?></span>
                                        <select name="field_map[<?php echo billing_escape($key); ?>]">
                                            <option value="">-- None --</option>
                                            <?php foreach ($wizard['headers'] as $header): ?>
                                                <option value="<?php echo billing_escape((string) $header); ?>" <?php echo (($wizard['field_map'][$key] ?? '') === $header) ? 'selected' : ''; ?>>
                                                    <?php echo billing_escape((string) $header); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="customer-import-actions">
                            <a class="customer-btn" href="customer_import.php?reset=1">Start Over</a>
                            <button class="customer-btn customer-btn--green" type="submit">Next <i class="fa-solid fa-angle-right"></i></button>
                        </div>
                    </form>
                <?php elseif ($wizard): ?>
                    <div class="customer-import-stage">
                        <div class="customer-import-file-meta">
                            Ready to import <strong><?php echo billing_escape((string) $wizard['original_name']); ?></strong> using <strong><?php echo billing_escape($wizard['duplicate_handling'] === 'skip' ? 'Skip Duplicates' : ($wizard['duplicate_handling'] === 'overwrite' ? 'Overwrite customers' : 'Add duplicates as new customers')); ?></strong>.
                        </div>

                        <div class="customer-import-info-bar">
                            <i class="fa-solid fa-table"></i>
                            <span>Preview of the first few mapped rows before import.</span>
                        </div>

                        <div class="customer-import-preview-card">
                            <table class="customer-import-table">
                                <thead>
                                    <tr>
                                        <th>Display Name</th>
                                        <th>Company Name</th>
                                        <th>Email</th>
                                        <th>Customer Type</th>
                                        <th>Phone</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($previewRows === []): ?>
                                        <tr>
                                            <td colspan="5">No preview rows are available.</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($previewRows as $row): ?>
                                            <tr>
                                                <td><?php echo billing_escape((string) $row['display_name']); ?></td>
                                                <td><?php echo billing_escape((string) $row['company_name']); ?></td>
                                                <td><?php echo billing_escape((string) $row['email']); ?></td>
                                                <td><?php echo billing_escape((string) $row['customer_type']); ?></td>
                                                <td><?php echo billing_escape((string) ($row['mobile'] !== '' ? $row['mobile'] : $row['work_phone'])); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <?php if ($importSummary): ?>
                            <div class="customer-import-alert customer-import-alert--success">
                                Imported <?php echo (int) $importSummary['total']; ?> row(s): created <?php echo (int) $importSummary['created']; ?>, updated <?php echo (int) $importSummary['updated']; ?>, skipped <?php echo (int) $importSummary['skipped']; ?>, ignored <?php echo (int) $importSummary['ignored']; ?>, failed <?php echo (int) $importSummary['failed']; ?>.
                            </div>
                            <div class="customer-import-results">
                                <h3>Import results</h3>
                                <table class="customer-import-table">
                                    <thead>
                                        <tr>
                                            <th>Customer</th>
                                            <th>Email</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($importSummary['details'] as $detail): ?>
                                            <tr>
                                                <td><?php echo billing_escape((string) $detail['name']); ?></td>
                                                <td><?php echo billing_escape((string) $detail['email']); ?></td>
                                                <td><span class="customer-status-pill customer-status-pill--<?php echo billing_escape((string) $detail['status']); ?>"><?php echo billing_escape(ucfirst((string) $detail['status'])); ?></span></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>

                        <div class="customer-import-actions">
                            <a class="customer-btn" href="customer_import.php?reset=1">Import Another File</a>
                            <?php if (!$importSummary): ?>
                                <form method="post">
                                    <input type="hidden" name="import_action" value="import">
                                    <button class="customer-btn customer-btn--green" type="submit">Import Customers</button>
                                </form>
                            <?php else: ?>
                                <a class="customer-btn customer-btn--green" href="customers.php">Open Customers</a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



