<?php
$pageTitle = 'Import Products by CSV';
require_once __DIR__ . '/../../app/includes/header.php'; require_admin();
require_once __DIR__ . '/../../app/includes/product_helpers.php';
require_role_access('*');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    try {
        if (empty($_FILES['csv_file']['name']) || ($_FILES['csv_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            throw new RuntimeException('Please upload a CSV file.');
        }
        $file = $_FILES['csv_file'];
        if ((int)$file['size'] > 5242880) {
            throw new RuntimeException('CSV file must be 5MB or smaller.');
        }
        if (strtolower(pathinfo((string)$file['name'], PATHINFO_EXTENSION)) !== 'csv') {
            throw new RuntimeException('Only CSV files are allowed.');
        }
        $tmp = (string)$file['tmp_name'];
        if (!is_uploaded_file($tmp) || filesize($tmp) === 0) {
            throw new RuntimeException('CSV file is empty.');
        }
        if (class_exists('finfo')) {
            $mime = (string)(new finfo(FILEINFO_MIME_TYPE))->file($tmp);
            if (!in_array($mime, ['text/plain', 'text/csv', 'application/csv', 'application/vnd.ms-excel'], true)) {
                throw new RuntimeException('Uploaded file does not look like a CSV file.');
            }
        }
        $dir = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'imports';
        if (!is_dir($dir)) { mkdir($dir, 0755, true); }
        $stored = $dir . DIRECTORY_SEPARATOR . 'products-import-' . date('Ymd-His') . '-' . bin2hex(random_bytes(3)) . '.csv';
        if (!move_uploaded_file($tmp, $stored)) {
            throw new RuntimeException('Could not store uploaded CSV.');
        }
        $_SESSION['product_import_file'] = $stored;
        redirect('/products/import-preview.php');
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
        redirect('/products/import.php');
    }
}
?>
<div class="page-head"><div><h1>Import Products by CSV</h1><p>Upload a CSV file using the required template.</p></div><a class="btn btn-outline-secondary" href="<?= APP_BASE ?>/products/sample-csv.php">Download Sample CSV</a></div>
<div class="card app-card p-4 mb-4"><p class="mb-0">Upload a CSV file using the required template. Existing products will be updated based on Product Name + Brand + Model.</p></div>
<form class="card app-card p-4" method="post" enctype="multipart/form-data">
    <?= csrf_field() ?>
    <label class="form-label">CSV File</label>
    <input class="form-control" type="file" name="csv_file" accept=".csv,text/csv" required>
    <button class="btn btn-primary mt-4" type="submit"><i class="bi bi-upload me-1"></i>Upload & Preview</button>
    <a class="btn btn-outline-secondary mt-4" href="<?= APP_BASE ?>/products/index.php">Cancel</a>
</form>
<?php require_once __DIR__ . '/../../app/includes/footer.php'; ?>
