<?php
// reports.php - RS Panel Reports (with column filter)
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

$userid = (int)($_SESSION['user_id'] ?? 0);
$role = $_SESSION['role'] ?? '';

// helpers
function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }
function fmt_date($d){
    if (empty($d) || $d === '0000-00-00') return '';
    return date('Y-m-d', strtotime($d));
}

/* -----------------------
   GET ALL COLUMNS FROM DATABASE (AUTO)
   ----------------------- */

$allowed_columns = [];

$res_cols = $conn->query("SHOW COLUMNS FROM products");

if ($res_cols) {
    while ($col = $res_cols->fetch_assoc()) {

        $field = $col['Field'];

        // ❌ skip unwanted columns
        if (in_array($field, ['id','created_at','updated_at'])) continue;

        // ✅ make label readable
        $label = ucwords(str_replace('_', ' ', $field));

        $allowed_columns[$field] = $label;
    }
}

/* -----------------------
   Get filters from GET
   ----------------------- */
$q = trim($_GET['q'] ?? '');
$country_id = (int)($_GET['country_id'] ?? 0);
$manufactured_by = trim($_GET['manufactured_by'] ?? '');
$marketed_by = trim($_GET['marketed_by'] ?? '');
$reg_status = trim($_GET['reg_status'] ?? 'all'); // all, active, expired
$date_from = trim($_GET['date_from'] ?? '');
$date_to = trim($_GET['date_to'] ?? '');

$per_page = 25;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $per_page;

$export = (isset($_GET['export']) && $_GET['export'] === 'csv') ? true : false;

/* -----------------------
   Column selection (from GET)
   ----------------------- */
// default columns if none selected
$default_columns = array_slice(array_keys($allowed_columns), 0, 5);
$selected_columns = $_GET['columns'] ?? $default_columns;
if (!is_array($selected_columns)) {
    // if single value, wrap as array
    $selected_columns = [$selected_columns];
}

// validate and keep order as provided by user
$valid_columns = [];
foreach ($selected_columns as $col) {
    if (isset($allowed_columns[$col])) $valid_columns[] = $col;
}
if (empty($valid_columns)) $valid_columns = $default_columns;

/* -----------------------
   Build WHERE clauses (safe escaping)
   ----------------------- */
$where = "1=1";
$parts = [];

if ($q !== '') {
    $q_esc = $conn->real_escape_string($q);
    $like = "%{$q_esc}%";
    $parts[] = "(p.product_name LIKE '{$like}' OR p.generic_name LIKE '{$like}' OR p.brand_name LIKE '{$like}' OR p.dossier_number LIKE '{$like}' OR p.registration_number LIKE '{$like}')";
}

if ($country_id > 0) {
    $parts[] = "p.country_id = " . intval($country_id);
}

if ($manufactured_by !== '') {
    $m_esc = $conn->real_escape_string($manufactured_by);
    $parts[] = "p.manufactured_by LIKE '%{$m_esc}%'";
}

if ($marketed_by !== '') {
    $mk_esc = $conn->real_escape_string($marketed_by);
    $parts[] = "p.marketed_by LIKE '%{$mk_esc}%'";
}

// registration status
$today = date('Y-m-d');
if ($reg_status === 'active') {
    // consider active if expiry is null or expiry >= today
    $parts[] = "(p.registration_exp_date IS NULL OR p.registration_exp_date = '' OR p.registration_exp_date >= '{$today}')";
} elseif ($reg_status === 'expired') {
    $parts[] = "(p.registration_exp_date IS NOT NULL AND p.registration_exp_date <> '' AND p.registration_exp_date < '{$today}')";
}

// created_at / date range (filter by created_at)
if ($date_from !== '') {
    $df = date('Y-m-d', strtotime(str_replace('/', '-', $date_from)));
    $parts[] = "DATE(p.created_at) >= '{$df}'";
}
if ($date_to !== '') {
    $dt = date('Y-m-d', strtotime($date_to));
    $parts[] = "DATE(p.created_at) <= '{$dt}'";
}

if (!empty($parts)) $where .= ' AND ' . implode(' AND ', $parts);

/* -----------------------
   Count total rows
   ----------------------- */
$count_sql = "SELECT COUNT(*) as cnt FROM products p WHERE {$where}";
$res = $conn->query($count_sql);
$total = 0;
if ($res) {
    $row = $res->fetch_assoc();
    $total = (int)$row['cnt'];
    $res->free();
}

/* -----------------------
   If CSV export requested - output CSV and exit
   ----------------------- */
/* Build CSV headers dynamically based on selected columns + standard extras.
   We'll avoid duplicate columns. */
$standard_extra_cols = [
    'country_name' => 'Country',
    'registration_number' => 'Registration Number',
    'registration_date' => 'Registration Date',
    'registration_exp_date' => 'Registration Expiry',
    'qty' => 'Qty',
    'created_by_name' => 'Created By',
    'created_at' => 'Created At',
    'file_path' => 'File Path'
];

if ($export) {
    $sql = "SELECT p.*, c.country_name, u.name AS created_by_name
            FROM products p
            LEFT JOIN countries c ON p.country_id = c.id
            LEFT JOIN users u ON p.created_by = u.id
            WHERE {$where}
            ORDER BY p.created_at DESC";
    $result = $conn->query($sql);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=products_report_' . date('Ymd_His') . '.csv');

    $out = fopen('php://output', 'w');

    // build header row (use labels)
    $headers = [];
    $seen = [];

    // selected columns first
    foreach ($valid_columns as $col) {
        if (isset($allowed_columns[$col]) && !isset($seen[$col])) {
            $headers[] = $allowed_columns[$col];
            $seen[$col] = true;
        }
    }

    // then add standard extras if not already included
    foreach ($standard_extra_cols as $key => $label) {
        // map db key to a comparable column key if possible
        // (registration_number/registration_date etc might already be in selected)
        if (strpos($key, 'registration_') === 0) {
            $comp_key = $key; // registration_date, registration_exp_date
        } elseif ($key === 'country_name') {
            $comp_key = 'country_name';
        } elseif ($key === 'created_by_name') {
            $comp_key = 'created_by_name';
        } else {
            $comp_key = $key;
        }

        // check whether equivalent was already selected (e.g. registration_number)
        if (!$seen[$comp_key]) {
            $headers[] = $label;
            $seen[$comp_key] = true;
        }
    }

    // write header
    fputcsv($out, $headers);

    // write rows
    if ($result) {
        while ($r = $result->fetch_assoc()) {
            $row_out = [];

            // selected columns values
            foreach ($valid_columns as $col) {
                // some selected columns map to fields in $r (e.g. file_path, registration_date)
                $val = $r[$col] ?? '';
                // format dates appropriately
                if (in_array($col, ['registration_date','registration_exp_date']) && $val && $val !== '0000-00-00') {
                    $val = date('Y-m-d', strtotime($val));
                }
                $row_out[] = $val;
            }

            // standard extras (only those not already included)
            foreach ($standard_extra_cols as $key => $label) {
                // skip if the key is already in selected columns
                if (in_array($key, $valid_columns) || in_array($key, ['registration_number','registration_date','registration_exp_date','qty','file_path']) && in_array($key, $valid_columns)) {
                    continue;
                }

                if ($key === 'country_name') {
                    $row_out[] = $r['country_name'] ?? '';
                } elseif ($key === 'created_by_name') {
                    $row_out[] = $r['created_by_name'] ?? '';
                } elseif ($key === 'file_path') {
                    $row_out[] = $r['file_path'] ?? '';
                } else {
                    $v = $r[$key] ?? '';
                    if (in_array($key, ['registration_date','registration_exp_date']) && $v && $v !== '0000-00-00') {
                        $v = date('Y-m-d', strtotime($v));
                    }
                    $row_out[] = $v;
                }
            }

            fputcsv($out, $row_out);
        }
        $result->free();
    }

    fclose($out);
    exit;
}

/* -----------------------
   Fetch page rows
   ----------------------- */
$sql = "SELECT p.*, c.country_name, u.name AS created_by_name
        FROM products p
        LEFT JOIN countries c ON p.country_id = c.id
        LEFT JOIN users u ON p.created_by = u.id
        WHERE {$where}
        ORDER BY p.created_at DESC
        LIMIT " . intval($offset) . "," . intval($per_page);

$result = $conn->query($sql);

/* -----------------------
   Load countries for filter
   ----------------------- */
$countries = [];
$resc = $conn->query("SELECT id, country_name FROM countries ORDER BY country_name");
if ($resc) {
    while ($r = $resc->fetch_assoc()) $countries[] = $r;
    $resc->free();
}

/* -----------------------
   Render HTML
   ----------------------- */
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reports - RS Panel</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
  --bg:#eef3f9;
  --surface:#ffffff;
  --surface-2:#f8fbff;
  --surface-3:#f3f6fb;
  --border:#dce3ee;
  --border-strong:#cbd5e1;
  --text:#0f172a;
  --muted:#64748b;

  --primary:#374155;
  --primary-dark:#273142;
  --primary-soft:#eef2f7;

  --success:#16a34a;
  --danger:#dc2626;
  --warning:#d97706;
  --info:#2563eb;

  --shadow:0 16px 40px rgba(15,23,42,.08);
  --shadow-soft:0 8px 20px rgba(15,23,42,.05);
  --radius:20px;
}

*{
  box-sizing:border-box;
}

body{
  margin:0;
  padding:78px 18px 24px;
  font-family:Inter, Segoe UI, Arial, sans-serif;
  background:linear-gradient(180deg,#eef3f9 0%, #e9eef6 100%);
  color:var(--text);
}

.container{
  max-width:1500px;
  margin:auto;
}

.card{
  margin-left:260px;
  background:var(--surface);
  border:1px solid var(--border);
  border-radius:var(--radius);
  box-shadow:var(--shadow);
  padding:24px;
}

h1{
  margin:0 0 18px;
  font-size:26px;
  line-height:1.2;
  font-weight:900;
  letter-spacing:-0.03em;
  color:var(--primary);
}

/* ===== FILTERS ===== */
.filters{
  display:grid;
  grid-template-columns:repeat(auto-fit, minmax(220px, 1fr));
  gap:14px;
  align-items:end;
  padding:18px;
  margin-bottom:18px;
  background:linear-gradient(180deg,#ffffff,#fbfdff);
  border:1px solid var(--border);
  border-radius:18px;
  box-shadow:var(--shadow-soft);
}

.filter-group{
  display:flex;
  flex-direction:column;
  gap:7px;
  min-width:0;
}

.filter-group label{
  font-size:12px;
  font-weight:800;
  color:var(--primary);
  text-transform:uppercase;
  letter-spacing:.06em;
}

.input{
  width:100%;
  height:44px;
  padding:10px 12px;
  border:1px solid var(--border-strong);
  border-radius:12px;
  background:#fff;
  color:var(--text);
  font-size:13px;
  outline:none;
  transition:all .2s ease;
}

.input:hover{
  border-color:#b7c2d1;
}

.input:focus{
  border-color:var(--primary);
  box-shadow:0 0 0 4px rgba(55,65,85,.10);
}

.filter-actions{
  display:flex;
  gap:10px;
  align-items:end;
  justify-content:flex-start;
  flex-wrap:wrap;
}

/* ===== BUTTONS ===== */
.btn,
.btn-secondary{
  min-height:42px;
  padding:0 15px;
  border-radius:12px;
  font-size:13px;
  font-weight:800;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  white-space:nowrap;
  text-decoration:none;
  cursor:pointer;
  transition:all .22s ease;
}

.btn{
  border:none;
  background:linear-gradient(135deg,var(--primary),var(--primary-dark));
  color:#fff;
  box-shadow:0 10px 22px rgba(55,65,85,.18);
}

.btn:hover{
  transform:translateY(-1px);
  box-shadow:0 14px 26px rgba(55,65,85,.22);
}

.btn-secondary{
  border:1px solid var(--border-strong);
  background:#fff;
  color:var(--primary);
}

.btn-secondary:hover{
  border-color:var(--primary);
  background:#f8fafc;
  transform:translateY(-1px);
}

/* ===== COLUMNS DROPDOWN ===== */
.columns-wrap{
  position:relative;
  display:inline-block;
}

#columnDropdown{
  display:none;
  position:absolute;
  top:48px;
  left:0;
  z-index:100;
  width:360px;
  padding:14px;
  background:#fff;
  border:1px solid var(--border);
  border-radius:16px;
  box-shadow:var(--shadow);
}

.column-grid{
  display:grid;
  grid-template-columns:repeat(2,minmax(0,1fr));
  gap:8px;
  max-height:260px;
  overflow:auto;
  padding-right:4px;
}

.column-grid label{
  display:flex;
  align-items:center;
  gap:8px;
  padding:9px 10px;
  border:1px solid #e9edf3;
  border-radius:10px;
  background:#fff;
  font-size:13px;
  color:var(--text);
  transition:all .2s ease;
}

.column-grid label:hover{
  border-color:#cfd8e3;
  background:#f8fafc;
}

.column-grid input{
  accent-color:var(--primary);
}

.col-apply{
  margin-top:12px;
  display:flex;
  justify-content:flex-end;
}

/* ===== TABLE ===== */
.table{
  width:100%;
  margin-top:14px;
  border-collapse:separate;
  border-spacing:0;
  background:#fff;
  border:1px solid var(--border);
  border-radius:16px;
  overflow:hidden;
  box-shadow:var(--shadow-soft);
}

.table thead th{
  position:sticky;
  top:0;
  z-index:1;
  background:linear-gradient(135deg,var(--primary),var(--primary-dark));
  color:#fff;
  font-weight:800;
  text-align:left;
  border-bottom:1px solid rgba(255,255,255,.08);
  padding:14px 14px;
  font-size:13px;
  letter-spacing:.02em;
  white-space:nowrap;
}

.table th,
.table td{
  padding:12px 14px;
  border-bottom:1px solid #edf0f3;
  font-size:13px;
  color:var(--text);
  vertical-align:top;
}

.table tbody tr:nth-child(even){
  background:#fafbfd;
}

.table tbody tr:hover{
  background:#f5f8fc;
}

.table tbody td{
  line-height:1.45;
}

.badge{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  padding:5px 10px;
  border-radius:999px;
  font-size:11px;
  font-weight:800;
  line-height:1;
}

.file-link{
  color:var(--primary);
  text-decoration:none;
  font-weight:800;
  display:inline-flex;
  align-items:center;
  gap:6px;
}

.file-link:hover{
  color:#111827;
  text-decoration:underline;
}

.small{
  font-size:12px;
  color:var(--muted);
}

/* ===== PAGINATION ===== */
.pager{
  margin-top:18px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  flex-wrap:wrap;
  gap:12px;
}

.pager > div{
  display:flex;
  flex-wrap:wrap;
  align-items:center;
  gap:10px;
}

/* ===== PAGE TOP CARD LOOK ===== */
.card > h1{
  display:flex;
  align-items:center;
  gap:10px;
}

.card > h1::before{
  content:"";
  width:12px;
  height:12px;
  border-radius:999px;
  background:var(--primary);
  display:inline-block;
}
/* HEADER WITH ICON */
.page-header{
  margin-bottom:18px;
}

.page-header .title{
  display:flex;
  align-items:center;
  gap:10px;
}

.page-header h1{
  margin:0;
  font-size:26px;
  font-weight:900;
  color:#374155;
}

/* ICON STYLE */
.page-header .icon{
  background:#eef2f7;
  color:#374155;
  width:38px;
  height:38px;
  border-radius:10px;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:16px;
}

/* ===== RESPONSIVE ===== */
@media(max-width:1100px){
  .card{
    margin-left:0;
  }
}

@media(max-width:900px){
  body{
    padding:68px 14px 18px;
  }

  .card{
    padding:16px;
  }

  #columnDropdown{
    width:min(360px, 92vw);
  }
}

@media(max-width:640px){
  .filters{
    grid-template-columns:1fr;
  }

  .table{
    display:block;
    overflow-x:auto;
    white-space:nowrap;
  }

  .pager{
    flex-direction:column;
    align-items:flex-start;
  }
}

</style>
</head>
<body>
  <div class="container">
    <?php include 'rasidebar.php'; ?>
    <?php include '../header.php'; ?>

    <div class="card" >
<div class="page-header">
  <div class="title">
    <i class="fa-solid fa-chart-line icon"></i>
    <h1>Products Report</h1>
  </div>
  <p class="subtitle">Manage and analyze all product data</p>
</div>
<form method="get" class="filters">
  <div class="filter-group">
    <label>Search</label>
    <input type="text" name="q" class="input" value="<?php echo e($q); ?>">
  </div>

  <div class="filter-group">
    <label>Country</label>
    <select name="country_id" class="input">
      <option value="0">All</option>
      <?php foreach ($countries as $c): ?>
        <option value="<?php echo $c['id']; ?>" <?php if ($country_id==$c['id']) echo 'selected'; ?>>
          <?php echo e($c['country_name']); ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

 

  <div class="filter-group">
    <label>From</label>
    <input type="date" name="date_from" class="input" value="<?php echo e($date_from); ?>">
  </div>

  <div class="filter-group">
    <label>To</label>
    <input type="date" name="date_to" class="input" value="<?php echo e($date_to); ?>">
  </div>


  <!-- Column selector -->
  <div class="filter-group columns-wrap">
    <label>Columns</label>
    <button type="button" class="btn-secondary" onclick="toggleColumns()">Select Columns ▾</button>

    <div id="columnDropdown">
      <div class="filter-actions">
      

        <div class="column-grid">
          <?php foreach ($allowed_columns as $key => $label): ?>
            <label style="font-size:13px;">
          <input type="checkbox" name="columns[]" value="<?php echo e($key); ?>" <?php if(in_array($key,$valid_columns)) echo 'checked'; ?>>              <?php echo e($label); ?>
            </label>
          <?php endforeach; ?>
        </div>

        <div class="col-apply">
          <button type="button" class="btn" onclick="applyColumns()"><i class="fa fa-check"></i> Apply</button>
        </div>
     </div>
    </div>
    
  
  </div>

<div class="filter-actions">
    <button type="submit" class="btn"><i class="fa fa-filter"></i> Filter</button>

    <a href="reports.php" class="btn-secondary">Reset</a>

    <?php
      $get = $_GET;
      $get['export']='csv';
    ?>
    <a href="reports.php?<?php echo http_build_query($get); ?>" class="btn-secondary">
      <i class="fa fa-download"></i> Export
    </a>
  </div>
</form>


      <table class="table">
        <thead>
          <tr>
            <th style="width:60px">ID</th>

            <!-- dynamic selected columns -->
            <?php foreach ($valid_columns as $col): ?>
              <th><?php echo e($allowed_columns[$col]); ?></th>
            <?php endforeach; ?>

            <!-- add some useful defaults but avoid duplicates -->
            <?php
              $extras = ['country_name' => 'Country', 'registration_exp_date'=>'Expiry', 'file_path'=>'File'];
              // determine which extras to show (skip if equivalent in valid_columns)
              $skip_keys = $valid_columns;
            ?>
            <?php foreach ($extras as $k => $label): ?>
              <?php
                $show = true;
                // map extras to comparable column names present in $valid_columns
                if ($k === 'registration_exp_date' && in_array('registration_exp_date', $skip_keys)) $show = false;
                if ($k === 'file_path' && in_array('file_path', $skip_keys)) $show = false;
                if ($k === 'created_at' && in_array('created_at', $skip_keys)) $show = false;
                if ($k === 'country_name' && in_array('country_name', $skip_keys)) $show = false;
              ?>
              <?php if ($show): ?>
                <th><?php echo e($label); ?></th>
              <?php endif; ?>
            <?php endforeach; ?>

          </tr>
        </thead>
        <tbody>
          <?php if ($result && $result->num_rows): $i = $offset + 1; ?>
            <?php while ($r = $result->fetch_assoc()): ?>
              <tr>
                <td><?php echo $i++; ?></td>

                <!-- render selected columns -->
                <?php foreach ($valid_columns as $col): ?>
                  <td>
                    <?php
                      $val = $r[$col] ?? '';
                      if (in_array($col, ['registration_date','registration_exp_date']) && $val && $val !== '0000-00-00') {
                        $val = date('Y-m-d', strtotime($val));
                      }
                      // show file link if file_path column selected
                      if ($col === 'file_path') {
                        if (!empty($val)) {
                          echo '<a class="file-link" href="../'.e($val).'" target="_blank"><i class="fa fa-file"></i> View</a>';
                        } else {
                          echo '<span class="small">-</span>';
                        }
                      } else {
                        echo e($val);
                      }
                    ?>
                  </td>
                <?php endforeach; ?>

                <!-- extras (Country, Expiry, File, Created) - but skip if already included above -->
                <?php
                  $show_country = !in_array('country_name', $valid_columns);
                  $show_expiry = !in_array('registration_exp_date', $valid_columns);
                  $show_file = !in_array('file_path', $valid_columns);
                  $show_created = !in_array('created_at', $valid_columns);
                ?>

                <?php if ($show_country): ?>
                  <td><?php echo e($r['country_name']); ?></td>
                <?php endif; ?>

                <?php if ($show_expiry): ?>
                  <td>
                    <?php
                      $exp = $r['registration_exp_date'];
                      if ($exp && $exp !== '0000-00-00') {
                        $expd = date('Y-m-d', strtotime($exp));
                        echo e($expd);
                        if ($expd < date('Y-m-d')) {
                          echo ' <span class="badge" style="background:#fee2e2;color:#991b1b">Expired</span>';
                        } else {
                          echo ' <span class="badge" style="background:#dcfce7;color:#166534">Active</span>';
                        }
                      } else {
                        echo '<span class="small">N/A</span>';
                      }
                    ?>
                  </td>
                <?php endif; ?>

                <?php if ($show_file): ?>
                  <td>
                    <?php if (!empty($r['file_path'])): ?>
                      <a class="file-link" href="../<?php echo e($r['file_path']); ?>" target="_blank"><i class="fa fa-file"></i> View</a>
                    <?php else: ?>
                      <span class="small">-</span>
                    <?php endif; ?>
                  </td>
                <?php endif; ?>

              </tr>
            <?php endwhile; ?>
          <?php else: ?>
            <tr><td colspan="<?php echo 1 + count($valid_columns) + 4; ?>" class="small">No records found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>

    <div class="pager">
  <div>
    <?php
      $last_page = max(1, ceil($total / $per_page));
      $prev_page = max(1, $page - 1);
      $next_page = min($last_page, $page + 1);

      $base_get = $_GET;
      unset($base_get['page']);
    ?>

    

    <a class="btn-secondary" href="reports.php?<?php $base_get['page']=$prev_page; echo http_build_query($base_get); ?>">
      ‹ Prev
    </a>

    <span style="color: #000;">Page <b><?php echo $page; ?></b> of <b><?php echo $last_page; ?></b></span>

    <a class="btn-secondary" href="reports.php?<?php $base_get['page']=$next_page; echo http_build_query($base_get); ?>">
      Next ›
    </a>

   
  </div>

  <div class="small">
    Per page: <?php echo $per_page; ?>
  </div>
</div>

</div>
</div>

<script>
function toggleColumns(){
  var box=document.getElementById("columnDropdown");
  box.style.display = box.style.display === "block" ? "none" : "block";
}

document.addEventListener("click",function(e){
  var box=document.getElementById("columnDropdown");
  var btn = e.target.closest("button");
  if(!e.target.closest("#columnDropdown") && !btn){
    if(box) box.style.display="none";
  }
});

function applyColumns(){
  let form = document.querySelector('.filters');

  // REMOVE old columns
  form.querySelectorAll('input[name="columns[]"]').forEach(e=>e.remove());

  // ADD selected columns
  document.querySelectorAll('#columnDropdown input[type="checkbox"]:checked').forEach(cb=>{
    let input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'columns[]';
    input.value = cb.value;
    form.appendChild(input);
  });

  form.submit();
}
</script>

</body>
</html>