<?php
declare(strict_types=1);
@ini_set('display_errors', '0');
error_reporting(E_ALL);

require_once __DIR__ . '/../connect.php';
require_once __DIR__ . '/../config.php';

$action = $_GET['action'] ?? $_POST['action'] ?? '';
if ($action === '') {
  json_response(['error' => 'Missing action'], 400);
}

// All dashboard API routes require admin
require_admin();

switch ($action) {
  case 'list':
    do_list();
    break;
  case 'delete':
    require_method('POST');
    do_delete();
    break;
  case 'reset_all':
    require_method('POST');
    do_reset_all();
    break;
  case 'export_csv':
    do_export_csv();
    break;
  default:
    json_response(['error' => 'Unknown action'], 400);
}

function do_list(): void {
  $rows = [];
  if (defined('ENABLE_DB') && ENABLE_DB) {
    try {
      $pdo = pdo();
      ensure_registrations_table($pdo);
      $stmt = $pdo->query('SELECT id, uuid, first_name, last_name, email, phone, scfhs_id, national_id, speciality, hospital, created_at, qr_path FROM registrations ORDER BY id ASC');
      $rows = $stmt->fetchAll();
    } catch (Throwable $e) {
      $rows = read_file_storage();
    }
  } else {
    $rows = read_file_storage();
  }
  json_response(['data' => $rows]);
}

function do_delete(): void {
  $data = get_input();
  require_fields($data, ['uuid']);
  $uuid = trim((string)$data['uuid']);
  $deleted = false; $qr = null;

  if (defined('ENABLE_DB') && ENABLE_DB) {
    try {
      $pdo = pdo();
      ensure_registrations_table($pdo);
      $q = $pdo->prepare('SELECT qr_path FROM registrations WHERE uuid = :u LIMIT 1');
      $q->execute([':u' => $uuid]);
      $qr = (string)($q->fetchColumn() ?: '');

      $stmt = $pdo->prepare('DELETE FROM registrations WHERE uuid = :u');
      $stmt->execute([':u' => $uuid]);
      $deleted = $stmt->rowCount() > 0;
    } catch (Throwable $e) {
      // ignore
    }
  }

  if (!$deleted) {
    // file based fallback
    $path = __DIR__ . '/../storage/registrations/' . $uuid . '.json';
    if (is_file($path)) {
      $json = json_decode((string)@file_get_contents($path), true);
      $qr = $qr ?: (is_array($json) ? (string)($json['qr_path'] ?? '') : '');
      $deleted = @unlink($path);
    }
  }

  if ($deleted && $qr) {
    $qrPath = realpath(__DIR__ . '/../' . ltrim($qr, '/')) ?: __DIR__ . '/../' . ltrim($qr, '/');
    if (is_file($qrPath)) { @unlink($qrPath); }
  }

  json_response(['success' => $deleted]);
}

function do_reset_all(): void {
  $deletedCount = 0;
  $ok = false;
  if (defined('ENABLE_DB') && ENABLE_DB) {
    try {
      $pdo = pdo();
      ensure_registrations_table($pdo);
      $cnt = (int)$pdo->query('SELECT COUNT(*) FROM registrations')->fetchColumn();
      $pdo->exec('TRUNCATE TABLE registrations');
      $deletedCount = $cnt; $ok = true;
    } catch (Throwable $e) {
      $ok = false;
    }
  }

  // Cleanup file storage regardless (qrcodes)
  $qrDir = __DIR__ . '/../storage/qrcodes/';
  if (is_dir($qrDir)) {
    foreach (glob($qrDir . '*.*') as $f) { @unlink($f); }
  }

  if (!$ok) {
    $regDir = __DIR__ . '/../storage/registrations/';
    if (is_dir($regDir)) {
      foreach (glob($regDir . '*.json') as $f) { if (@unlink($f)) { $deletedCount++; } }
      $ok = true;
    }
  }

  json_response(['success' => $ok, 'deleted' => $deletedCount]);
}

function do_export_csv(): void {
  // Gather all registrations
  $rows = [];
  if (defined('ENABLE_DB') && ENABLE_DB) {
    try {
      $pdo = pdo();
      ensure_registrations_table($pdo);
      $stmt = $pdo->query('SELECT id, uuid, first_name, last_name, email, phone, scfhs_id, national_id, speciality, hospital, created_at FROM registrations ORDER BY id ASC');
      $rows = $stmt->fetchAll();
    } catch (Throwable $e) {
      $rows = read_file_storage();
    }
  } else {
    $rows = read_file_storage();
  }

  $filename = 'registrations-' . date('Ymd-His') . '.csv';
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=' . $filename);
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

  $out = fopen('php://output', 'w');
  // UTF-8 BOM for Excel compatibility
  fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));

  fputcsv($out, ['ID','UUID','First Name','Last Name','Email','Phone','Created At']);
  foreach ($rows as $r) {
    fputcsv($out, [
      $r['id'] ?? '',
      $r['uuid'] ?? '',
      $r['first_name'] ?? '',
      $r['last_name'] ?? '',
      $r['email'] ?? '',
      $r['phone'] ?? '',
      $r['created_at'] ?? '',
    ]);
  }
  fclose($out);
  exit;
}

function read_file_storage(): array {
  $rows = [];
  $regDir = __DIR__ . '/../storage/registrations/';
  if (is_dir($regDir)) {
    foreach (glob($regDir . '*.json') as $file) {
      $rec = json_decode((string)@file_get_contents($file), true);
      if (is_array($rec)) {
        $rows[] = [
          'id' => null,
          'uuid' => (string)($rec['uuid'] ?? ''),
          'first_name' => (string)($rec['first_name'] ?? ''),
          'last_name' => (string)($rec['last_name'] ?? ''),
          'email' => (string)($rec['email'] ?? ''),
          'phone' => (string)($rec['phone'] ?? ''),
          'scfhs_id' => (string)($rec['scfhs_id'] ?? ''),
          'national_id' => (string)($rec['national_id'] ?? ''),
          'speciality' => (string)($rec['speciality'] ?? ''),
          'hospital' => (string)($rec['hospital'] ?? ''),
          'created_at' => (string)($rec['created_at'] ?? ''),
          'qr_path' => (string)($rec['qr_path'] ?? ''),
        ];
      }
    }
  }
  return $rows;
}

function ensure_registrations_table(PDO $pdo): void {
  $sql = "CREATE TABLE IF NOT EXISTS registrations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        uuid VARCHAR(64) NOT NULL UNIQUE,
        first_name VARCHAR(100) NOT NULL,
        last_name VARCHAR(100) NOT NULL,
        email VARCHAR(255) NOT NULL,
        phone VARCHAR(20) NOT NULL,
        scfhs_id VARCHAR(50) NOT NULL,
        national_id VARCHAR(50) NOT NULL,
        speciality VARCHAR(150) NOT NULL,
        hospital VARCHAR(150) NOT NULL,
        qr_path VARCHAR(255) NULL,
        created_at DATETIME NOT NULL,
        UNIQUE KEY uniq_email (email),
        UNIQUE KEY uniq_phone (phone),
        UNIQUE KEY uniq_national_id (national_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
  $pdo->exec($sql);
  try { $pdo->exec('ALTER TABLE registrations ADD UNIQUE KEY uniq_email (email)'); } catch (Throwable $e) { /* ignore */ }
  try { $pdo->exec('ALTER TABLE registrations ADD UNIQUE KEY uniq_phone (phone)'); } catch (Throwable $e) { /* ignore */ }
  try { $pdo->exec('ALTER TABLE registrations ADD UNIQUE KEY uniq_national_id (national_id)'); } catch (Throwable $e) { /* ignore */ }
}
