<?php
require_once '../includes/config.php';
requireAdmin();

$success = '';
$error   = '';

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

    if ($action === 'add') {
        $title       = sanitize($_POST['title'] ?? '');
        $url         = sanitize($_POST['url'] ?? '');
        $type        = sanitize($_POST['type'] ?? 'link');
        $subject_tag = sanitize($_POST['subject_tag'] ?? '');
        $notes       = sanitize($_POST['notes'] ?? '');

        if (!$title || !$url) {
            $error = 'Title and URL are required.';
        } elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
            $error = 'Please enter a valid URL (must start with https://).';
        } else {
            $pdo->prepare("INSERT INTO admin_resources (title,url,type,subject_tag,notes,is_active) VALUES (?,?,?,?,?,1)")
                ->execute([$title,$url,$type,$subject_tag,$notes]);
            $success = 'Resource added!';
        }
    }

    if ($action === 'toggle') {
        $pdo->prepare("UPDATE admin_resources SET is_active = NOT is_active WHERE id=?")
            ->execute([(int)$_POST['id']]);
        $success = 'Visibility updated!';
    }

    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM admin_resources WHERE id=?")->execute([(int)$_POST['id']]);
        $success = 'Deleted!';
    }

    if ($action === 'edit') {
        $id          = (int)($_POST['id'] ?? 0);
        $title       = sanitize($_POST['title'] ?? '');
        $url         = sanitize($_POST['url'] ?? '');
        $type        = sanitize($_POST['type'] ?? 'link');
        $subject_tag = sanitize($_POST['subject_tag'] ?? '');
        $notes       = sanitize($_POST['notes'] ?? '');
        if ($title && $url) {
            $pdo->prepare("UPDATE admin_resources SET title=?,url=?,type=?,subject_tag=?,notes=? WHERE id=?")
                ->execute([$title,$url,$type,$subject_tag,$notes,$id]);
            $success = 'Resource updated!';
        }
    }
}

// ── DATA ─────────────────────────────────────────────────────────
$typeFilter = $_GET['type'] ?? '';
$where      = $typeFilter ? "WHERE type='" . htmlspecialchars($typeFilter, ENT_QUOTES) . "'" : '';
$resources  = $pdo->query("SELECT * FROM admin_resources $where ORDER BY created_at DESC")->fetchAll();

$stats = [
    'total'  => (int)$pdo->query("SELECT COUNT(*) FROM admin_resources")->fetchColumn(),
    'active' => (int)$pdo->query("SELECT COUNT(*) FROM admin_resources WHERE is_active=1")->fetchColumn(),
];
$typeStats = $pdo->query("SELECT type, COUNT(*) as cnt FROM admin_resources GROUP BY type ORDER BY cnt DESC")->fetchAll();

$typeMap = [
    'youtube'  => ['▶️', '#ef4444', 'YouTube Video'],
    'telegram' => ['📱', '#2AABEE', 'Telegram'],
    'pdf'      => ['📄', '#f59e0b', 'PDF / Doc'],
    'website'  => ['🌐', '#38bdf8', 'Website'],
    'notes'    => ['📝', '#6366f1', 'Notes'],
    'book'     => ['📚', '#22c55e', 'Book'],
    'link'     => ['🔗', '#a855f7', 'Other Link'],
];

require_once 'includes/header.php';
renderAdminHeader('Study Resources', 'resources');
?>

<style>
.res-form-card { background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:24px; }
.type-pill {
  display:inline-flex;align-items:center;gap:5px;
  padding:5px 14px;border-radius:20px;font-size:12px;font-weight:600;
  text-decoration:none;border:1px solid var(--border);
  background:var(--bg-secondary);color:var(--text-muted);cursor:pointer;transition:all 0.15s;
}
.type-pill:hover,.type-pill.on{border-color:var(--accent);background:rgba(99,102,241,0.1);color:var(--accent);}
.res-row {
  background:var(--bg-secondary);border:1px solid var(--border);border-radius:12px;
  padding:14px 16px;display:flex;gap:14px;align-items:flex-start;
  transition:transform 0.15s;
}
.res-row:hover{transform:translateY(-1px);}
.url-hint{font-size:11px;margin-top:5px;padding:6px 10px;border-radius:8px;display:none;}
</style>

<?php if ($success): ?><div class="alert alert-success">✅ <?= $success ?></div><?php endif; ?>
<?php if ($error):   ?><div class="alert alert-error">❌ <?= $error ?></div><?php endif; ?>

<!-- Stats -->
<div class="stats-grid" style="margin-bottom:22px">
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(99,102,241,0.15)">🗂️</div>
    <div class="stat-value"><?= $stats['total'] ?></div>
    <div class="stat-label">Total Resources</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(16,185,129,0.15)">👁️</div>
    <div class="stat-value"><?= $stats['active'] ?></div>
    <div class="stat-label">Visible to Students</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(239,68,68,0.15)">🔒</div>
    <div class="stat-value"><?= $stats['total'] - $stats['active'] ?></div>
    <div class="stat-label">Hidden</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(245,158,11,0.15)">📂</div>
    <div class="stat-value"><?= count($typeStats) ?></div>
    <div class="stat-label">Categories Used</div>
  </div>
</div>

<div class="grid-2" style="align-items:start;gap:20px">

<!-- ── ADD FORM ── -->
<div>
  <div class="res-form-card">
    <div class="card-header" style="padding:0 0 16px"><div class="card-title">➕ Add New Resource</div></div>

    <form method="POST" id="addForm">
      <input type="hidden" name="action" value="add">

      <div class="form-group">
        <label class="form-label">Title *</label>
        <input type="text" name="title" class="form-control"
               placeholder="e.g. Physics – Electrostatics Full Lecture" required>
      </div>

      <div class="form-group">
        <label class="form-label">URL *</label>
        <input type="url" name="url" id="addUrl" class="form-control"
               placeholder="https://..." required oninput="detectUrlType(this,'addType','addHint')">
        <div id="addHint" class="url-hint"></div>
      </div>

      <div class="form-group">
        <label class="form-label">Type *</label>
        <select name="type" id="addType" class="form-control">
          <option value="youtube">▶️ YouTube Video</option>
          <option value="telegram">📱 Telegram Channel / Group</option>
          <option value="pdf">📄 PDF / Document</option>
          <option value="website">🌐 Website / Article</option>
          <option value="notes">📝 Notes</option>
          <option value="book">📚 Book / Textbook</option>
          <option value="link">🔗 Other Link</option>
        </select>
      </div>

      <div class="form-group">
        <label class="form-label">Subject Tag</label>
        <input type="text" name="subject_tag" class="form-control"
               placeholder="e.g. Physics, Maths, All Students"
               list="tagSuggestions">
        <datalist id="tagSuggestions">
          <option value="All Students"><option value="Physics"><option value="Chemistry">
          <option value="Mathematics"><option value="Combined Maths"><option value="Biology">
          <option value="ICT"><option value="Economics"><option value="Accounting">
          <option value="Business Studies"><option value="Science Stream">
          <option value="Arts Stream"><option value="Technology Stream">
        </datalist>
        <div style="font-size:11px;color:var(--text-muted);margin-top:4px">Students can filter by this tag</div>
      </div>

      <div class="form-group">
        <label class="form-label">Description</label>
        <textarea name="notes" class="form-control" rows="2"
                  placeholder="Brief description of what students will find here..."></textarea>
      </div>

      <button type="submit" class="btn btn-primary btn-full">🗂️ Add Resource</button>
    </form>
  </div>

  <!-- Category breakdown -->
  <?php if (!empty($typeStats)): ?>
  <div class="card" style="margin-top:16px">
    <div class="card-header"><div class="card-title">📊 By Category</div></div>
    <?php foreach ($typeStats as $ts):
      [$ic,$col,$lbl] = $typeMap[$ts['type']] ?? ['🔗','#a855f7',$ts['type']];
    ?>
    <div style="display:flex;align-items:center;justify-content:space-between;padding:9px 0;border-bottom:1px solid var(--border)">
      <span style="font-size:13px;color:var(--text-primary)"><?= $ic ?> <?= $lbl ?></span>
      <span style="font-size:12px;font-weight:700;background:<?= $col ?>22;color:<?= $col ?>;padding:2px 10px;border-radius:20px"><?= $ts['cnt'] ?></span>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</div>

<!-- ── RESOURCE LIST ── -->
<div>
  <!-- Type filter -->
  <div style="display:flex;flex-wrap:wrap;gap:7px;margin-bottom:14px">
    <a href="?" class="type-pill <?= !$typeFilter?'on':'' ?>">All</a>
    <?php foreach ($typeMap as $t=>[$ic,$col,$lbl]): ?>
    <a href="?type=<?= $t ?>" class="type-pill <?= $typeFilter===$t?'on':'' ?>"
       style="<?= $typeFilter===$t?"border-color:$col;background:{$col}22;color:$col":'' ?>">
      <?= $ic ?> <?= explode(' ',$lbl)[0] ?>
    </a>
    <?php endforeach; ?>
  </div>

  <div class="card">
    <div class="card-header">
      <div class="card-title">📋 All Resources <span style="color:var(--text-muted);font-weight:400">(<?= count($resources) ?>)</span></div>
    </div>

    <?php if (empty($resources)): ?>
    <div class="empty-state" style="padding:40px">
      <div class="empty-icon">🗂️</div>
      <h3>No resources yet</h3>
      <p>Add YouTube videos, Telegram channels, PDFs and more</p>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;gap:10px;padding:16px">
    <?php foreach ($resources as $r):
      [$ic,$col,$lbl] = $typeMap[$r['type']] ?? ['🔗','#a855f7','Other'];
    ?>
    <div class="res-row" style="border-left:4px solid <?= $r['is_active'] ? $col : 'var(--border)' ?>;<?= !$r['is_active']?'opacity:0.55':'' ?>">
      <!-- Icon -->
      <div style="font-size:26px;flex-shrink:0;line-height:1;margin-top:2px"><?= $ic ?></div>

      <!-- Info -->
      <div style="flex:1;min-width:0">
        <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:4px">
          <span style="font-size:14px;font-weight:700;color:var(--text-primary)"><?= htmlspecialchars($r['title']) ?></span>
          <span style="font-size:10px;font-weight:700;background:<?= $col ?>22;color:<?= $col ?>;padding:1px 7px;border-radius:20px"><?= $lbl ?></span>
          <?php if ($r['subject_tag']): ?>
          <span style="font-size:10px;background:rgba(99,102,241,0.12);color:var(--accent);padding:1px 7px;border-radius:20px;font-weight:600"><?= htmlspecialchars($r['subject_tag']) ?></span>
          <?php endif; ?>
          <?php if (!$r['is_active']): ?>
          <span style="font-size:10px;background:rgba(100,116,139,0.15);color:var(--text-muted);padding:1px 7px;border-radius:20px">🔒 Hidden</span>
          <?php endif; ?>
        </div>
        <?php if ($r['notes']): ?>
        <div style="font-size:12px;color:var(--text-muted);margin-bottom:5px"><?= htmlspecialchars($r['notes']) ?></div>
        <?php endif; ?>
        <a href="<?= htmlspecialchars($r['url']) ?>" target="_blank"
           style="font-size:11px;color:var(--accent);text-decoration:none;word-break:break-all">
          <?= htmlspecialchars(mb_substr($r['url'],0,55)) ?><?= mb_strlen($r['url'])>55?'…':'' ?>
        </a>
        <div style="font-size:10px;color:var(--text-muted);margin-top:3px">Added <?= date('M j, Y',strtotime($r['created_at'])) ?></div>
      </div>

      <!-- Actions -->
      <div style="display:flex;flex-direction:column;gap:5px;flex-shrink:0">
        <form method="POST">
          <input type="hidden" name="action" value="toggle">
          <input type="hidden" name="id" value="<?= $r['id'] ?>">
          <button class="btn btn-sm <?= $r['is_active']?'btn-secondary':'btn-primary' ?>" style="width:70px;font-size:11px">
            <?= $r['is_active']?'🔒 Hide':'👁 Show' ?>
          </button>
        </form>
        <button onclick="openEdit(<?= htmlspecialchars(json_encode($r),ENT_QUOTES) ?>)"
                class="btn btn-secondary btn-sm" style="width:70px;font-size:11px">✏️ Edit</button>
        <form method="POST" onsubmit="return confirm('Delete this resource?')">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?= $r['id'] ?>">
          <button class="btn btn-danger btn-sm" style="width:70px;font-size:11px">🗑 Del</button>
        </form>
      </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>
</div>
</div><!-- /grid -->

<!-- Edit Modal -->
<div class="modal-overlay" id="editModal">
  <div class="modal" style="max-width:480px">
    <div class="modal-header">
      <span class="modal-title">✏️ Edit Resource</span>
      <button class="modal-close" onclick="document.getElementById('editModal').classList.remove('active')">✕</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="eId">
      <div class="form-group">
        <label class="form-label">Title</label>
        <input type="text" name="title" id="eTitle" class="form-control" required>
      </div>
      <div class="form-group">
        <label class="form-label">URL</label>
        <input type="url" name="url" id="eUrl" class="form-control" required oninput="detectUrlType(this,'eType','eHint')">
        <div id="eHint" class="url-hint"></div>
      </div>
      <div class="form-group">
        <label class="form-label">Type</label>
        <select name="type" id="eType" class="form-control">
          <option value="youtube">▶️ YouTube Video</option>
          <option value="telegram">📱 Telegram Channel / Group</option>
          <option value="pdf">📄 PDF / Document</option>
          <option value="website">🌐 Website / Article</option>
          <option value="notes">📝 Notes</option>
          <option value="book">📚 Book / Textbook</option>
          <option value="link">🔗 Other Link</option>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Subject Tag</label>
        <input type="text" name="subject_tag" id="eSubject" class="form-control">
      </div>
      <div class="form-group">
        <label class="form-label">Description</label>
        <textarea name="notes" id="eNotes" class="form-control" rows="2"></textarea>
      </div>
      <button type="submit" class="btn btn-primary btn-full">💾 Save Changes</button>
    </form>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
<script>
function detectUrlType(input, typeId, hintId) {
  var url  = input.value;
  var sel  = document.getElementById(typeId);
  var hint = document.getElementById(hintId);
  var configs = [
    { test: u => u.includes('youtube.com')||u.includes('youtu.be'), val:'youtube',  bg:'rgba(239,68,68,0.1)',  color:'#ef4444', text:'▶️ YouTube video detected'},
    { test: u => u.includes('t.me')||u.includes('telegram.me'),    val:'telegram', bg:'rgba(42,171,238,0.1)', color:'#2AABEE', text:'📱 Telegram link detected'},
    { test: u => u.match(/\.pdf(\?.*)?$/i),                        val:'pdf',      bg:'rgba(245,158,11,0.1)', color:'#f59e0b', text:'📄 PDF detected'},
  ];
  var matched = configs.find(c => c.test(url));
  if (matched && url.length > 8) {
    sel.value = matched.val;
    hint.style.display  = 'block';
    hint.style.background = matched.bg;
    hint.style.color    = matched.color;
    hint.textContent    = matched.text + ' — type set automatically';
  } else {
    hint.style.display = 'none';
  }
}

function openEdit(r) {
  document.getElementById('eId').value      = r.id;
  document.getElementById('eTitle').value   = r.title;
  document.getElementById('eUrl').value     = r.url;
  document.getElementById('eType').value    = r.type;
  document.getElementById('eSubject').value = r.subject_tag || '';
  document.getElementById('eNotes').value   = r.notes || '';
  document.getElementById('editModal').classList.add('active');
}
</script>
