<?php

declare(strict_types=1);

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/supplies.php';

$user = sparrow_require_backyard_login();

function sparrow_supply_import_redirect_error(
    string $message
): void {
    header(
        'Location: ' . sparrow_url(
            '/backyard/import.php?supplies_error='
            . urlencode($message)
        )
    );
    exit;
}

function sparrow_supply_import_read_csv(
    string $path
): array {
    $handle = fopen($path, 'r');

    if ($handle === false) {
        throw new RuntimeException(
            'Could not open the supplies CSV file.'
        );
    }

    try {
        $headers = fgetcsv($handle);

        if ($headers === false) {
            throw new RuntimeException(
                'The supplies CSV file is empty.'
            );
        }

        if (isset($headers[0])) {
            $headers[0] = preg_replace(
                '/^\xEF\xBB\xBF/',
                '',
                (string) $headers[0]
            );
        }

        $headers = array_map(
            static fn ($header): string => strtolower(
                trim((string) $header)
            ),
            $headers
        );

        $required_headers = [
            'name',
            'category',
            'quantity',
            'reorder_level',
            'unit',
            'supplier',
            'unit_cost',
            'notes',
            'active',
        ];

        $missing_headers = array_diff(
            $required_headers,
            $headers
        );

        if ($missing_headers) {
            throw new RuntimeException(
                'The supplies CSV is missing: '
                . implode(', ', $missing_headers)
                . '.'
            );
        }

        $rows = [];
        $seen_names = [];
        $csv_row_number = 1;

        while (($data = fgetcsv($handle)) !== false) {
            $csv_row_number++;

            if (
                count($data) === 1
                && trim((string) ($data[0] ?? '')) === ''
            ) {
                continue;
            }

            $row = [];

            foreach ($headers as $index => $header) {
                $row[$header] = trim(
                    (string) ($data[$index] ?? '')
                );
            }

            $name = $row['name'] ?? '';

            if ($name === '') {
                throw new RuntimeException(
                    'Supply name is missing on CSV row '
                    . $csv_row_number
                    . '.'
                );
            }

            $name_key = strtolower($name);

            if (isset($seen_names[$name_key])) {
                throw new RuntimeException(
                    'The CSV contains the supply "'
                    . $name
                    . '" more than once.'
                );
            }

            $seen_names[$name_key] = true;

            foreach (
                ['quantity', 'reorder_level'] as $number_field
            ) {
                if (
                    ($row[$number_field] ?? '') === ''
                    || !is_numeric($row[$number_field])
                    || (float) $row[$number_field] < 0
                ) {
                    throw new RuntimeException(
                        ucfirst(str_replace('_', ' ', $number_field))
                        . ' is invalid for "'
                        . $name
                        . '".'
                    );
                }
            }

            if (
                ($row['unit_cost'] ?? '') !== ''
                && (
                    !is_numeric($row['unit_cost'])
                    || (float) $row['unit_cost'] < 0
                )
            ) {
                throw new RuntimeException(
                    'Unit cost is invalid for "'
                    . $name
                    . '".'
                );
            }

            $active_value = strtolower(
                (string) ($row['active'] ?? '1')
            );

            if (
                !in_array(
                    $active_value,
                    ['0', '1', 'yes', 'no', 'true', 'false'],
                    true
                )
            ) {
                throw new RuntimeException(
                    'Active status is invalid for "'
                    . $name
                    . '".'
                );
            }

            $row['quantity'] = (float) $row['quantity'];
            $row['reorder_level'] =
                (float) $row['reorder_level'];
            $row['unit_cost'] = $row['unit_cost'] === ''
                ? null
                : (float) $row['unit_cost'];
            $row['active'] = in_array(
                $active_value,
                ['1', 'yes', 'true'],
                true
            ) ? 1 : 0;

            $rows[] = $row;
        }

        return $rows;
    } finally {
        fclose($handle);
    }
}

function sparrow_supply_import_find_existing(
    PDO $pdo,
    string $name
): ?array {
    $stmt = $pdo->prepare("
        SELECT *
        FROM supplies
        WHERE LOWER(TRIM(name)) = LOWER(TRIM(:name))
        ORDER BY is_active DESC, id ASC
        LIMIT 1
    ");

    $stmt->execute([
        ':name' => $name,
    ]);

    $supply = $stmt->fetch();

    return $supply ?: null;
}

function sparrow_supply_import_insert(
    PDO $pdo,
    array $row
): int {
    $stmt = $pdo->prepare("
        INSERT INTO supplies (
            name,
            category,
            quantity,
            reorder_level,
            unit,
            supplier,
            unit_cost,
            notes,
            is_active
        ) VALUES (
            :name,
            :category,
            :quantity,
            :reorder_level,
            :unit,
            :supplier,
            :unit_cost,
            :notes,
            :is_active
        )
    ");

    $stmt->execute([
        ':name' => $row['name'],
        ':category' => $row['category'],
        ':quantity' => $row['quantity'],
        ':reorder_level' => $row['reorder_level'],
        ':unit' => $row['unit'],
        ':supplier' => $row['supplier'],
        ':unit_cost' => $row['unit_cost'],
        ':notes' => $row['notes'],
        ':is_active' => $row['active'],
    ]);

    $supply_id = (int) $pdo->lastInsertId();

    if ((float) $row['quantity'] > 0) {
        sparrow_add_supply_adjustment_record(
            $pdo,
            $supply_id,
            0,
            (float) $row['quantity'],
            'Starting Quantity',
            'Starting quantity imported from WordPress.'
        );
    }

    return $supply_id;
}

function sparrow_supply_import_update(
    PDO $pdo,
    array $existing,
    array $row
): void {
    $stmt = $pdo->prepare("
        UPDATE supplies
        SET
            name = :name,
            category = :category,
            quantity = :quantity,
            reorder_level = :reorder_level,
            unit = :unit,
            supplier = :supplier,
            unit_cost = :unit_cost,
            notes = :notes,
            is_active = :is_active
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':name' => $row['name'],
        ':category' => $row['category'],
        ':quantity' => $row['quantity'],
        ':reorder_level' => $row['reorder_level'],
        ':unit' => $row['unit'],
        ':supplier' => $row['supplier'],
        ':unit_cost' => $row['unit_cost'],
        ':notes' => $row['notes'],
        ':is_active' => $row['active'],
        ':id' => (int) $existing['id'],
    ]);

    $before_quantity = (float) $existing['quantity'];
    $after_quantity = (float) $row['quantity'];

    if (abs($after_quantity - $before_quantity) > 0.00001) {
        sparrow_add_supply_adjustment_record(
            $pdo,
            (int) $existing['id'],
            $before_quantity,
            $after_quantity,
            'Correction',
            'Quantity updated from the WordPress supplies import.'
        );
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header(
        'Location: '
        . sparrow_url('/backyard/import.php')
    );
    exit;
}

try {
    $pdo = sparrow_db();
    $action = (string) ($_POST['action'] ?? 'preview');

    if ($action === 'confirm_import') {
        $encoded_rows = (string) (
            $_POST['rows_json'] ?? ''
        );

        $rows_json = base64_decode(
            $encoded_rows,
            true
        );

        if ($rows_json === false || $rows_json === '') {
            throw new RuntimeException(
                'Import preview data was missing.'
            );
        }

        $rows = json_decode($rows_json, true);

        if (!is_array($rows) || !$rows) {
            throw new RuntimeException(
                'Import preview data was invalid.'
            );
        }

        $created = 0;
        $updated = 0;
        $skipped = 0;

        $pdo->beginTransaction();

        try {
            foreach ($rows as $row) {
                if (
                    !is_array($row)
                    || trim((string) ($row['name'] ?? '')) === ''
                ) {
                    $skipped++;
                    continue;
                }

                $existing = sparrow_supply_import_find_existing(
                    $pdo,
                    (string) $row['name']
                );

                if ($existing !== null) {
                    sparrow_supply_import_update(
                        $pdo,
                        $existing,
                        $row
                    );
                    $updated++;
                } else {
                    sparrow_supply_import_insert($pdo, $row);
                    $created++;
                }
            }

            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            throw $e;
        }

        header(
            'Location: ' . sparrow_url(
                '/backyard/import.php?supplies_imported=1'
                . '&created=' . $created
                . '&updated=' . $updated
                . '&skipped=' . $skipped
            )
        );
        exit;
    }

    if (
        empty($_FILES['supplies_csv'])
        || (
            $_FILES['supplies_csv']['error']
            ?? UPLOAD_ERR_NO_FILE
        ) !== UPLOAD_ERR_OK
    ) {
        throw new RuntimeException(
            'Please choose the WordPress supplies CSV file.'
        );
    }

    $tmp_name = (string) (
        $_FILES['supplies_csv']['tmp_name'] ?? ''
    );

    if (!is_uploaded_file($tmp_name)) {
        throw new RuntimeException(
            'The supplies CSV upload was invalid.'
        );
    }

    $rows = sparrow_supply_import_read_csv($tmp_name);

    if (!$rows) {
        throw new RuntimeException(
            'No supplies were found in this CSV file.'
        );
    }

    $preview_rows = [];
    $will_create = 0;
    $will_update = 0;

    foreach ($rows as $row) {
        $existing = sparrow_supply_import_find_existing(
            $pdo,
            (string) $row['name']
        );

        if ($existing !== null) {
            $will_update++;
        } else {
            $will_create++;
        }

        $preview_rows[] = [
            'row' => $row,
            'existing' => $existing,
        ];
    }

    $rows_json = json_encode($rows);

    if ($rows_json === false) {
        throw new RuntimeException(
            'The supplies preview could not be prepared.'
        );
    }

    $encoded_rows = base64_encode($rows_json);

    sparrow_backyard_header(
        'Preview WordPress Supplies'
    );
    ?>

    <section class="card">
        <h1>Preview WordPress Supplies</h1>

        <p class="muted">
            Nothing has been saved yet. Existing supplies are
            matched by name and updated instead of duplicated.
        </p>

        <div class="import-button-row">
            <span class="status-pill">
                <?php echo $will_create; ?> will create
            </span>

            <span class="status-pill">
                <?php echo $will_update; ?> will update
            </span>
        </div>

        <form
            method="post"
            action="<?php echo sparrow_escape(
                sparrow_url('/backyard/import-supplies.php')
            ); ?>"
        >
            <input
                type="hidden"
                name="action"
                value="confirm_import"
            >

            <input
                type="hidden"
                name="rows_json"
                value="<?php echo sparrow_escape(
                    $encoded_rows
                ); ?>"
            >

            <div class="form-actions">
                <button type="submit" class="button">
                    Import These Supplies
                </button>

                <a
                    class="button button-secondary"
                    href="<?php echo sparrow_escape(
                        sparrow_url('/backyard/import.php')
                    ); ?>"
                >
                    Cancel
                </a>
            </div>
        </form>
    </section>

    <section class="card">
        <h2>
            Supplies Found:
            <?php echo count($preview_rows); ?>
        </h2>

        <div class="table-wrap">
            <table class="table">
                <thead>
                    <tr>
                        <th>Status</th>
                        <th>Supply</th>
                        <th>Category</th>
                        <th>Quantity</th>
                        <th>Reorder At</th>
                        <th>Unit</th>
                        <th>Notes</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($preview_rows as $preview): ?>
                        <?php $row = $preview['row']; ?>
                        <tr>
                            <td>
                                <?php echo $preview['existing']
                                    ? 'Will update'
                                    : 'Will create'; ?>
                            </td>

                            <td>
                                <strong>
                                    <?php echo sparrow_escape(
                                        $row['name']
                                    ); ?>
                                </strong>
                            </td>

                            <td>
                                <?php echo sparrow_escape(
                                    $row['category']
                                ); ?>
                            </td>

                            <td>
                                <?php echo number_format(
                                    (float) $row['quantity'],
                                    2
                                ); ?>
                            </td>

                            <td>
                                <?php echo number_format(
                                    (float) $row['reorder_level'],
                                    2
                                ); ?>
                            </td>

                            <td>
                                <?php echo sparrow_escape(
                                    $row['unit']
                                ); ?>
                            </td>

                            <td>
                                <?php echo $row['notes'] !== ''
                                    ? nl2br(sparrow_escape($row['notes']))
                                    : '<span class="muted">—</span>'; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>

    <?php
    sparrow_backyard_footer();
    exit;
} catch (Throwable $e) {
    sparrow_supply_import_redirect_error(
        $e->getMessage()
    );
}