<?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;
$billingActiveNav = 'payments_received';

function billing_payment_import_session_key(): string
{
    return 'billing_payment_import_wizard';
}

function billing_payment_received_session_key(): string
{
    return 'billing_payment_received_rows';
}

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

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

function billing_payment_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_payment_import_column_map(): array
{
    return [
        'payment_number' => 'payment_number_suffix',
        'payment_number_suffix' => 'payment_number_suffix',
        'payment_number_prefix' => 'payment_number_prefix',
        'date' => 'date',
        'payment_date' => 'date',
        'payment_status' => 'payment_status',
        'status' => 'payment_status',
        'mode' => 'mode',
        'payment_mode' => 'mode',
        'description' => 'description',
        'notes' => 'description',
        'description_of_supply' => 'description_of_supply',
        'exchange_rate' => 'exchange_rate',
        'amount' => 'amount',
        'payment_amount' => 'amount',
        'bank_charges' => 'bank_charges',
        'reference_number' => 'reference_number',
        'reference' => 'reference_number',
        'customer_name' => 'customer_name',
        'customer' => 'customer_name',
        'gst_identification_number_gstin' => 'gstin',
        'gstin' => 'gstin',
        'gst_treatment' => 'gst_treatment',
        'deposit_to' => 'deposit_to',
        'tax_account' => 'tax_account',
        'template_name' => 'template_name',
        'payment_type' => 'payment_type',
        'place_of_supply' => 'place_of_supply',
        'tax_name' => 'tax_name',
        'tax_percentage' => 'tax_percentage',
        'tax_type' => 'tax_type',
        'invoice_number' => 'invoice_number',
        'invoice' => 'invoice_number',
        'invoice_amount' => 'invoice_amount',
        'withholding_tax_amount' => 'withholding_tax_amount',
    ];
}

function billing_payment_import_target_fields(): array
{
    return [
        'payment_details' => [
            'title' => 'Payment Details',
            'rows' => [
                'payment_number_prefix' => 'Payment Number Prefix',
                'payment_number_suffix' => 'Payment Number Suffix *',
                'date' => 'Date *',
                'payment_status' => 'Payment Status',
                'mode' => 'Mode',
                'description' => 'Description',
                'description_of_supply' => 'Description of Supply',
                'exchange_rate' => 'Exchange Rate',
                'amount' => 'Amount *',
                'bank_charges' => 'Bank Charges',
                'reference_number' => 'Reference Number',
            ],
        ],
        'contact_details' => [
            'title' => 'Contact Details',
            'rows' => [
                'customer_name' => 'Customer Name',
                'gstin' => 'GST Identification Number (GSTIN)',
                'gst_treatment' => 'GST Treatment',
            ],
        ],
        'others' => [
            'title' => 'Others',
            'rows' => [
                'deposit_to' => 'Deposit To',
                'tax_account' => 'Tax Account',
                'template_name' => 'Template Name',
                'payment_type' => 'Payment Type',
                'place_of_supply' => 'Place of Supply',
                'tax_name' => 'Tax Name',
                'tax_percentage' => 'Tax Percentage',
                'tax_type' => 'Tax Type',
            ],
        ],
        'invoice_details' => [
            'title' => 'Invoice Details',
            'rows' => [
                'invoice_number' => 'Invoice Number *',
                'invoice_amount' => 'Invoice Amount',
                'withholding_tax_amount' => 'Withholding Tax Amount',
            ],
        ],
    ];
}

function billing_payment_import_flat_fields(): array
{
    $flat = [];
    foreach (billing_payment_import_target_fields() as $section) {
        foreach ($section['rows'] as $key => $label) {
            $flat[$key] = $label;
        }
    }
    return $flat;
}

function billing_payment_import_date_formats(): array
{
    return [
        'yyyy-MM-dd',
        'dd/MM/yyyy',
        'MM/dd/yyyy',
        'dd-MM-yyyy',
    ];
}

function billing_payment_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_payment_import_read_delimited_rows(string $path, string $delimiter, string $encoding): array
{
    if (!is_file($path)) {
        return [];
    }

    $contents = (string) file_get_contents($path);
    $contents = billing_payment_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[] = array_map(static fn($value) => billing_clean((string) $value), $row);
    }

    fclose($stream);
    return $rows;
}

function billing_payment_import_column_index(string $cellRef): int
{
    $letters = preg_replace('/[^A-Z]/', '', strtoupper($cellRef)) ?? '';
    $index = 0;
    $length = strlen($letters);
    for ($i = 0; $i < $length; $i++) {
        $index = ($index * 26) + (ord($letters[$i]) - 64);
    }
    return max(0, $index - 1);
}

function billing_payment_import_read_xlsx_rows(string $path): array
{
    if (!class_exists('ZipArchive')) {
        return [];
    }

    $zip = new ZipArchive();
    if ($zip->open($path) !== true) {
        return [];
    }

    $sharedStrings = [];
    $sharedStringsXml = $zip->getFromName('xl/sharedStrings.xml');
    if (is_string($sharedStringsXml) && $sharedStringsXml !== '') {
        $sharedRoot = @simplexml_load_string($sharedStringsXml);
        if ($sharedRoot instanceof SimpleXMLElement) {
            foreach ($sharedRoot->si as $stringNode) {
                $value = '';
                if (isset($stringNode->t)) {
                    $value = (string) $stringNode->t;
                } elseif (isset($stringNode->r)) {
                    foreach ($stringNode->r as $run) {
                        $value .= (string) ($run->t ?? '');
                    }
                }
                $sharedStrings[] = billing_clean($value);
            }
        }
    }

    $sheetXml = $zip->getFromName('xl/worksheets/sheet1.xml');
    $zip->close();
    if (!is_string($sheetXml) || $sheetXml === '') {
        return [];
    }

    $sheetRoot = @simplexml_load_string($sheetXml);
    if (!($sheetRoot instanceof SimpleXMLElement)) {
        return [];
    }

    $sheetRoot->registerXPathNamespace('a', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
    $rows = [];
    foreach ($sheetRoot->xpath('//a:sheetData/a:row') ?: [] as $rowNode) {
        $row = [];
        foreach ($rowNode->c as $cell) {
            $index = billing_payment_import_column_index((string) ($cell['r'] ?? 'A1'));
            $type = (string) ($cell['t'] ?? '');
            $value = '';
            if ($type === 'inlineStr') {
                $value = (string) ($cell->is->t ?? '');
            } else {
                $value = (string) ($cell->v ?? '');
            }

            if ($type === 's') {
                $sharedIndex = (int) $value;
                $value = $sharedStrings[$sharedIndex] ?? '';
            }

            $row[$index] = billing_clean($value);
        }

        if ($row === []) {
            continue;
        }

        ksort($row);
        $normalizedRow = [];
        $maxIndex = max(array_keys($row));
        for ($i = 0; $i <= $maxIndex; $i++) {
            $normalizedRow[] = $row[$i] ?? '';
        }
        $rows[] = $normalizedRow;
    }

    return $rows;
}

function billing_payment_import_parse_file(string $path, string $extension, string $delimiter, string $encoding): array
{
    if ($extension === 'xlsx') {
        return billing_payment_import_read_xlsx_rows($path);
    }

    $readDelimiter = $extension === 'tsv' ? "\t" : $delimiter;
    return billing_payment_import_read_delimited_rows($path, $readDelimiter, $encoding);
}

function billing_payment_import_auto_map(array $headers): array
{
    $aliases = billing_payment_import_column_map();
    $mapped = array_fill_keys(array_keys(billing_payment_import_flat_fields()), '');

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

    return $mapped;
}

function billing_payment_import_cleanup(?array $wizard): void
{
    if (!$wizard) {
        return;
    }

    $path = (string) ($wizard['stored_path'] ?? '');
    if ($path !== '' && is_file($path)) {
        @unlink($path);
    }
}

function billing_payment_import_match_invoice(array $record, array $invoiceLookup): ?array
{
    $invoiceNumber = strtoupper(trim((string) ($record['invoice_number'] ?? '')));
    if ($invoiceNumber === '') {
        return null;
    }

    return $invoiceLookup[$invoiceNumber] ?? null;
}

function billing_payment_import_normalize_amount(string $value): float
{
    $value = str_replace([',', "\u{20B9}", 'â‚¹', ' '], '', trim($value));
    return is_numeric($value) ? (float) $value : 0.0;
}

function billing_payment_import_convert_date(string $value, string $format): string
{
    $value = trim($value);
    if ($value === '') {
        return '';
    }

    $formatMap = [
        'yyyy-MM-dd' => 'Y-m-d',
        'dd/MM/yyyy' => 'd/m/Y',
        'MM/dd/yyyy' => 'm/d/Y',
        'dd-MM-yyyy' => 'd-m-Y',
    ];
    $phpFormat = $formatMap[$format] ?? 'Y-m-d';

    $date = DateTime::createFromFormat($phpFormat, $value);
    if ($date instanceof DateTime) {
        return $date->format('Y-m-d');
    }

    $timestamp = strtotime($value);
    return $timestamp ? date('Y-m-d', $timestamp) : '';
}

function billing_payment_import_build_record(array $headers, array $row, array $fieldMap, string $dateFormat): array
{
    $record = array_fill_keys(array_keys(billing_payment_import_flat_fields()), '');
    $headerIndex = [];
    foreach ($headers as $index => $header) {
        $headerIndex[$header] = $index;
    }

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

    $record['normalized_date'] = billing_payment_import_convert_date((string) $record['date'], $dateFormat);
    $record['normalized_amount'] = billing_payment_import_normalize_amount((string) $record['amount']);

    return $record;
}

function billing_payment_import_label_parts(string $label): array
{
    $required = str_contains($label, '*');
    $text = trim(str_replace('*', '', $label));
    return [$text, $required];
}

function billing_payment_import_preview(array $headers, array $rows, array $fieldMap, string $dateFormat, array $invoiceLookup, bool $autoGenerateNumbers): array
{
    $previewRows = [];
    $importable = 0;
    $skipped = 0;
    $messages = [];

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

        $record = billing_payment_import_build_record($headers, $row, $fieldMap, $dateFormat);
        $invoice = billing_payment_import_match_invoice($record, $invoiceLookup);
        $rowErrors = [];

        if (!$autoGenerateNumbers && $record['payment_number_suffix'] === '' && empty($fieldMap['payment_number_suffix'])) {
            $rowErrors[] = 'Missing payment number mapping.';
        }
        if ($record['normalized_date'] === '') {
            $rowErrors[] = 'Invalid or missing payment date.';
        }
        if ($record['normalized_amount'] <= 0) {
            $rowErrors[] = 'Amount must be greater than zero.';
        }
        if ($record['invoice_number'] === '') {
            $rowErrors[] = 'Invoice number is required.';
        } elseif (!$invoice) {
            $rowErrors[] = 'Invoice was not found in this organization.';
        }

        $record['customer_name'] = $record['customer_name'] !== ''
            ? $record['customer_name']
            : (string) ($invoice['customer_name'] ?? '');
        $record['reference_number'] = (string) $record['reference_number'];
        $record['mode'] = $record['mode'] !== '' ? $record['mode'] : 'Manual / Offline';
        $record['status_text'] = $rowErrors === [] ? 'Ready' : 'Skipped';
        $record['errors'] = $rowErrors;

        if ($rowErrors === []) {
            $importable++;
        } else {
            $skipped++;
        }

        if (count($previewRows) < 8) {
            $previewRows[] = $record;
        }
    }

    $requiredFieldKeys = ['date', 'amount', 'invoice_number'];
    if (!$autoGenerateNumbers) {
        array_unshift($requiredFieldKeys, 'payment_number_suffix');
    }
    foreach ($requiredFieldKeys as $key) {
        if (($fieldMap[$key] ?? '') === '') {
            $messages[] = billing_payment_import_flat_fields()[$key] . ' is not mapped.';
        }
    }

    return [
        'rows' => $previewRows,
        'importable' => $importable,
        'skipped' => $skipped,
        'unmapped' => count($messages),
        'messages' => $messages,
    ];
}

$sessionKey = billing_payment_import_session_key();
$wizard = is_array($_SESSION[$sessionKey] ?? null) ? $_SESSION[$sessionKey] : null;
$errors = [];
$preview = null;
$currentStep = 1;

$invoices = billing_get_invoices((int) $user['id'], (int) $organization['id']);
$invoiceLookup = [];
foreach ($invoices as $invoice) {
    $invoiceLookup[strtoupper((string) ($invoice['invoice_number'] ?? ''))] = $invoice;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' && isset($_GET['reset']) && $_GET['reset'] === '1') {
    billing_payment_import_cleanup($wizard);
    unset($_SESSION[$sessionKey]);
    $wizard = null;
}

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

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

        $selectedEncoding = array_key_exists((string) ($_POST['character_encoding'] ?? 'UTF-8'), billing_payment_import_encoding_options())
            ? (string) $_POST['character_encoding']
            : 'UTF-8';
        $selectedDateFormat = in_array((string) ($_POST['date_format'] ?? 'yyyy-MM-dd'), billing_payment_import_date_formats(), true)
            ? (string) $_POST['date_format']
            : 'yyyy-MM-dd';
        $autoGenerateNumbers = isset($_POST['auto_generate_payment_numbers']) ? '1' : '0';

        $upload = $_FILES['payment_file'] ?? null;
        if (!$upload || !isset($upload['tmp_name']) || !is_uploaded_file($upload['tmp_name'])) {
            $errors[] = 'Choose a CSV, TSV, or XLSX 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', 'tsv', 'txt', 'xlsx'], true)) {
                $errors[] = 'The selected file format is not supported in this payment import flow.';
            } elseif ($extension === 'xlsx' && !class_exists('ZipArchive')) {
                $errors[] = 'XLSX import is not available on this server because the PHP zip extension is missing. Please upload a CSV file or enable php_zip.';
            }
        }

        if ($errors === []) {
            $token = session_id() . '_' . bin2hex(random_bytes(6));
            $storedPath = billing_payment_import_temp_dir() . '/' . $token . '.' . $extension;
            if (!move_uploaded_file((string) $upload['tmp_name'], $storedPath)) {
                $errors[] = 'Unable to save the uploaded file right now.';
            } else {
                $rows = billing_payment_import_parse_file($storedPath, $extension, ',', $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_payment_import_normalize_header', $headers),
                        array_keys(billing_payment_import_column_map())
                    );

                    $requiredLikeHeaders = ['date', 'amount', 'invoice_number'];
                    $recognizedRequired = array_intersect($recognized, $requiredLikeHeaders);

                    if (count($recognized) < 3 || count($recognizedRequired) < 2) {
                        $errors[] = 'This file does not look like a payment import file. Please upload a CSV/XLSX with headers such as Invoice Number, Date, Amount, Payment Mode, and Reference Number.';
                    } else {
                    $wizard = [
                        'token' => $token,
                        'stored_path' => $storedPath,
                        'original_name' => (string) ($upload['name'] ?? 'payment-import.csv'),
                        'character_encoding' => $selectedEncoding,
                        'date_format' => $selectedDateFormat,
                        'auto_generate_payment_numbers' => $autoGenerateNumbers,
                        'headers' => $headers,
                        'extension' => $extension,
                        'field_map' => billing_payment_import_auto_map($headers),
                    ];

                    if ($autoGenerateNumbers === '1') {
                        $wizard['field_map']['payment_number_suffix'] = '';
                    }

                    $_SESSION[$sessionKey] = $wizard;
                    $currentStep = 2;
                    }
                }
            }
        }
    }

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

        $dateFormat = in_array((string) ($_POST['date_format'] ?? $wizard['date_format']), billing_payment_import_date_formats(), true)
            ? (string) $_POST['date_format']
            : (string) $wizard['date_format'];

        if (($wizard['auto_generate_payment_numbers'] ?? '0') === '1') {
            $fieldMap['payment_number_suffix'] = '';
        }

        if ($fieldMap['date'] === '') {
            $errors[] = 'Map the required Date field before continuing.';
        }
        if ($fieldMap['amount'] === '') {
            $errors[] = 'Map the required Amount field before continuing.';
        }
        if ($fieldMap['invoice_number'] === '') {
            $errors[] = 'Map the required Invoice Number field before continuing.';
        }
        if (($wizard['auto_generate_payment_numbers'] ?? '0') !== '1' && $fieldMap['payment_number_suffix'] === '') {
            $errors[] = 'Map the required Payment Number Suffix field or enable auto-generation.';
        }

        $wizard['field_map'] = $fieldMap;
        $wizard['date_format'] = $dateFormat;
        $_SESSION[$sessionKey] = $wizard;

        if ($errors === []) {
            $rows = billing_payment_import_parse_file((string) $wizard['stored_path'], (string) $wizard['extension'], ',', (string) $wizard['character_encoding']);
            $preview = billing_payment_import_preview(
                $wizard['headers'],
                $rows,
                $wizard['field_map'],
                $wizard['date_format'],
                $invoiceLookup,
                (($wizard['auto_generate_payment_numbers'] ?? '0') === '1')
            );
            $currentStep = 3;
        } else {
            $currentStep = 2;
        }
    }

    if ($action === 'import' && $wizard) {
        $rows = billing_payment_import_parse_file((string) $wizard['stored_path'], (string) $wizard['extension'], ',', (string) $wizard['character_encoding']);
        $preview = billing_payment_import_preview(
            $wizard['headers'],
            $rows,
            $wizard['field_map'],
            $wizard['date_format'],
            $invoiceLookup,
            (($wizard['auto_generate_payment_numbers'] ?? '0') === '1')
        );
        $currentStep = 3;

        if (($preview['importable'] ?? 0) <= 0) {
            $errors[] = 'There are no valid payment rows to import.';
        } else {
            $existingPayments = is_array($_SESSION[billing_payment_received_session_key()] ?? null)
                ? $_SESSION[billing_payment_received_session_key()]
                : [];
            $sequence = count($existingPayments) + 1;

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

                $record = billing_payment_import_build_record($wizard['headers'], $row, $wizard['field_map'], $wizard['date_format']);
                $invoice = billing_payment_import_match_invoice($record, $invoiceLookup);
                if (!$invoice || $record['normalized_date'] === '' || $record['normalized_amount'] <= 0) {
                    continue;
                }

                if (($wizard['auto_generate_payment_numbers'] ?? '0') === '1') {
                    $paymentNumber = 'PAY-' . str_pad((string) $sequence, 6, '0', STR_PAD_LEFT);
                } else {
                    $paymentNumber = (string) $record['payment_number_suffix'];
                }

                $existingPayments[] = [
                    'payment_number' => $paymentNumber,
                    'date' => $record['normalized_date'],
                    'customer_name' => $record['customer_name'] !== '' ? $record['customer_name'] : (string) ($invoice['customer_name'] ?? ''),
                    'invoice_number' => (string) $record['invoice_number'],
                    'mode' => $record['mode'] !== '' ? $record['mode'] : 'Manual / Offline',
                    'reference_number' => (string) $record['reference_number'],
                    'amount' => $record['normalized_amount'],
                    'status' => strtolower((string) ($record['payment_status'] !== '' ? $record['payment_status'] : 'completed')),
                ];
                $sequence++;
            }

            $_SESSION[billing_payment_received_session_key()] = $existingPayments;
            billing_payment_import_cleanup($wizard);
            unset($_SESSION[$sessionKey]);
            billing_flash('success', 'Payment import completed successfully.');
            billing_redirect('payments_received.php');
        }
    }
}

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

if ($wizard && $currentStep === 3 && $preview === null) {
    $rows = billing_payment_import_parse_file((string) $wizard['stored_path'], (string) $wizard['extension'], ',', (string) $wizard['character_encoding']);
    $preview = billing_payment_import_preview(
        $wizard['headers'],
        $rows,
        $wizard['field_map'],
        $wizard['date_format'],
        $invoiceLookup,
        (($wizard['auto_generate_payment_numbers'] ?? '0') === '1')
    );
}

$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 | Payments Received | 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?v=20260505-payment-import">
<style>
.payment-import-shell {
    background: #fff;
}

.payment-import-shell .customer-import-wizard {
    border-top: 1px solid #e7edf4;
    min-height: calc(100vh - 140px);
}

.payment-import-shell .customer-import-wizard-head {
    min-height: 112px;
    padding: 18px 26px 14px;
    justify-content: center;
    border-bottom: 1px solid #e7edf4;
    position: relative;
}

.payment-import-shell .customer-import-wizard-head h1 {
    font-size: 25px;
    font-weight: 500;
    color: #000;
}

.payment-import-shell .customer-import-close {
    position: absolute;
    right: 18px;
    top: 18px;
    color: #ff4d4f;
}

.payment-import-shell .customer-import-steps--wizard {
    justify-content: center;
    gap: 28px;
    padding: 0;
    margin-top: 12px;
}

.payment-import-shell .customer-import-steps--wizard span {
    position: relative;
    padding: 0;
    border: 0;
    background: transparent;
    color: #c2c9d7;
    font-size: 15px;
    font-weight: 600;
    gap: 10px;
}

.payment-import-shell .customer-import-steps--wizard span:not(:last-child)::after {
    content: "";
    width: 38px;
    height: 1px;
    background: #dde3ee;
    display: inline-block;
    margin-left: 12px;
}

.payment-import-shell .customer-import-steps--wizard span i {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #f5f7fb;
    border: 1px solid #dfe5ef;
    color: #c2c9d7;
    font-size: 15px;
}

.payment-import-shell .customer-import-steps--wizard span.is-active,
.payment-import-shell .customer-import-steps--wizard span.is-done {
    color: #111827;
}

.payment-import-shell .customer-import-steps--wizard span.is-active i {
    background: #4a89f3;
    border-color: #4a89f3;
    color: #fff;
}

.payment-import-shell .customer-import-steps--wizard span.is-done i {
    background: #21b66f;
    border-color: #21b66f;
    color: #fff;
}

.payment-import-shell .customer-import-stage {
    max-width: 1280px;
    margin: 0 auto;
    padding: 36px 22px 28px;
    gap: 26px;
}

.payment-import-shell .customer-upload-dropzone--wizard {
    max-width: 796px;
    margin: 0 auto;
    border-radius: 16px;
    border-style: dashed;
    background: #fdfdff;
}

.payment-import-shell .customer-upload-area {
    min-height: 320px;
    gap: 18px;
}

.payment-import-shell .customer-upload-icon {
    width: 72px;
    height: 72px;
    background: linear-gradient(180deg, #ffffff, #f3f4fb);
    box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
}

.payment-import-shell .customer-upload-icon i {
    color: #777388;
}

.payment-import-shell .customer-upload-area h2 {
    font-size: 20px;
    font-weight: 500;
    color: #000;
}

.payment-import-shell .customer-upload-area p,
.payment-import-shell .customer-import-sample-copy,
.payment-import-shell .payment-import-inline-note,
.payment-import-shell .payment-import-save-row label,
.payment-import-shell .payment-import-save-row small {
    color: #65748b;
    line-height: 1.6;
}

.payment-import-shell .payment-import-file-name {
    margin-top: 4px;
    color: #21a35f;
    font-size: 14px;
    font-weight: 600;
}

.payment-import-shell .customer-import-sample-copy {
    max-width: 796px;
    margin: 0 auto;
    font-size: 15px;
}

.payment-import-shell .customer-import-config-grid {
    max-width: 796px;
    margin: 0 auto;
    grid-template-columns: 250px minmax(0, 1fr);
    gap: 16px 26px;
    align-items: center;
}

.payment-import-shell .customer-import-config-grid > label {
    font-size: 16px;
    font-weight: 500;
    color: #111827;
}

.payment-import-shell .customer-import-select,
.payment-import-shell .payment-import-map-row select,
.payment-import-shell .payment-import-date-format select {
    min-height: 44px;
    border-radius: 10px;
    border-color: #d9dfeb;
    color: #546174;
    font-size: 15px;
    background: #fff;
}

.payment-import-shell .customer-import-radio {
    max-width: 796px;
    margin: 0 auto;
    align-items: flex-start;
    gap: 12px;
    border: 0;
    padding: 0;
}

.payment-import-shell .customer-import-radio strong {
    display: block;
    font-size: 16px;
    font-weight: 600;
    color: #111827;
    margin-bottom: 6px;
}

.payment-import-shell .customer-import-tips {
    max-width: 796px;
    margin: 14px auto 0;
    background: #f7f8fb;
    border: 0;
    border-radius: 16px;
    padding: 20px 28px;
}

.payment-import-shell .customer-import-tips h3 {
    font-size: 17px;
    font-weight: 700;
    margin-bottom: 12px;
}

.payment-import-shell .customer-import-tips ul {
    gap: 16px;
}

.payment-import-shell .customer-import-actions {
    max-width: 1000px;
    margin: 12px auto 0;
    padding-top: 18px;
    border-top: 1px solid #e7edf4;
    justify-content: space-between;
}

.payment-import-shell .customer-import-actions form {
    margin: 0;
}

.payment-import-shell .customer-import-file-meta {
    max-width: 1000px;
    margin: 0 auto;
    font-size: 18px;
    color: #000;
}

.payment-import-shell .customer-import-info-bar {
    max-width: 1000px;
    margin: 0 auto;
    border-radius: 12px;
    background: #edf5ff;
    border: 0;
    padding: 16px 20px;
    color: #335d98;
    box-shadow: inset 0 0 0 1px #d6e7ff;
}

.payment-import-shell .customer-import-info-bar i {
    color: #4a89f3;
}

.payment-import-shell .payment-import-defaults,
.payment-import-shell .payment-import-preview-box {
    max-width: 1000px;
    margin: 0 auto;
    border-radius: 18px;
    background: #fbfbfc;
    border: 1px solid #eef1f5;
    padding: 24px;
}

.payment-import-shell .payment-import-defaults-head h2,
.payment-import-shell .payment-import-section h2,
.payment-import-shell .payment-import-preview-box h3 {
    margin: 0;
    color: #000;
    font-size: 20px;
    font-weight: 600;
}

.payment-import-shell .payment-import-defaults-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.payment-import-shell .payment-import-date-inline {
    display: block;
}

.payment-import-shell .payment-import-defaults-head .payment-link-btn {
    font-size: 15px;
    cursor: pointer;
}

.payment-import-shell .payment-import-section {
    max-width: 1000px;
    margin: 18px auto 0;
    display: grid;
    gap: 14px;
}

.payment-import-shell .payment-import-map-table {
    border-radius: 0;
    border: 0;
    overflow: visible;
}

.payment-import-shell .payment-import-map-head,
.payment-import-shell .payment-import-map-row {
    display: grid;
    grid-template-columns: 230px minmax(0, 290px) minmax(0, 290px);
    gap: 18px;
    align-items: center;
}

.payment-import-shell .payment-import-map-head {
    padding: 0 20px 12px;
    background: transparent;
    border-bottom: 1px solid #eceff4;
    color: #7b889d;
    font-size: 12px;
    font-weight: 800;
    text-transform: uppercase;
}

.payment-import-shell .payment-import-map-head span:last-child {
    grid-column: 2 / 4;
}

.payment-import-shell .payment-import-map-row {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f3f7;
    background: #fff;
}

.payment-import-shell .payment-import-map-row:last-child {
    border-bottom: 0;
}

.payment-import-shell .payment-import-map-row > span:first-child {
    color: #111827;
    font-size: 16px;
    font-weight: 500;
}

.payment-import-shell .payment-import-required-label {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    color: #111827;
}

.payment-import-shell .payment-import-required-mark {
    color: #ff3b30;
    font-weight: 700;
}

.payment-import-shell .payment-import-date-format {
    display: flex;
    align-items: center;
    gap: 12px;
}

.payment-import-shell .payment-import-date-format select {
    width: 100%;
}

.payment-import-shell .payment-import-date-help {
    color: #8e99ac;
    font-size: 18px;
}

.payment-import-shell .payment-import-date-spacer {
    min-height: 1px;
}

.payment-import-shell .payment-import-map-row select:focus,
.payment-import-shell .payment-import-date-format select:focus {
    outline: none;
    border-color: #4a89f3;
    box-shadow: 0 0 0 3px rgba(74, 137, 243, 0.12);
}

.payment-import-shell .payment-import-save-row {
    max-width: 1000px;
    margin: 12px auto 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.payment-import-shell .payment-import-save-row input {
    width: 18px;
    height: 18px;
}

.payment-import-shell .payment-import-save-row label {
    color: #111827;
    font-weight: 500;
}

.payment-import-modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(17, 24, 39, 0.46);
    display: none;
    align-items: flex-start;
    justify-content: center;
    padding: 92px 24px 24px;
    z-index: 120;
}

.payment-import-modal-overlay.is-open {
    display: flex;
}

.payment-import-modal {
    width: min(874px, calc(100vw - 48px));
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 26px 70px rgba(15, 23, 42, 0.22);
    overflow: hidden;
}

.payment-import-modal-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 22px 24px;
    border-bottom: 1px solid #e8edf4;
}

.payment-import-modal-head h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
    color: #111827;
}

.payment-import-modal-close {
    border: 0;
    background: transparent;
    color: #ff4d4f;
    font-size: 28px;
    cursor: pointer;
}

.payment-import-modal-body {
    padding: 18px 30px 30px;
}

.payment-import-modal-table {
    width: 100%;
    border-collapse: collapse;
}

.payment-import-modal-table th,
.payment-import-modal-table td {
    padding: 14px 14px;
    border-bottom: 1px solid #e8edf4;
    text-align: left;
}

.payment-import-modal-table th {
    color: #7b889d;
    font-size: 12px;
    font-weight: 800;
    text-transform: uppercase;
}

.payment-import-modal-table td {
    color: #111827;
    font-size: 16px;
}

.payment-import-modal-table input[type="checkbox"] {
    width: 18px;
    height: 18px;
    accent-color: #4a89f3;
}

.payment-import-modal-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    padding-top: 28px;
}

.payment-import-shell .payment-import-bottom-actions {
    max-width: 1000px;
    margin: 24px auto 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    padding-top: 18px;
    border-top: 1px solid #e7edf4;
}

.payment-import-shell .payment-import-bottom-left {
    display: flex;
    align-items: center;
    gap: 14px;
}

.payment-import-shell .payment-import-preview-summary {
    max-width: 1000px;
    margin: 0 auto;
    gap: 1px;
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid #edf2f7;
}

.payment-import-shell .payment-import-preview-item {
    padding: 18px 20px;
    background: #fff;
}

.payment-import-shell .payment-import-preview-table {
    width: 100%;
    border-collapse: collapse;
}

.payment-import-shell .payment-import-preview-table th,
.payment-import-shell .payment-import-preview-table td {
    padding: 12px 14px;
    border-bottom: 1px solid #edf2f7;
    text-align: left;
    vertical-align: top;
}

.payment-import-shell .payment-import-preview-table th {
    color: #667085;
    font-size: 12px;
    font-weight: 800;
    background: #fbfcff;
}

.payment-import-shell .payment-import-preview-status {
    display: inline-flex;
    padding: 6px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 800;
}

.payment-import-shell .payment-import-preview-status.is-ready {
    background: #edf9f0;
    color: #0d6b3b;
}

.payment-import-shell .payment-import-preview-status.is-skipped {
    background: #fff4e5;
    color: #c26a16;
}

.payment-import-shell .payment-import-error-list {
    display: grid;
    gap: 6px;
    color: #b45309;
    font-size: 13px;
}

@media (max-width: 1080px) {
    .payment-import-shell .payment-import-map-head,
    .payment-import-shell .payment-import-map-row {
        grid-template-columns: 1fr;
    }

    .payment-import-shell .payment-import-map-head span:last-child {
        grid-column: auto;
    }

    .payment-import-shell .payment-import-date-spacer {
        display: none;
    }
}

@media (max-width: 720px) {
    .payment-import-shell .customer-import-config-grid {
        grid-template-columns: 1fr;
    }

    .payment-import-shell .customer-import-actions,
    .payment-import-shell .payment-import-bottom-actions,
    .payment-import-shell .payment-import-bottom-left {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php 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 payment-import-shell">
            <section class="customer-import-wizard">
                <div class="customer-import-wizard-head">
                    <h1><?php echo $currentStep === 2 ? 'Map Fields' : ($currentStep === 3 ? 'Preview' : 'Invoice Payments - Select File'); ?></h1>
                    <a class="customer-import-close" href="payments_received.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">
                        <input type="hidden" name="date_format" value="yyyy-MM-dd">
                        <div class="customer-upload-dropzone customer-upload-dropzone--wizard">
                            <label class="customer-upload-area" for="payment_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>
                                <div class="payment-import-file-name" data-payment-file-name></div>
                                <input id="payment_file" name="payment_file" type="file" accept=".csv,.tsv,.txt,.xlsx" hidden>
                            </label>
                        </div>

                        <div class="customer-import-sample-copy">
                            Download a <a href="assets/payment-import-template.csv" download>sample csv file</a> or <a href="assets/payment-import-template.csv" download>sample xls 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>Character Encoding</label>
                            <select name="character_encoding" class="customer-import-select">
                                <?php foreach (billing_payment_import_encoding_options() as $value => $label): ?>
                                    <option value="<?php echo billing_escape($value); ?>"><?php echo billing_escape($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <label class="customer-import-radio">
                            <input type="checkbox" name="auto_generate_payment_numbers" value="1">
                            <span>
                                <strong>Auto-Generate Payment Numbers</strong>
                                <small>Payment numbers will be generated automatically according to your settings. Any payment numbers in the import file will be ignored.</small>
                            </span>
                        </label>

                        <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 these <a href="#">accepted formats</a>.</li>
                                <li>You can download the <a href="assets/payment-import-template.csv" download>sample xls file</a> 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/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="payments_received.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>

                        <section class="payment-import-defaults">
                            <div class="payment-import-defaults-head">
                                <h2>Default Data Formats</h2>
                                <button class="payment-link-btn" type="button" data-payment-date-edit><i class="fa-regular fa-pen-to-square"></i> Edit</button>
                            </div>
                            <div class="payment-import-date-inline">
                                <div class="payment-import-inline-note">
                                    <strong>Date</strong><br>
                                    Select format at field level
                                </div>
                                <select name="date_format" class="customer-import-select">
                                    <?php foreach (billing_payment_import_date_formats() as $format): ?>
                                        <option value="<?php echo billing_escape($format); ?>" <?php echo $wizard['date_format'] === $format ? 'selected' : ''; ?>><?php echo billing_escape($format); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </section>

                        <?php foreach (billing_payment_import_target_fields() as $section): ?>
                            <section class="payment-import-section">
                                <h2><?php echo billing_escape((string) $section['title']); ?></h2>
                                <div class="payment-import-map-table">
                                    <div class="payment-import-map-head">
                                        <span>Zoho Billing Field</span>
                                        <span>Imported File Headers</span>
                                    </div>
                                    <?php foreach ($section['rows'] as $key => $label): ?>
                                        <?php [$labelText, $labelRequired] = billing_payment_import_label_parts((string) $label); ?>
                                        <label class="payment-import-map-row">
                                            <span class="<?php echo $labelRequired ? 'payment-import-required-label' : ''; ?>">
                                                <span><?php echo billing_escape($labelText); ?></span>
                                                <?php if ($labelRequired): ?><span class="payment-import-required-mark">*</span><?php endif; ?>
                                            </span>
                                            <select name="field_map[<?php echo billing_escape($key); ?>]" class="customer-import-select">
                                                <option value="">Select</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>
                                            <?php if ($key === 'date'): ?>
                                                <span class="payment-import-date-format">
                                                    <select name="date_format">
                                                        <?php foreach (billing_payment_import_date_formats() as $format): ?>
                                                            <option value="<?php echo billing_escape($format); ?>" <?php echo $wizard['date_format'] === $format ? 'selected' : ''; ?>><?php echo billing_escape($format); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <i class="fa-regular fa-circle-question payment-import-date-help"></i>
                                                </span>
                                            <?php else: ?>
                                                <span class="payment-import-date-spacer"></span>
                                            <?php endif; ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </section>
                        <?php endforeach; ?>

                        <div class="payment-import-save-row">
                            <input id="payment_import_save_map" type="checkbox" name="save_mapping" value="1">
                            <label for="payment_import_save_map">Save these selections for use during future imports.</label>
                            <small>Not connected to database storage yet.</small>
                        </div>

                        <div class="payment-import-bottom-actions">
                            <div class="payment-import-bottom-left">
                                <a class="customer-btn" href="payments_received_import.php?reset=1"><i class="fa-solid fa-angle-left"></i> Previous</a>
                                <button class="customer-btn customer-btn--green" type="submit">Next <i class="fa-solid fa-angle-right"></i></button>
                            </div>
                            <a class="customer-btn" href="payments_received.php">Cancel</a>
                        </div>

                        <div class="payment-import-modal-overlay" data-payment-date-modal>
                            <div class="payment-import-modal">
                                <div class="payment-import-modal-head">
                                    <h3>Default Data Formats</h3>
                                    <button class="payment-import-modal-close" type="button" data-payment-date-close aria-label="Close">&times;</button>
                                </div>
                                <div class="payment-import-modal-body">
                                    <table class="payment-import-modal-table">
                                        <thead>
                                            <tr>
                                                <th>Data Type</th>
                                                <th>Select Format at Field Level</th>
                                                <th>Default Format</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>Date</td>
                                                <td style="text-align:center;"><input type="checkbox" checked></td>
                                                <td>
                                                    <select class="customer-import-select" data-payment-date-modal-select>
                                                        <option value="">Select</option>
                                                        <?php foreach (billing_payment_import_date_formats() as $format): ?>
                                                            <option value="<?php echo billing_escape($format); ?>" <?php echo $wizard['date_format'] === $format ? 'selected' : ''; ?>><?php echo billing_escape($format); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                    <div class="payment-import-modal-actions">
                                        <button class="customer-btn customer-btn--green" type="button" data-payment-date-save>Save</button>
                                        <button class="customer-btn" type="button" data-payment-date-close>Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                <?php elseif ($wizard && $preview): ?>
                    <div class="customer-import-stage">
                        <div class="customer-import-alert <?php echo ($preview['importable'] ?? 0) > 0 ? 'customer-import-alert--success' : 'customer-import-alert--error'; ?>">
                            <?php if (($preview['importable'] ?? 0) > 0): ?>
                                <?php echo (int) $preview['importable']; ?> row(s) are ready to be imported.
                            <?php else: ?>
                                None of the rows can be imported.
                            <?php endif; ?>
                        </div>

                        <div class="payment-import-preview-summary">
                            <div class="payment-import-preview-item">
                                <strong>Invoice Payments that are ready to be imported</strong>
                                <a href="#preview-table"><?php echo (int) ($preview['importable'] ?? 0); ?> row(s)</a>
                            </div>
                            <div class="payment-import-preview-item">
                                <strong>No. of Records skipped - <?php echo (int) ($preview['skipped'] ?? 0); ?></strong>
                                <a href="#preview-table">View Details</a>
                            </div>
                            <div class="payment-import-preview-item">
                                <strong>Unmapped Fields - <?php echo (int) ($preview['unmapped'] ?? 0); ?></strong>
                                <a href="#unmapped-fields">View Details</a>
                            </div>
                        </div>

                        <section class="payment-import-preview-box" id="unmapped-fields">
                            <h3>Mapping notes</h3>
                            <?php if (($preview['messages'] ?? []) === []): ?>
                                <div class="payment-import-inline-note">All required fields have been mapped for this preview.</div>
                            <?php else: ?>
                                <ul>
                                    <?php foreach ($preview['messages'] as $message): ?>
                                        <li><?php echo billing_escape((string) $message); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                        </section>

                        <section class="payment-import-preview-box" id="preview-table">
                            <h3>Preview rows</h3>
                            <div class="customer-import-preview-card">
                                <table class="payment-import-preview-table">
                                    <thead>
                                        <tr>
                                            <th>Payment#</th>
                                            <th>Date</th>
                                            <th>Customer</th>
                                            <th>Invoice#</th>
                                            <th>Amount</th>
                                            <th>Mode</th>
                                            <th>Status</th>
                                            <th>Notes</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($preview['rows'] as $row): ?>
                                            <tr>
                                                <td><?php echo billing_escape((string) (($row['payment_number_suffix'] !== '' ? $row['payment_number_suffix'] : 'Auto Generate'))); ?></td>
                                                <td><?php echo billing_escape((string) ($row['normalized_date'] !== '' ? $row['normalized_date'] : $row['date'])); ?></td>
                                                <td><?php echo billing_escape((string) ($row['customer_name'] !== '' ? $row['customer_name'] : '-')); ?></td>
                                                <td><?php echo billing_escape((string) ($row['invoice_number'] !== '' ? $row['invoice_number'] : '-')); ?></td>
                                                <td><?php echo billing_escape((string) ($row['amount'] !== '' ? $row['amount'] : '-')); ?></td>
                                                <td><?php echo billing_escape((string) ($row['mode'] !== '' ? $row['mode'] : 'Manual / Offline')); ?></td>
                                                <td>
                                                    <span class="payment-import-preview-status <?php echo $row['status_text'] === 'Ready' ? 'is-ready' : 'is-skipped'; ?>">
                                                        <?php echo billing_escape((string) $row['status_text']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php if (($row['errors'] ?? []) === []): ?>
                                                        Ready to import
                                                    <?php else: ?>
                                                        <div class="payment-import-error-list">
                                                            <?php foreach ($row['errors'] as $message): ?>
                                                                <span><?php echo billing_escape((string) $message); ?></span>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </section>

                        <div class="customer-import-actions">
                            <a class="customer-btn" href="payments_received_import.php?reset=1">Previous</a>
                            <?php if (($preview['importable'] ?? 0) > 0): ?>
                                <form method="post">
                                    <input type="hidden" name="import_action" value="import">
                                    <button class="customer-btn customer-btn--green" type="submit">Import</button>
                                </form>
                            <?php else: ?>
                                <a class="customer-btn customer-btn--green" href="payments_received_import.php?reset=1">Fix Mapping</a>
                            <?php endif; ?>
                            <a class="customer-btn" href="payments_received.php">Cancel</a>
                        </div>
                    </div>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const fileInput = document.getElementById('payment_file');
    const fileName = document.querySelector('[data-payment-file-name]');
    const errorAlert = document.querySelector('.customer-import-alert--error');
    const dateEditButton = document.querySelector('[data-payment-date-edit]');
    const dateModal = document.querySelector('[data-payment-date-modal]');
    const dateCloseButtons = document.querySelectorAll('[data-payment-date-close]');
    const dateSaveButton = document.querySelector('[data-payment-date-save]');
    const dateModalSelect = document.querySelector('[data-payment-date-modal-select]');
    const dateInlineSelects = document.querySelectorAll('select[name="date_format"]');

    if (fileInput) {
        fileInput.addEventListener('change', function () {
            const selected = fileInput.files && fileInput.files[0] ? fileInput.files[0].name : '';
            if (fileName) {
                fileName.textContent = selected ? 'Selected file: ' + selected : '';
            }
            if (selected && errorAlert) {
                errorAlert.remove();
            }
        });
    }

    if (dateEditButton && dateModal) {
        dateEditButton.addEventListener('click', function () {
            if (dateModalSelect && dateInlineSelects.length) {
                dateModalSelect.value = dateInlineSelects[0].value;
            }
            dateModal.classList.add('is-open');
            document.body.classList.add('billing-drawer-open');
        });

        dateCloseButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                dateModal.classList.remove('is-open');
                document.body.classList.remove('billing-drawer-open');
            });
        });

        dateModal.addEventListener('click', function (event) {
            if (event.target === dateModal) {
                dateModal.classList.remove('is-open');
                document.body.classList.remove('billing-drawer-open');
            }
        });

        if (dateSaveButton) {
            dateSaveButton.addEventListener('click', function () {
                if (dateModalSelect) {
                    dateInlineSelects.forEach(function (select) {
                        select.value = dateModalSelect.value;
                    });
                }
                dateModal.classList.remove('is-open');
                document.body.classList.remove('billing-drawer-open');
            });
        }
    }
});
</script>
</body>
</html>



