<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mj_deal_helpers.php';
require_once __DIR__ . '/../includes/mj_deal_import_helpers.php';
$admin = require_admin();
mj_deal_ensure_schema();
mj_deal_import_ensure_schema();

if (isset($_GET['sample']) && $_GET['sample'] === '1') { mj_deal_import_output_sample_csv(); }
verify_csrf();

$adminTitle = 'Import Deals';
$adminSubtitle = 'Upload display-only deals by CSV. Import preview and validation run before records are created.';
$preview = $_SESSION['deal_import_preview'] ?? [];
$previewMeta = $_SESSION['deal_import_meta'] ?? [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mode = (string)($_POST['mode'] ?? 'preview');
    try {
        if ($mode === 'clear') {
            unset($_SESSION['deal_import_preview'], $_SESSION['deal_import_meta']);
            flash('success', 'Deal import preview cleared.');
            redirect('deal-import.php');
        }
        if ($mode === 'preview') {
            if (empty($_FILES['csv_file']['name']) || (int)($_FILES['csv_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                throw new RuntimeException('Please upload a CSV file.');
            }
            $name = (string)$_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 ((int)$_FILES['csv_file']['size'] > 8 * 1024 * 1024) { throw new RuntimeException('CSV file max size is 8MB. Please split bigger files.'); }
            $defaultStatus = (string)($_POST['default_status'] ?? 'draft');
            if (!in_array($defaultStatus, ['draft','pending','active','use_file'], true)) { $defaultStatus = 'draft'; }
            $duplicateMode = (string)($_POST['duplicate_mode'] ?? 'skip');
            if (!in_array($duplicateMode, ['skip','draft_anyway','update_draft'], true)) { $duplicateMode = 'skip'; }
            $rows = mj_deal_import_read_csv_assoc($_FILES['csv_file']['tmp_name'], 2000);
            if (!$rows) { throw new RuntimeException('No data rows found in CSV.'); }
            $preview = mj_deal_import_preview_rows($rows, $defaultStatus);
            $_SESSION['deal_import_preview'] = $preview;
            $_SESSION['deal_import_meta'] = ['filename'=>$name,'total'=>count($rows),'default_status'=>$defaultStatus,'duplicate_mode'=>$duplicateMode,'created_at'=>date('Y-m-d H:i:s')];
            flash('success', 'CSV preview ready. Check validation results before confirming import.');
            redirect('deal-import.php');
        }
        if ($mode === 'confirm') {
            $preview = $_SESSION['deal_import_preview'] ?? [];
            $previewMeta = $_SESSION['deal_import_meta'] ?? [];
            if (!$preview) { throw new RuntimeException('No preview data found. Please upload and preview CSV again.'); }
            $duplicateMode = (string)($previewMeta['duplicate_mode'] ?? 'skip');
            $imported = $updated = $skipped = $failed = 0;
            $messages = [];
            foreach ($preview as $row) {
                $res = mj_deal_import_insert_or_update($row, $duplicateMode);
                if ($res['status'] === 'imported') { $imported++; }
                elseif ($res['status'] === 'updated') { $updated++; }
                elseif ($res['status'] === 'skipped') { $skipped++; }
                else { $failed++; }
                if ($res['status'] !== 'imported') { $messages[] = 'Line '.(int)($row['line'] ?? 0).': '.$res['message']; }
            }
            mj_deal_import_store_log((string)($previewMeta['filename'] ?? 'deal-import.csv'), count($preview), $imported, $updated, $skipped, $failed, (string)($previewMeta['default_status'] ?? 'draft'), $duplicateMode, $messages);
            admin_log('deal_csv_import', 'mj_deal_import_logs', 0, ['imported'=>$imported,'updated'=>$updated,'skipped'=>$skipped,'failed'=>$failed]);
            unset($_SESSION['deal_import_preview'], $_SESSION['deal_import_meta']);
            flash($failed ? 'warning' : 'success', 'Deal import completed. Imported: '.$imported.' Updated: '.$updated.' Skipped: '.$skipped.' Failed: '.$failed);
            redirect('deal-import.php');
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
        redirect('deal-import.php');
    }
}

$preview = $_SESSION['deal_import_preview'] ?? [];
$previewMeta = $_SESSION['deal_import_meta'] ?? [];
$stats = ['ready'=>0,'error'=>0,'duplicate'=>0,'warning'=>0];
foreach ($preview as $p) {
    if (!empty($p['errors'])) { $stats['error']++; }
    else { $stats['ready']++; }
    if (!empty($p['warnings'])) { $stats['warning']++; }
    if ((int)($p['duplicate_id'] ?? 0) > 0) { $stats['duplicate']++; }
}
$logs = [];
try { $logs = all_rows('SELECT l.*, a.name AS admin_name FROM mj_deal_import_logs l LEFT JOIN mj_admin_users a ON a.id=l.admin_id ORDER BY l.id DESC LIMIT 20'); } catch (Throwable $e) { $logs = []; }
include __DIR__ . '/_header.php';
?>
<div class="alert alert-info border-0 shadow-sm">
  <i class="fas fa-shield-alt mr-1"></i><b>Display-only deal import:</b> This importer creates deal advertising/enquiry records only. It does not create customer checkout, voucher purchase, merchant payout, or customer-to-seller payment.
</div>
<div class="row">
  <div class="col-lg-4 col-6"><div class="small-box bg-primary"><div class="inner"><h3><?= e((string)($previewMeta['total'] ?? 0)) ?></h3><p>Rows in Preview</p></div><div class="icon"><i class="fas fa-file-csv"></i></div></div></div>
  <div class="col-lg-4 col-6"><div class="small-box bg-success"><div class="inner"><h3><?= e((string)$stats['ready']) ?></h3><p>Ready Rows</p></div><div class="icon"><i class="fas fa-check-circle"></i></div></div></div>
  <div class="col-lg-4 col-6"><div class="small-box bg-danger"><div class="inner"><h3><?= e((string)$stats['error']) ?></h3><p>Error Rows</p></div><div class="icon"><i class="fas fa-exclamation-triangle"></i></div></div></div>
</div>

<div class="card card-primary card-outline">
  <div class="card-header d-flex align-items-center">
    <h3 class="card-title"><i class="fas fa-upload mr-2"></i>Upload Deal CSV</h3>
    <div class="ml-auto"><a class="btn btn-outline-primary btn-sm" href="deal-import.php?sample=1"><i class="fas fa-download mr-1"></i>Download Sample CSV</a> <a class="btn btn-outline-secondary btn-sm" href="deals.php"><i class="fas fa-fire mr-1"></i>All Deals</a></div>
  </div>
  <form method="post" enctype="multipart/form-data">
    <?= csrf_input() ?><input type="hidden" name="mode" value="preview">
    <div class="card-body">
      <div class="form-row">
        <div class="form-group col-md-4"><label>CSV File</label><input class="form-control" type="file" name="csv_file" accept=".csv" required><small class="text-muted">Maximum 2,000 rows / 8MB per import.</small></div>
        <div class="form-group col-md-4"><label>Default Import Status</label><select class="form-control" name="default_status"><option value="draft">Draft - safest</option><option value="pending">Pending Approval</option><option value="active">Active</option><option value="use_file">Use status column from CSV</option></select><small class="text-muted">Recommended: Draft or Pending Approval.</small></div>
        <div class="form-group col-md-4"><label>Duplicate Handling</label><select class="form-control" name="duplicate_mode"><option value="skip">Skip possible duplicates</option><option value="draft_anyway">Import duplicate as Draft</option><option value="update_draft">Update existing Draft only</option></select></div>
      </div>
      <button class="btn btn-primary"><i class="fas fa-eye mr-1"></i>Upload & Preview</button>
    </div>
  </form>
</div>

<div class="card card-outline card-secondary">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-table mr-2"></i>CSV Columns</h3></div>
  <div class="card-body">
    <p class="text-muted mb-2">Required: <b>title</b> and <b>country</b>. Recommended: category_name, original_price, offer_price, end_date, phone/whatsapp/email.</p>
    <div class="table-responsive"><table class="table table-sm table-bordered mb-0"><tr>
      <?php foreach (mj_deal_import_headers() as $h): ?><td><code><?= e($h) ?></code></td><?php endforeach; ?>
    </tr></table></div>
  </div>
</div>

<?php if($preview): ?>
<div class="card card-warning card-outline">
  <div class="card-header d-flex align-items-center"><h3 class="card-title"><i class="fas fa-clipboard-check mr-2"></i>Preview & Validation</h3><div class="ml-auto"><span class="badge badge-success">Ready <?= (int)$stats['ready'] ?></span> <span class="badge badge-warning">Warnings <?= (int)$stats['warning'] ?></span> <span class="badge badge-danger">Errors <?= (int)$stats['error'] ?></span> <span class="badge badge-info">Duplicates <?= (int)$stats['duplicate'] ?></span></div></div>
  <div class="card-body">
    <?php if($stats['error'] > 0): ?><div class="alert alert-danger"><b>Please fix rows with errors before importing.</b> Rows with errors will be skipped if you continue.</div><?php endif; ?>
    <div class="table-responsive" style="max-height:520px;overflow:auto">
      <table class="table table-sm table-hover table-striped">
        <thead><tr><th>Line</th><th>Deal</th><th>Country / City</th><th>Category</th><th>Price</th><th>Status</th><th>Validation</th></tr></thead>
        <tbody>
        <?php foreach($preview as $p): $d=$p['data']; $hasErr=!empty($p['errors']); ?>
          <tr class="<?= $hasErr?'table-danger':((!empty($p['warnings']))?'table-warning':'') ?>">
            <td><?= (int)$p['line'] ?></td>
            <td><b><?= e($d['title'] ?? '') ?></b><br><small class="text-muted"><?= e($d['short_description'] ?? '') ?></small></td>
            <td><?= e($p['raw']['country'] ?? $p['raw']['country_name'] ?? '') ?><br><small><?= e($p['raw']['city'] ?? '') ?></small></td>
            <td><?= e($p['raw']['category_name'] ?? $p['raw']['category'] ?? '') ?></td>
            <td><?= e(($d['currency_code'] ?? '').' '.number_format((float)($d['deal_price'] ?? 0),2)) ?><br><small class="text-muted">Original <?= e(number_format((float)($d['original_price'] ?? 0),2)) ?></small></td>
            <td><?= mj_deal_status_badge((string)($d['status'] ?? 'draft')) ?></td>
            <td>
              <?php if($hasErr): ?><div class="text-danger"><i class="fas fa-times-circle"></i> <?= e(implode(' ', $p['errors'])) ?></div><?php else: ?><div class="text-success"><i class="fas fa-check-circle"></i> Ready</div><?php endif; ?>
              <?php if(!empty($p['warnings'])): ?><small class="text-warning"><i class="fas fa-exclamation-triangle"></i> <?= e(implode(' ', $p['warnings'])) ?></small><?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <div class="mt-3 d-flex flex-wrap">
      <form method="post" class="mr-2" onsubmit="return confirm('Confirm import? Rows with errors will be skipped.');"><?= csrf_input() ?><input type="hidden" name="mode" value="confirm"><button class="btn btn-success" <?= $stats['ready']<1?'disabled':'' ?>><i class="fas fa-check mr-1"></i>Confirm Import</button></form>
      <form method="post" onsubmit="return confirm('Clear current preview?');"><?= csrf_input() ?><input type="hidden" name="mode" value="clear"><button class="btn btn-light"><i class="fas fa-trash mr-1"></i>Clear Preview</button></form>
    </div>
  </div>
</div>
<?php endif; ?>

<div class="card card-outline card-info">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-history mr-2"></i>Recent Deal Import Logs</h3></div>
  <div class="card-body table-responsive">
    <table class="table table-sm table-striped">
      <thead><tr><th>Date</th><th>Admin</th><th>File</th><th>Total</th><th>Imported</th><th>Updated</th><th>Skipped</th><th>Failed</th><th>Status</th><th>Duplicate Mode</th></tr></thead>
      <tbody>
      <?php if(!$logs): ?><tr><td colspan="10" class="text-center text-muted py-3">No deal import logs yet.</td></tr><?php endif; ?>
      <?php foreach($logs as $l): ?><tr><td><?= e($l['created_at']) ?></td><td><?= e($l['admin_name'] ?? 'Admin') ?></td><td><?= e($l['filename']) ?></td><td><?= (int)$l['total_rows'] ?></td><td><span class="badge badge-success"><?= (int)$l['imported_rows'] ?></span></td><td><span class="badge badge-info"><?= (int)$l['updated_rows'] ?></span></td><td><span class="badge badge-warning"><?= (int)$l['skipped_rows'] ?></span></td><td><span class="badge badge-danger"><?= (int)$l['failed_rows'] ?></span></td><td><?= e($l['default_status']) ?></td><td><?= e($l['duplicate_mode']) ?></td></tr><?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . '/_footer.php'; ?>
