<?php
require_once __DIR__.'/../includes/importer.php';
$admin = require_admin();
verify_csrf();
$result = null;
$importType = $_POST['import_type'] ?? '';

$handlers = [
    'users' => 'mj_import_users',
    'categories' => 'mj_import_categories',
    'listings' => 'mj_import_listings',
    'companies' => 'mj_import_companies',
    'company_services' => 'mj_import_company_services',
    'company_seed' => 'mj_import_company_seed',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if ($importType === 'sample_data') {
            $result = mj_run_sample_data();
            q('INSERT INTO mj_import_logs(import_type,filename,total_rows,success_rows,failed_rows,created_at) VALUES(?,?,?,?,?,NOW())', ['sample_data','sample_data.sql',1,1,0]);
            flash('success', 'Sample data installed successfully.');
            redirect('import-center.php');
        }
        if (!isset($handlers[$importType])) { throw new RuntimeException('Invalid import type.'); }
        if (empty($_FILES['csv_file']['name']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) { throw new RuntimeException('Please upload a CSV file.'); }
        $name = $_FILES['csv_file']['name'];
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if ($ext !== 'csv') { throw new RuntimeException('Only CSV files are supported. Save Excel as CSV first.'); }
        if ($_FILES['csv_file']['size'] > 20 * 1024 * 1024) { throw new RuntimeException('CSV file max size is 20MB per upload. Split bigger files.'); }
        $rows = mj_read_csv_assoc($_FILES['csv_file']['tmp_name']);
        if (!$rows) { throw new RuntimeException('No data rows found in CSV.'); }
        $fn = $handlers[$importType];
        $result = $fn($rows);
        q('INSERT INTO mj_import_logs(import_type,filename,total_rows,success_rows,failed_rows,created_at) VALUES(?,?,?,?,?,NOW())', [$importType,$name,count($rows),(int)$result['ok'],(int)$result['bad']]);
        admin_log('csv_import_'.$importType, 'mj_import_logs', 0, ['filename'=>$name,'rows'=>count($rows),'result'=>$result]);
        flash($result['bad'] ? 'warning' : 'success', 'Import completed. Success: '.$result['ok'].' Failed: '.$result['bad']);
        if (!empty($result['errors'])) { $_SESSION['import_errors'] = $result['errors']; }
        redirect('import-center.php');
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
        redirect('import-center.php');
    }
}
$logs = all_rows('SELECT * FROM mj_import_logs ORDER BY id DESC LIMIT 25');
$templates = [
    'users' => '../import-templates/users.csv',
    'categories' => '../import-templates/categories.csv',
    'listings' => '../import-templates/listings.csv',
    'companies' => '../import-templates/companies.csv',
    'company_services' => '../import-templates/company_services.csv',
    'company_seed' => '../import-templates/company_seed.csv',
    'deals' => '../import-templates/deals.csv',
];
$errors = $_SESSION['import_errors'] ?? [];
unset($_SESSION['import_errors']);
$adminTitle = 'Import Center';
include __DIR__.'/_header.php';
?>
<h1>Import Center</h1>
<p class="muted">Import marketplace listings, companies, users, categories, services, business registry rows and demo/sample data. For Excel files, save as CSV first.</p>

<div class="grid grid-2">
  <form method="post" enctype="multipart/form-data" class="card form-card">
    <div class="card-body">
      <?=csrf_input()?>
      <h2>CSV Import</h2>
      <label class="label">Import type</label>
      <select class="form-control" name="import_type" required>
        <option value="listings">Marketplace Listings</option>
        <option value="companies">Companies / Shops / Restaurants</option>
        <option value="company_seed">Business Seed / ACRA / NEA / Google-style Data</option>
        <option value="company_services">Company Services</option>
        <option value="users">Users / Sellers</option>
        <option value="categories">Categories</option>
      </select>
      <label class="label">CSV file</label>
      <input class="form-control" type="file" name="csv_file" accept=".csv" required>
      <p class="muted">Recommended: import users/categories first, then companies/listings/services.</p>
      <button class="btn-primary">Upload & Import</button>
    </div>
  </form>

  <form method="post" class="card form-card" onsubmit="return confirm('Install demo sample data? Existing data will not be deleted.');">
    <div class="card-body">
      <?=csrf_input()?>
      <h2>One-click Sample Data</h2>
      <input type="hidden" name="import_type" value="sample_data">
      <p>Add demo users, Singapore/India locations, sample companies, branches, services, listings, offers, reviews and banners.</p>
      <button class="btn-secondary">Install Sample Data</button>
    </div>
  </form>
</div>

<?php if($errors): ?>
<div class="alert alert-warning"><b>Import warnings:</b><br><?=e(implode("\n", $errors))?></div>
<?php endif; ?>

<div class="card"><div class="card-body">
<h2>Download CSV Templates</h2>
<p><a class="btn-primary" href="deal-import.php">Deal Import</a> <span class="muted">Use the dedicated Deal Import page for preview/validation before import.</span></p>
<div class="pill-row">
<?php foreach($templates as $name=>$url): ?><a class="btn-secondary" href="<?=e($url)?>" download><?=e(ucwords(str_replace('_',' ', $name)))?></a><?php endforeach; ?>
</div>
</div></div>

<div class="card"><div class="card-body">
<h2>Import Rules</h2>
<table class="table">
<tr><th>Type</th><th>Use For</th><th>Important Columns</th></tr>
<tr><td>Listings</td><td>Products, services, rentals, cars, property, jobs, courses.</td><td>title, seller_email, country, category, price, description, city</td></tr>
<tr><td>Companies</td><td>Live company directory profiles.</td><td>company_name, owner_email, country, category, address, phone, email, website, services</td></tr>
<tr><td>Business Seed</td><td>Large ACRA/NEA/Google/Yellows Pages-style rows before owner claim.</td><td>entity_name/company_name, source, uen/source_ref, address, phone, website, services</td></tr>
<tr><td>Services</td><td>Service menu for existing companies.</td><td>company_name, service_name, price_from, duration_minutes</td></tr>
<tr><td>Users</td><td>Seller/buyer/customer accounts.</td><td>name, email, mobile, country, city</td></tr>
<tr><td>Categories</td><td>Marketplace/company category structure.</td><td>type, name, parent, icon, sort_order</td></tr>
</table>
</div></div>

<h2>Recent Import Logs</h2>
<table class="table"><tr><th>Date</th><th>Type</th><th>File</th><th>Total</th><th>Success</th><th>Failed</th></tr>
<?php foreach($logs as $l): ?><tr><td><?=e($l['created_at'])?></td><td><?=e($l['import_type'])?></td><td><?=e($l['filename'])?></td><td><?=e($l['total_rows'])?></td><td><?=e($l['success_rows'])?></td><td><?=e($l['failed_rows'])?></td></tr><?php endforeach; ?>
</table>
<?php include __DIR__.'/_footer.php'; ?>
