<?php
// classroom.php (refactored, admin-only)
// Keeps your styling intact, adds Create Classroom form, fixes JS issues, and optimizes queries.

include 'includes/conn.php';
include 'includes/functions.php';

// Only admin may access this page (you asked: admin => all permissions; rest none)
requireRole('admin');

function is_ajax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
function json_response($data) {
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

$message = '';
$message_type = 'info';

// ---------- Handle AJAX POST actions ----------
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['action']) || is_ajax())) {
        $action = $_POST['action'] ?? null;

        // All actions are admin-only (we already required admin)
        // Create classroom
        if ($action === 'create_classroom') {
            $name = trim($_POST['name'] ?? '');
            $class_level = trim($_POST['class_level'] ?? '');
            $description = trim($_POST['description'] ?? '');
            if ($name === '' || $class_level === '') json_response(['status'=>'error','message'=>'Name and level required']);
            $stmt = $pdo->prepare("INSERT INTO classrooms (name, class_level, description) VALUES (?, ?, ?)");
            $stmt->execute([$name, $class_level, $description]);
            json_response(['status'=>'success','message'=>'Classroom created']);
        }

        // Delete classroom (fails if students exist)
        if ($action === 'delete_classroom') {
            $cid = (int)($_POST['classroom_id'] ?? 0);
            if (!$cid) json_response(['status'=>'error','message'=>'Missing classroom id']);
            $ct = $pdo->prepare("SELECT COUNT(*) FROM classroom_students WHERE classroom_id = ?");
            $ct->execute([$cid]);
            if ($ct->fetchColumn() > 0) json_response(['status'=>'error','message'=>'Remove students before deleting']);
            $d = $pdo->prepare("DELETE FROM classrooms WHERE id = ?");
            $d->execute([$cid]);
            json_response(['status'=>'success','message'=>'Classroom deleted']);
        }

        // Assign teachers (replace existing)
        if ($action === 'assign_teachers') {
            $cid = (int)($_POST['classroom_id'] ?? 0);
            $teacher_ids = $_POST['teacher_ids'] ?? [];
            if (!$cid) json_response(['status'=>'error','message'=>'Missing classroom id']);
            if (!is_array($teacher_ids)) $teacher_ids = [];
            $pdo->beginTransaction();
            $del = $pdo->prepare("DELETE FROM classroom_teachers WHERE classroom_id = ?");
            $del->execute([$cid]);
            // Use standard insert (INSERT IGNORE is MySQL-only — keep compatibility)
            $ins = $pdo->prepare("INSERT INTO classroom_teachers (classroom_id, teacher_id) VALUES (?, ?)");
            foreach ($teacher_ids as $tid) {
                $tid = (int)$tid;
                if ($tid > 0) {
                    // Avoid duplicates by checking quickly
                    $check = $pdo->prepare("SELECT 1 FROM classroom_teachers WHERE classroom_id = ? AND teacher_id = ? LIMIT 1");
                    $check->execute([$cid, $tid]);
                    if (!$check->fetchColumn()) $ins->execute([$cid, $tid]);
                }
            }
            $pdo->commit();
            json_response(['status'=>'success','message'=>'Teachers assigned']);
        }

        // Assign single student to a classroom (ensures student not already assigned)
        if ($action === 'assign_student') {
            $cid = (int)($_POST['classroom_id'] ?? 0);
            $sid = (int)($_POST['student_id'] ?? 0);
            if (!$cid || !$sid) json_response(['status'=>'error','message'=>'Missing parameters']);
            // check if student already assigned anywhere
            $chk = $pdo->prepare("SELECT classroom_id FROM classroom_students WHERE student_id = ?");
            $chk->execute([$sid]);
            if ($chk->fetch()) json_response(['status'=>'error','message'=>'Student already assigned to a classroom']);
            $ins = $pdo->prepare("INSERT INTO classroom_students (classroom_id, student_id) VALUES (?, ?)");
            $ins->execute([$cid, $sid]);
            // update user's current_class and class_level
            $cn = $pdo->prepare("SELECT name, class_level FROM classrooms WHERE id = ?");
            $cn->execute([$cid]);
            $cinfo = $cn->fetch(PDO::FETCH_ASSOC);
            if ($cinfo) {
                $u = $pdo->prepare("UPDATE users SET current_class = ?, class_level = ? WHERE id = ?");
                $u->execute([$cinfo['name'], $cinfo['class_level'], $sid]);
            }
            json_response(['status'=>'success','message'=>'Student assigned to classroom']);
        }

        // Remove student from classroom
        if ($action === 'remove_student') {
            $cid = (int)($_POST['classroom_id'] ?? 0);
            $sid = (int)($_POST['student_id'] ?? 0);
            if (!$cid || !$sid) json_response(['status'=>'error','message'=>'Missing parameters']);
            $del = $pdo->prepare("DELETE FROM classroom_students WHERE classroom_id = ? AND student_id = ?");
            $del->execute([$cid, $sid]);
            $u = $pdo->prepare("UPDATE users SET current_class = NULL, class_level = NULL WHERE id = ?");
            $u->execute([$sid]);
            json_response(['status'=>'success','message'=>'Student removed']);
        }

        // Remove single teacher mapping
        if ($action === 'remove_teacher') {
            $cid = (int)($_POST['classroom_id'] ?? 0);
            $tid = (int)($_POST['teacher_id'] ?? 0);
            if (!$cid || !$tid) json_response(['status'=>'error','message'=>'Missing parameters']);
            $del = $pdo->prepare("DELETE FROM classroom_teachers WHERE classroom_id = ? AND teacher_id = ?");
            $del->execute([$cid, $tid]);
            json_response(['status'=>'success','message'=>'Teacher removed']);
        }

        // Promote class
        if ($action === 'promote_class') {
            $cid = (int)($_POST['classroom_id'] ?? 0);
            if (!$cid) json_response(['status'=>'error','message'=>'Missing classroom id']);
            $s = $pdo->prepare("SELECT * FROM classrooms WHERE id = ?");
            $s->execute([$cid]);
            $cur = $s->fetch(PDO::FETCH_ASSOC);
            if (!$cur) json_response(['status'=>'error','message'=>'Classroom not found']);
            $order = ['JSS1'=>'JSS2','JSS2'=>'JSS3','JSS3'=>'SSS1','SSS1'=>'SSS2','SSS2'=>'SSS3','SSS3'=>'Alumni'];
            $lvl = $cur['class_level'];
            if (!isset($order[$lvl])) json_response(['status'=>'error','message'=>'No promotion available for this level']);
            $next_lvl = $order[$lvl];
            $next_name = str_replace($lvl, $next_lvl, $cur['name']);
            $t = $pdo->prepare("SELECT * FROM classrooms WHERE name = ? LIMIT 1");
            $t->execute([$next_name]);
            $next = $t->fetch(PDO::FETCH_ASSOC);
            if (!$next) json_response(['status'=>'error','message'=>'Destination class does not exist']);
            $students_stmt = $pdo->prepare("SELECT student_id FROM classroom_students WHERE classroom_id = ?");
            $students_stmt->execute([$cid]);
            $students = $students_stmt->fetchAll(PDO::FETCH_COLUMN);
            if (count($students) === 0) json_response(['status'=>'error','message'=>'No students to promote']);
            $pdo->beginTransaction();
            $updateUser = $pdo->prepare("UPDATE users SET current_class = ?, class_level = ? WHERE id = ?");
            $delOld = $pdo->prepare("DELETE FROM classroom_students WHERE classroom_id = ? AND student_id = ?");
            $insNew = $pdo->prepare("INSERT INTO classroom_students (classroom_id, student_id) VALUES (?, ?)");
            foreach ($students as $sid) {
                $updateUser->execute([$next['name'], $next_lvl, $sid]);
                $delOld->execute([$cid, $sid]);
                $insNew->execute([$next['id'], $sid]);
            }
            $pdo->commit();
            json_response(['status'=>'success','message'=>"Promoted to {$next['name']}"]);
        }

        json_response(['status'=>'error','message'=>'Unknown action']);
    }

    // CSV export
    if (isset($_GET['export_classroom_id'])) {
        $cid = (int) $_GET['export_classroom_id'];
        $q = $pdo->prepare("
            SELECT u.id, u.first_name, u.last_name, u.username, u.email, u.current_class, u.class_level
            FROM classroom_students cs
            JOIN users u ON cs.student_id = u.id
            WHERE cs.classroom_id = ?
        ");
        $q->execute([$cid]);
        $rows = $q->fetchAll(PDO::FETCH_ASSOC);
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="class_'.$cid.'_students.csv"');
        $out = fopen('php://output','w');
        // header row
        fputcsv($out, ['id','first_name','last_name','username','email','current_class','class_level']);
        foreach ($rows as $r) fputcsv($out, $r);
        fclose($out);
        exit;
    }

    // ---------- Page data (optimized queries) ----------
    // Fetch all classrooms
    $stmt = $pdo->prepare("SELECT * FROM classrooms ORDER BY name ASC");
    $stmt->execute();
    $classrooms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch all students (basic info)
    $students = $pdo->prepare("SELECT id, first_name, last_name FROM users WHERE role='student' ORDER BY first_name, last_name");
    $students->execute();
    $students = $students->fetchAll(PDO::FETCH_ASSOC);

    // Students assigned (ids) used to hide already assigned in dropdown
    $assigned_stmt = $pdo->query("SELECT student_id FROM classroom_students");
    $assigned_students = $assigned_stmt->fetchAll(PDO::FETCH_COLUMN);

    // Fetch all teachers (basic)
    $teachers_stmt = $pdo->prepare("SELECT id, first_name, last_name FROM users WHERE role='teacher' ORDER BY first_name, last_name");
    $teachers_stmt->execute();
    $teachers = $teachers_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch student counts per classroom
    $student_counts_stmt = $pdo->query("SELECT classroom_id, COUNT(*) AS count FROM classroom_students GROUP BY classroom_id");
    $student_counts = $student_counts_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    // Fetch classroom -> teachers mapping in one go
    $class_teachers = [];
    $ct_all = $pdo->query("
        SELECT ct.classroom_id, u.id AS teacher_id, u.first_name, u.last_name
        FROM classroom_teachers ct
        JOIN users u ON ct.teacher_id = u.id
        ORDER BY u.first_name, u.last_name
    ")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($ct_all as $r) {
        $class_teachers[$r['classroom_id']][] = ['id'=>$r['teacher_id'],'first_name'=>$r['first_name'],'last_name'=>$r['last_name']];
    }

    // Quick map of assigned student ids (again) for the forms
    $assigned_stmt2 = $pdo->query("SELECT student_id FROM classroom_students");
    $assigned_students = $assigned_stmt2->fetchAll(PDO::FETCH_COLUMN);

    // If viewing students in a classroom
    $view_classroom_students = [];
    $view_cid = 0;
    if (isset($_GET['view_students']) && isset($_GET['classroom_id'])) {
        $view_cid = (int)$_GET['classroom_id'];
        // get classroom students with user info
        $vcstmt = $pdo->prepare("
            SELECT u.id, u.first_name, u.last_name, u.username, u.email
            FROM classroom_students cs
            JOIN users u ON cs.student_id = u.id
            WHERE cs.classroom_id = ?
            ORDER BY u.first_name, u.last_name
        ");
        $vcstmt->execute([$view_cid]);
        $view_classroom_students = $vcstmt->fetchAll(PDO::FETCH_ASSOC);
    }

} catch (PDOException $e) {
    $message = 'DB error: '.$e->getMessage();
    $message_type = 'danger';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" type="image/png" sizes="32x32" href="BCA-Logo.png">
<link rel="icon" type="image/png" sizes="16x16" href="BCA-Logo.png">
<title>Manage Classrooms</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<style>
:root{--bg:#fff;--text:#111;--card:#f8f9fa}
[data-theme='dark']{--bg:#0f1720;--text:#e6eef8;--card:#0b1220}
body{background:var(--bg);color:var(--text)}.card{background:var(--card)}
</style>
</head>

<body>
<nav class="navbar navbar-expand-lg" style="background-color:#198754">
  <div class="container-fluid">
    <a class="navbar-brand text-white" href="admin.php"><i class="fas fa-chalkboard-teacher"></i> Portal</a>
    <div class="d-flex align-items-center">
      <button id="themeToggle" class="btn btn-sm btn-light me-2">Toggle Dark</button>
      <span class="text-white me-3">Welcome, <?php echo htmlspecialchars($_SESSION['first_name'] ?? ''); ?></span>
      <a class="text-white me-3" href="admin.php">Dashboard</a>
    </div>
  </div>
</nav>

<div class="container mt-4">
<?php if (!empty($message)): ?><div class="alert alert-<?php echo htmlspecialchars($message_type); ?> alert-dismissible fade show"><?php echo $message; ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

<?php if (!empty($view_classroom_students) && $view_cid): ?>
  <?php $cindex=array_search($view_cid,array_column($classrooms,'id')); $cname = $cindex!==false?$classrooms[$cindex]['name']:'Unknown'; ?>
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h4><i class="fas fa-users"></i> Students in <?php echo htmlspecialchars($cname); ?></h4>
      <div>
        <a class="btn btn-secondary btn-sm" href="classroom.php">Back</a>
        <a class="btn btn-outline-primary btn-sm" href="?export_classroom_id=<?php echo $view_cid; ?>">Export CSV</a>
      </div>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-striped"><thead><tr><th>ID</th><th>Name</th><th>Username</th><th>Email</th><th>Actions</th></tr></thead>
        <tbody>
        <?php foreach($view_classroom_students as $s): ?>
          <tr id="student-row-<?php echo $s['id'];?>"><td><?php echo $s['id'];?></td><td><?php echo htmlspecialchars($s['first_name'].' '.$s['last_name']);?></td><td><?php echo htmlspecialchars($s['username']);?></td><td><?php echo htmlspecialchars($s['email']);?></td>
            <td><button class="btn btn-sm btn-outline-danger remove-student-btn" data-cid="<?php echo $view_cid;?>" data-sid="<?php echo $s['id'];?>">Remove</button></td></tr>
        <?php endforeach; ?>
        </tbody></table>
      </div>
      <div class="mt-3"><button id="promoteClassBtn" class="btn btn-success" data-cid="<?php echo $view_cid;?>">Promote All Students</button></div>
    </div>
  </div>

<?php else: ?>

  <div class="row">
    <div class="col-md-8">
      <!-- Create Classroom (admin only) -->
      <div class="card mb-3">
        <div class="card-header"><h5><i class="fas fa-plus-circle"></i> Create New Classroom</h5></div>
        <div class="card-body">
          <form id="createClassForm">
            <div class="mb-3">
              <label class="form-label">Classroom Name</label>
              <input type="text" class="form-control" name="name" required>
            </div>
            <div class="mb-3">
              <label class="form-label">Class Level</label>
              <input type="text" class="form-control" name="class_level" required>
            </div>
            <div class="mb-3">
              <label class="form-label">Description</label>
              <textarea class="form-control" name="description" rows="3"></textarea>
            </div>
            <div id="createMsg" class="mb-2"></div>
            <button class="btn btn-primary">Create Classroom</button>
          </form>
        </div>
      </div>

      <!-- Classrooms table -->
      <div class="card mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h5><i class="fas fa-chalkboard"></i> My Classrooms</h5>
          <div>
            <button id="exportAllBtn" class="btn btn-outline-light btn-sm">Export All</button>
          </div>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Level</th>
                  <th>Teachers</th>
                  <th>Students</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach($classrooms as $c): ?>
                  <tr>
                    <td><?php echo htmlspecialchars($c['name']);?></td>
                    <td><?php echo htmlspecialchars($c['class_level']);?></td>
                    <td>
                      <?php
                        $tlist = $class_teachers[$c['id']] ?? [];
                        if (count($tlist) === 0) echo '<em>—</em>';
                        else {
                            $names = array_map(function($t){ return htmlspecialchars($t['first_name'].' '.$t['last_name']); }, $tlist);
                            echo implode(', ', $names);
                        }
                      ?>
                    </td>
                    <td><span class="badge bg-primary"><?php echo intval($student_counts[$c['id']] ?? 0);?></span></td>
                    <td class="d-flex gap-1">
                      <a class="btn btn-sm btn-outline-info" href="?view_students=1&classroom_id=<?php echo $c['id'];?>">View</a>
                      <button class="btn btn-sm btn-outline-warning assign-students-btn" data-cid="<?php echo $c['id'];?>">Assign Students</button>
                      <button class="btn btn-sm btn-outline-danger delete-classroom-btn" data-cid="<?php echo $c['id'];?>">Delete</button>
                      <a class="btn btn-sm btn-outline-primary" href="?export_classroom_id=<?php echo $c['id'];?>">Export</a>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>

    <div class="col-md-4">

      <!-- Quick assign student -->
      <div class="card mb-3">
        <div class="card-header"><h5><i class="fas fa-user-plus"></i> Quick Assign Student</h5></div>
        <div class="card-body">
          <form id="assignStudentForm">
            <div class="mb-3">
              <label>Classroom</label>
              <select name="classroom_id" class="form-select" required>
                <option value="">Choose...</option>
                <?php foreach($classrooms as $c): ?>
                  <option value="<?php echo $c['id'];?>"><?php echo htmlspecialchars($c['name']);?></option>
                <?php endforeach;?>
              </select>
            </div>
            <div class="mb-3">
              <label>Student (only unassigned shown)</label>
              <select name="student_id" class="form-select" required>
                <option value="">Choose...</option>
                <?php foreach($students as $s): ?>
                  <?php if (!in_array($s['id'],$assigned_students)): ?>
                    <option value="<?php echo $s['id'];?>"><?php echo htmlspecialchars($s['first_name'].' '.$s['last_name']);?></option>
                  <?php endif; ?>
                <?php endforeach; ?>
              </select>
            </div>
            <div id="assignStudentMsg" class="mb-2"></div>
            <button class="btn btn-success">Assign Student</button>
          </form>
        </div>
      </div>

      <div class="card">
        <div class="card-header"><h5>Info</h5></div>
        <div class="card-body"><p>Admins: create classrooms, assign teachers and students, promote and export lists. Teachers may view classrooms they belong to. Students see their assigned class on their profile.</p></div>
      </div>

    </div>
  </div>
<?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Dark mode toggle (keeps your dark.js pattern but self-contained fallback)
(function(){
  const btn = document.getElementById('themeToggle');
  const saved = localStorage.getItem('theme');
  if (saved === 'dark') document.documentElement.setAttribute('data-theme','dark');
  btn?.addEventListener('click', ()=>{
    const now = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
    if (now === 'dark') document.documentElement.setAttribute('data-theme','dark');
    else document.documentElement.removeAttribute('data-theme');
    localStorage.setItem('theme', now);
  });
})();

// Helper to POST to this same file
async function postAjax(formData){
  formData.append('ajax','1');
  const res = await fetch('classroom.php', {
    method: 'POST',
    body: formData,
    headers: { 'X-Requested-With': 'XMLHttpRequest' }
  });
  return res.json();
}

// Create classroom
document.getElementById('createClassForm')?.addEventListener('submit', async function(e){
  e.preventDefault();
  const fd = new FormData(this);
  fd.append('action','create_classroom');
  const res = await postAjax(fd);
  document.getElementById('createMsg').innerHTML = `<div class="alert alert-${res.status==='success'?'success':'danger'}">${res.message}</div>`;
  if (res.status==='success') setTimeout(()=>location.reload(),800);
});

// Assign student form
document.getElementById('assignStudentForm')?.addEventListener('submit', async function(e){
  e.preventDefault();
  const fd = new FormData(this);
  fd.append('action','assign_student');
  const res = await postAjax(fd);
  document.getElementById('assignStudentMsg').innerHTML = `<div class="alert alert-${res.status==='success'?'success':'danger'}">${res.message}</div>`;
  if (res.status==='success') setTimeout(()=>location.reload(),700);
});

// Assign teachers
document.getElementById('assignTeachersForm')?.addEventListener('submit', async function(e){
  e.preventDefault();
  const fd = new FormData(this);
  fd.append('action','assign_teachers');
  const res = await postAjax(fd);
  document.getElementById('assignTeachersMsg').innerHTML = `<div class="alert alert-${res.status==='success'?'success':'danger'}">${res.message}</div>`;
  if (res.status==='success') setTimeout(()=>location.reload(),700);
});

// Fill quick assign forms when buttons clicked
document.querySelectorAll('.assign-teachers-btn').forEach(btn=>{
  btn.addEventListener('click', function(){
    const cid = this.dataset.cid;
    const sel = document.querySelector('#assignTeachersForm [name=classroom_id]');
    if (sel) { sel.value = cid; sel.scrollIntoView({behavior:'smooth', block:'center'}); sel.focus(); }
  });
});
document.querySelectorAll('.assign-students-btn').forEach(btn=>{
  btn.addEventListener('click', function(){
    const cid = this.dataset.cid;
    const sel = document.querySelector('#assignStudentForm [name=classroom_id]');
    if (sel) { sel.value = cid; sel.scrollIntoView({behavior:'smooth', block:'center'}); sel.focus(); }
  });
});

// Delete classroom
document.querySelectorAll('.delete-classroom-btn').forEach(btn=>{
  btn.addEventListener('click', async function(){
    if (!confirm('Delete classroom? This will fail if students are assigned.')) return;
    const fd = new FormData();
    fd.append('action','delete_classroom');
    fd.append('classroom_id', this.dataset.cid);
    const res = await postAjax(fd);
    alert(res.message);
    if (res.status==='success') location.reload();
  });
});

// Remove student from view_students
document.querySelectorAll('.remove-student-btn').forEach(btn=>{
  btn.addEventListener('click', async function(){
    const sid = this.dataset.sid;
    const cid = this.dataset.cid;
    if (!confirm('Remove student from this classroom?')) return;
    const fd = new FormData();
    fd.append('action','remove_student');
    fd.append('classroom_id', cid);
    fd.append('student_id', sid);
    const res = await postAjax(fd);
    alert(res.message);
    if (res.status==='success') {
      document.getElementById('student-row-'+sid)?.remove();
    }
  });
});

// Promote class (in view_students)
document.getElementById('promoteClassBtn')?.addEventListener('click', async function(){
  const cid = this.dataset.cid || '';
  if (!cid) return alert('No classroom selected');
  if (!confirm('Promote all students in this class?')) return;
  const fd = new FormData();
  fd.append('action','promote_class');
  fd.append('classroom_id', cid);
  const res = await postAjax(fd);
  alert(res.message);
  if (res.status==='success') location.href = 'classroom.php';
});

// Export all (open each CSV in new tab)
document.getElementById('exportAllBtn')?.addEventListener('click', function(){
  if (!confirm('Export each classroom as CSV in new tabs?')) return;
  <?php foreach($classrooms as $c): ?>
    window.open('?export_classroom_id=<?php echo intval($c['id']);?>','_blank');
  <?php endforeach; ?>
});

</script>
</body>
</html>
