<?php require_once 'layout/header.php';
if (!isRole('superadmin')) {
    echo '<div class="card" style="text-align:center;padding:48px">
            <div style="font-size:48px;margin-bottom:16px">⛔</div>
            <h3 style="font-family:\'Quicksand\',sans-serif;font-size:18px;color:#9B1C4C;margin-bottom:8px">Akses Ditolak</h3>
            <p style="color:var(--text2)">Hanya superadmin yang bisa mengakses halaman ini.</p>
          </div>';
    require_once 'layout/footer.php'; exit;
}

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $act = $_POST['action']??'';

    if ($act==='tambah') {
        $hash = password_hash($_POST['password'], PASSWORD_BCRYPT);
        // Handle foto upload
        $foto = null;
        if (!empty($_FILES['foto']['name'])) {
            $ext  = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg','jpeg','png','webp'];
            if (in_array($ext, $allowed)) {
                $namaFile = 'admin_'.time().'_'.rand(100,999).'.'.$ext;
                $uploadDir = 'uploads/foto_admin/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                if (move_uploaded_file($_FILES['foto']['tmp_name'], $uploadDir.$namaFile)) {
                    $foto = $namaFile;
                }
            }
        }
        $pdo->prepare("INSERT INTO admin (username,password,nama_lengkap,email,role,foto) VALUES (?,?,?,?,?,?)")
            ->execute([$_POST['username'],$hash,$_POST['nama_lengkap'],$_POST['email'],$_POST['role'],$foto]);
        $_SESSION['toast'] = '✅ Admin berhasil ditambahkan';

    } elseif ($act==='edit') {
        $id = (int)$_POST['id'];

        // Handle foto upload
        $fotoSql = '';
        $fotoVal = [];
        if (!empty($_FILES['foto']['name'])) {
            $ext  = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg','jpeg','png','webp'];
            if (in_array($ext, $allowed)) {
                $namaFile = 'admin_'.time().'_'.rand(100,999).'.'.$ext;
                $uploadDir = 'uploads/foto_admin/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                if (move_uploaded_file($_FILES['foto']['tmp_name'], $uploadDir.$namaFile)) {
                    $fotoSql = ',foto=?';
                    $fotoVal = [$namaFile];
                }
            }
        }

        if (!empty($_POST['password'])) {
            $hash = password_hash($_POST['password'], PASSWORD_BCRYPT);
            $params = array_merge(
                [$_POST['nama_lengkap'],$_POST['username'],$_POST['email'],$_POST['role'],$hash],
                $fotoVal, [$id]
            );
            $pdo->prepare("UPDATE admin SET nama_lengkap=?,username=?,email=?,role=?,password=?{$fotoSql} WHERE id=?")
                ->execute($params);
        } else {
            $params = array_merge(
                [$_POST['nama_lengkap'],$_POST['username'],$_POST['email'],$_POST['role']],
                $fotoVal, [$id]
            );
            $pdo->prepare("UPDATE admin SET nama_lengkap=?,username=?,email=?,role=?{$fotoSql} WHERE id=?")
                ->execute($params);
        }
        $_SESSION['toast'] = '✅ Data admin berhasil diperbarui';

    } elseif ($act==='hapus' && (int)$_POST['id'] !== $_SESSION['admin_id']) {
        $pdo->prepare("DELETE FROM admin WHERE id=?")->execute([(int)$_POST['id']]);
        $_SESSION['toast'] = '🗑️ Admin berhasil dihapus';
    }

    redirect('index.php?page=admin');
}

$admins     = $pdo->query("SELECT id,username,nama_lengkap,email,role,foto,last_login FROM admin ORDER BY id")->fetchAll();
$toast      = $_SESSION['toast']??''; unset($_SESSION['toast']);
$roleColors = ['superadmin'=>'badge-danger','admin'=>'badge-primary','bendahara'=>'badge-success'];
$roleIcons  = ['superadmin'=>'👑','admin'=>'🛡️','bendahara'=>'💼'];
$avatarGrad = [
    ['#FF6B9D','#FB923C'], ['#A855F7','#6366F1'], ['#38BDF8','#34D399'],
    ['#FBBF24','#FB923C'], ['#F472B6','#A855F7'], ['#34D399','#38BDF8']
];

// Helper: render avatar (foto atau inisial)
function renderAvatar($a, $size=46, $radius=14, $fontSize=20) {
    $uploadDir = 'uploads/foto_admin/';
    if (!empty($a['foto']) && file_exists($uploadDir.$a['foto'])) {
        return "<img src='{$uploadDir}{$a['foto']}' style='width:{$size}px;height:{$size}px;border-radius:{$radius}px;object-fit:cover;flex-shrink:0;box-shadow:0 3px 10px rgba(0,0,0,.15)'>";
    }
    // fallback inisial
    static $grads = [
        ['#FF6B9D','#FB923C'],['#A855F7','#6366F1'],['#38BDF8','#34D399'],
        ['#FBBF24','#FB923C'],['#F472B6','#A855F7'],['#34D399','#38BDF8']
    ];
    $idx = $a['id'] % count($grads);
    $g   = $grads[$idx];
    $ini = mb_strtoupper(mb_substr($a['nama_lengkap'],0,1));
    return "<div style='width:{$size}px;height:{$size}px;border-radius:{$radius}px;background:linear-gradient(135deg,{$g[0]},{$g[1]});display:flex;align-items:center;justify-content:center;font-family:\"Quicksand\",sans-serif;font-weight:700;font-size:{$fontSize}px;color:#fff;flex-shrink:0;box-shadow:0 3px 10px {$g[0]}55'>{$ini}</div>";
}
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title">👑 Kelola Admin</div>
    <div class="page-header-sub"><?= count($admins) ?> admin terdaftar di sistem</div>
  </div>
  <button class="btn btn-primary" onclick="openModal('modalTambahAdmin')">➕ Tambah Admin</button>
</div>

<!-- Admin Cards Grid -->
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:16px;margin-bottom:24px">
  <?php foreach($admins as $i=>$a):
    $g      = $avatarGrad[$i % count($avatarGrad)];
    $isSelf = ($a['id'] == $_SESSION['admin_id']);
  ?>
  <div class="card" style="padding:20px;position:relative;overflow:hidden">
    <div style="position:absolute;top:-20px;right:-20px;width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,<?= $g[0] ?>,<?= $g[1] ?>);opacity:.10;pointer-events:none"></div>

    <div style="display:flex;align-items:flex-start;gap:12px">
      <?= renderAvatar($a, 46, 14, 20) ?>
      <div style="flex:1;min-width:0">
        <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
          <div style="font-family:'Quicksand',sans-serif;font-weight:700;font-size:14.5px"><?= e($a['nama_lengkap']) ?></div>
          <?php if($isSelf): ?>
            <span class="pill pill-green" style="font-size:10px;padding:2px 8px">Kamu</span>
          <?php endif ?>
        </div>
        <div style="font-size:12px;color:var(--text3);font-family:monospace;margin-top:2px">@<?= e($a['username']) ?></div>
        <div style="font-size:12px;color:var(--text2);margin-top:2px">✉️ <?= e($a['email']) ?></div>
      </div>
    </div>

    <div style="display:flex;align-items:center;justify-content:space-between;margin-top:14px;padding-top:12px;border-top:1px solid var(--border);flex-wrap:wrap;gap:8px">
      <span class="badge <?= $roleColors[$a['role']]??'badge-info' ?>">
        <?= $roleIcons[$a['role']]??'👤' ?> <?= ucfirst($a['role']) ?>
      </span>
      <div style="display:flex;align-items:center;gap:6px">
        <span style="font-size:11px;color:var(--text3)">
          <?= $a['last_login'] ? '🕐 '.date('d/m/Y',strtotime($a['last_login'])) : '🚫 Belum login' ?>
        </span>
        <button class="btn btn-outline btn-sm" onclick='bukaEdit(<?= json_encode($a) ?>)'>✏️</button>
        <?php if(!$isSelf): ?>
        <form method="POST" style="display:inline" onsubmit="return confirm('Hapus admin ini?')">
          <input type="hidden" name="action" value="hapus">
          <input type="hidden" name="id" value="<?= $a['id'] ?>">
          <button class="btn btn-danger btn-sm" type="submit">🗑️</button>
        </form>
        <?php endif ?>
      </div>
    </div>
  </div>
  <?php endforeach ?>
</div>

<!-- Full Table -->
<div class="card" style="padding:0;overflow:hidden">
  <div style="padding:16px 20px;border-bottom:1px solid var(--border)">
    <div style="font-family:'Quicksand',sans-serif;font-weight:700;font-size:14px">📋 Daftar Lengkap</div>
  </div>
  <div style="overflow-x:auto">
    <table>
      <thead>
        <tr><th>#</th><th>Admin</th><th>Username</th><th>Email</th><th>Role</th><th>Foto</th><th>Last Login</th><th>Aksi</th></tr>
      </thead>
      <tbody>
      <?php foreach($admins as $i=>$a):
        $isSelf = ($a['id'] == $_SESSION['admin_id']);
        $g      = $avatarGrad[$i % count($avatarGrad)];
      ?>
      <tr>
        <td>
          <div style="width:26px;height:26px;border-radius:8px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--text2)"><?= $i+1 ?></div>
        </td>
        <td>
          <div style="display:flex;align-items:center;gap:9px">
            <?= renderAvatar($a, 34, 10, 14) ?>
            <div>
              <div style="font-weight:600;font-size:13.5px"><?= e($a['nama_lengkap']) ?></div>
              <?php if($isSelf): ?>
                <span class="pill pill-green" style="font-size:10px;padding:1px 7px">Kamu</span>
              <?php endif ?>
            </div>
          </div>
        </td>
        <td>
          <span style="font-family:monospace;font-size:12.5px;background:var(--surface2);padding:3px 8px;border-radius:6px;color:var(--text2)">@<?= e($a['username']) ?></span>
        </td>
        <td style="font-size:12.5px;color:var(--text2)"><?= e($a['email']) ?></td>
        <td>
          <span class="badge <?= $roleColors[$a['role']]??'badge-info' ?>">
            <?= $roleIcons[$a['role']]??'👤' ?> <?= ucfirst($a['role']) ?>
          </span>
        </td>
        <td>
          <?php if(!empty($a['foto']) && file_exists('uploads/foto_admin/'.$a['foto'])): ?>
            <img src="uploads/foto_admin/<?= e($a['foto']) ?>"
                 style="width:32px;height:32px;border-radius:8px;object-fit:cover;border:2px solid var(--border)">
          <?php else: ?>
            <span style="font-size:12px;color:var(--text3)">–</span>
          <?php endif ?>
        </td>
        <td style="font-size:12px;color:var(--text2)">
          <?= $a['last_login'] ? date('d/m/Y H:i',strtotime($a['last_login'])) : '–' ?>
        </td>
        <td>
          <div style="display:flex;gap:6px;align-items:center">
            <button class="btn btn-outline btn-sm" onclick='bukaEdit(<?= json_encode($a) ?>)'>✏️ Edit</button>
            <?php if(!$isSelf): ?>
            <form method="POST" style="display:inline" onsubmit="return confirm('Hapus admin ini?')">
              <input type="hidden" name="action" value="hapus">
              <input type="hidden" name="id" value="<?= $a['id'] ?>">
              <button class="btn btn-danger btn-sm" type="submit">🗑️ Hapus</button>
            </form>
            <?php else: ?>
              <span style="font-size:12px;color:var(--text3)">–</span>
            <?php endif ?>
          </div>
        </td>
      </tr>
      <?php endforeach ?>
      </tbody>
    </table>
  </div>
</div>

<!-- ═══ Modal Tambah Admin ═══ -->
<div class="modal-overlay" id="modalTambahAdmin">
  <div class="modal">
    <div class="modal-header">
      <h3>➕ Tambah Admin Baru</h3>
      <button class="modal-close" onclick="closeModal('modalTambahAdmin')">×</button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="tambah">
      <div class="modal-body">
        <div class="form-group">
          <label>Nama Lengkap</label>
          <input name="nama_lengkap" required placeholder="Nama lengkap admin">
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Username</label>
            <input name="username" required placeholder="username">
          </div>
          <div class="form-group">
            <label>Password</label>
            <input name="password" type="password" required placeholder="••••••••">
          </div>
        </div>
        <div class="form-group">
          <label>Email</label>
          <input name="email" type="email" required placeholder="email@sekolah.sch.id">
        </div>
        <div class="form-group">
          <label>Role</label>
          <select name="role">
            <option value="admin">🛡️ Admin</option>
            <option value="bendahara">💼 Bendahara</option>
            <option value="superadmin">👑 Superadmin</option>
          </select>
        </div>
        <div class="form-group">
          <label>Foto Profil (opsional)</label>
          <div class="foto-upload-wrap" onclick="document.getElementById('fotoTambah').click()">
            <div class="foto-upload-preview" id="previewTambah">
              <span style="font-size:32px">🖼️</span>
              <div style="font-size:13px;color:var(--text2);margin-top:6px">Klik untuk upload foto</div>
              <div style="font-size:11px;color:var(--text3);margin-top:2px">JPG, PNG, WEBP — maks 2MB</div>
            </div>
            <input type="file" name="foto" id="fotoTambah" accept="image/*" style="display:none"
                   onchange="previewFoto(this,'previewTambah')">
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalTambahAdmin')">Batal</button>
        <button type="submit" class="btn btn-primary">💾 Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- ═══ Modal Edit Admin ═══ -->
<div class="modal-overlay" id="modalEditAdmin">
  <div class="modal">
    <div class="modal-header">
      <h3>✏️ Edit Data Admin</h3>
      <button class="modal-close" onclick="closeModal('modalEditAdmin')">×</button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="editAdminId">
      <div class="modal-body">

        <!-- Preview badge -->
        <div style="background:var(--surface2);border-radius:12px;padding:12px 16px;margin-bottom:18px;display:flex;align-items:center;gap:10px">
          <div id="editAdminAvatar" style="width:40px;height:40px;border-radius:12px;background:linear-gradient(135deg,#A855F7,#6366F1);display:flex;align-items:center;justify-content:center;font-family:'Quicksand',sans-serif;font-weight:700;font-size:17px;color:#fff;flex-shrink:0;overflow:hidden"></div>
          <div>
            <div id="editAdminName" style="font-family:'Quicksand',sans-serif;font-weight:700;font-size:14px;color:var(--text)"></div>
            <div id="editAdminUser" style="font-size:12px;color:var(--text3);font-family:monospace"></div>
          </div>
        </div>

        <div class="form-group">
          <label>Nama Lengkap</label>
          <input name="nama_lengkap" id="editNamaLengkap" required placeholder="Nama lengkap admin"
                 oninput="document.getElementById('editAdminName').textContent=this.value">
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Username</label>
            <input name="username" id="editUsername" required placeholder="username"
                   oninput="document.getElementById('editAdminUser').textContent='@'+this.value">
          </div>
          <div class="form-group">
            <label>Email</label>
            <input name="email" id="editEmail" type="email" required placeholder="email@sekolah.sch.id">
          </div>
        </div>
        <div class="form-group">
          <label>Role</label>
          <select name="role" id="editRole">
            <option value="admin">🛡️ Admin</option>
            <option value="bendahara">💼 Bendahara</option>
            <option value="superadmin">👑 Superadmin</option>
          </select>
        </div>
        <div class="form-group">
          <label>Password Baru</label>
          <div style="position:relative">
            <input name="password" id="editPassword" type="password" placeholder="Kosongkan jika tidak ingin mengubah">
            <button type="button" onclick="togglePass()" style="position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;font-size:16px" id="togglePassBtn">👁️</button>
          </div>
          <div style="font-size:11.5px;color:var(--text3);margin-top:5px">ℹ️ Biarkan kosong jika tidak ingin mengubah password</div>
        </div>
        <div class="form-group">
          <label>Ganti Foto Profil (opsional)</label>
          <div class="foto-upload-wrap" onclick="document.getElementById('fotoEdit').click()">
            <div class="foto-upload-preview" id="previewEdit">
              <span style="font-size:28px">📷</span>
              <div style="font-size:13px;color:var(--text2);margin-top:6px">Klik untuk ganti foto</div>
              <div style="font-size:11px;color:var(--text3);margin-top:2px">Biarkan kosong jika tidak ingin mengubah</div>
            </div>
            <input type="file" name="foto" id="fotoEdit" accept="image/*" style="display:none"
                   onchange="previewFoto(this,'previewEdit')">
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalEditAdmin')">Batal</button>
        <button type="submit" class="btn btn-primary">💾 Simpan Perubahan</button>
      </div>
    </form>
  </div>
</div>

<style>
.foto-upload-wrap {
  border: 2px dashed var(--border);
  border-radius: var(--radius-sm);
  cursor: pointer;
  transition: border-color .2s, background .2s;
  overflow: hidden;
}
.foto-upload-wrap:hover {
  border-color: var(--candy-purple);
  background: var(--surface2);
}
.foto-upload-preview {
  padding: 20px;
  text-align: center;
  min-height: 90px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.foto-upload-preview img {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  object-fit: cover;
  margin-bottom: 6px;
}
</style>

<script>
function bukaEdit(a) {
  document.getElementById('editAdminId').value     = a.id;
  document.getElementById('editNamaLengkap').value = a.nama_lengkap;
  document.getElementById('editUsername').value    = a.username;
  document.getElementById('editEmail').value       = a.email;
  document.getElementById('editRole').value        = a.role;
  document.getElementById('editPassword').value    = '';

  // Update preview badge
  document.getElementById('editAdminName').textContent = a.nama_lengkap;
  document.getElementById('editAdminUser').textContent = '@' + a.username;

  // Avatar: foto atau inisial
  const av = document.getElementById('editAdminAvatar');
  if (a.foto) {
    av.innerHTML = '<img src="uploads/foto_admin/'+a.foto+'" style="width:100%;height:100%;object-fit:cover">';
  } else {
    av.innerHTML = a.nama_lengkap.charAt(0).toUpperCase();
    av.style.fontSize = '17px';
  }

  // Reset foto preview
  const prev = document.getElementById('previewEdit');
  prev.innerHTML = '<span style="font-size:28px">📷</span><div style="font-size:13px;color:var(--text2);margin-top:6px">Klik untuk ganti foto</div><div style="font-size:11px;color:var(--text3);margin-top:2px">Biarkan kosong jika tidak ingin mengubah</div>';

  openModal('modalEditAdmin');
}

function togglePass() {
  const inp = document.getElementById('editPassword');
  const btn = document.getElementById('togglePassBtn');
  inp.type = inp.type === 'password' ? 'text' : 'password';
  btn.textContent = inp.type === 'password' ? '👁️' : '🙈';
}

function previewFoto(input, previewId) {
  const prev = document.getElementById(previewId);
  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = e => {
      prev.innerHTML = '<img src="'+e.target.result+'" style="width:80px;height:80px;border-radius:12px;object-fit:cover;margin-bottom:6px"><div style="font-size:12px;color:var(--text2)">'+input.files[0].name+'</div>';
    };
    reader.readAsDataURL(input.files[0]);
  }
}
</script>

<?php require_once 'layout/footer.php'; ?>