<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── AJAX: user's own resources ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add_mine') {
        $subId = (int)($_POST['subject_id'] ?? 0);
        $title = sanitize($_POST['title'] ?? '');
        $url   = sanitize($_POST['url'] ?? '');
        $type  = sanitize($_POST['type'] ?? 'link');
        $notes = sanitize($_POST['notes'] ?? '');
        if (!$subId || !$title || !$url)
            jsonResponse(['success'=>false,'message'=>'Subject, title and URL are required.']);
        if (!filter_var($url, FILTER_VALIDATE_URL))
            jsonResponse(['success'=>false,'message'=>'Please enter a valid URL (include https://).']);
        $pdo->prepare("INSERT INTO subject_resources (user_id,subject_id,title,url,type,notes) VALUES (?,?,?,?,?,?)")
            ->execute([$uid,$subId,$title,$url,$type,$notes]);
        jsonResponse(['success'=>true,'message'=>'Resource saved!']);
    }

    if ($action === 'delete_mine') {
        $pdo->prepare("DELETE FROM subject_resources WHERE id=? AND user_id=?")->execute([(int)$_POST['id'],$uid]);
        jsonResponse(['success'=>true]);
    }
}

// ── FILTERS ──────────────────────────────────────────────────────
$tab        = $_GET['tab']  ?? 'admin';
$typeFilter = $_GET['type'] ?? '';
$tagFilter  = $_GET['tag']  ?? '';

// ── ADMIN RESOURCES ──────────────────────────────────────────────
$aWhere = "WHERE is_active=1";
if ($typeFilter) $aWhere .= " AND type='" . htmlspecialchars($typeFilter, ENT_QUOTES) . "'";
if ($tagFilter)  $aWhere .= " AND subject_tag='" . htmlspecialchars($tagFilter, ENT_QUOTES) . "'";

$adminRes   = $pdo->query("SELECT * FROM admin_resources $aWhere ORDER BY type ASC, created_at DESC")->fetchAll();
$adminTags  = $pdo->query("SELECT DISTINCT subject_tag FROM admin_resources WHERE is_active=1 AND subject_tag!='' ORDER BY subject_tag")->fetchAll(PDO::FETCH_COLUMN);
$adminCount = (int)$pdo->query("SELECT COUNT(*) FROM admin_resources WHERE is_active=1")->fetchColumn();
$aTypeCnt   = [];
foreach ($pdo->query("SELECT type,COUNT(*) c FROM admin_resources WHERE is_active=1 GROUP BY type")->fetchAll() as $r)
    $aTypeCnt[$r['type']] = $r['c'];

// Group admin resources by type
$adminByType = [];
foreach ($adminRes as $r) $adminByType[$r['type']][] = $r;

// ── MY RESOURCES ─────────────────────────────────────────────────
$mWhere = "WHERE sr.user_id=$uid";
if ($typeFilter) $mWhere .= " AND sr.type='" . htmlspecialchars($typeFilter, ENT_QUOTES) . "'";
$myRes = $pdo->prepare("
    SELECT sr.*, s.name subject_name, s.color subject_color
    FROM subject_resources sr
    JOIN subjects s ON sr.subject_id=s.id
    $mWhere ORDER BY s.name, sr.created_at DESC
");
$myRes->execute();
$myRes = $myRes->fetchAll();
$myBySubject = [];
foreach ($myRes as $r) $myBySubject[$r['subject_name']][] = $r;

// Subjects for modal
$subjects = $pdo->prepare("SELECT id,name,color FROM subjects WHERE user_id=? ORDER BY name");
$subjects->execute([$uid]);
$subjects = $subjects->fetchAll();

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

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

<style>
/* ── Tabs ── */
.rtab-bar{display:flex;gap:3px;background:var(--bg-secondary);border-radius:12px;padding:4px;width:fit-content;margin-bottom:20px}
.rtab{padding:8px 22px;border-radius:9px;font-size:13px;font-weight:600;cursor:pointer;border:none;background:none;color:var(--text-muted);transition:all .18s}
.rtab.on{background:var(--bg-card);color:var(--text-primary);box-shadow:0 2px 8px rgba(0,0,0,.15)}
/* ── Cards ── */
.res-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:14px}
.res-card{
  background:var(--bg-secondary);border:1px solid var(--border);border-radius:14px;
  padding:16px;display:flex;flex-direction:column;gap:9px;
  transition:transform .18s,box-shadow .18s;position:relative;overflow:hidden;
}
.res-card:hover{transform:translateY(-3px);box-shadow:0 10px 28px rgba(0,0,0,.14)}
.res-open-btn{
  display:inline-flex;align-items:center;gap:5px;margin-top:auto;align-self:flex-start;
  padding:6px 14px;border-radius:8px;font-size:12px;font-weight:700;text-decoration:none;
  transition:filter .15s;border:none;cursor:pointer;
}
.res-open-btn:hover{filter:brightness(1.1)}
/* ── Filter pills ── */
.fpill{
  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 .15s;white-space:nowrap;
}
.fpill:hover,.fpill.on{border-color:var(--accent);background:rgba(99,102,241,.1);color:var(--accent)}
/* ── Section heading ── */
.type-heading{
  display:flex;align-items:center;gap:10px;margin-bottom:12px;margin-top:6px;
}
.type-heading-icon{
  width:34px;height:34px;border-radius:10px;display:flex;align-items:center;
  justify-content:center;font-size:16px;flex-shrink:0;
}
.admin-badge-tag{font-size:10px;color:var(--text-muted);margin-top:2px}
</style>

<!-- Header -->
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:20px">
  <div>
    <h2 style="font-size:20px;font-weight:800;color:var(--text-primary);margin:0">🗂️ Study Resources</h2>
    <p style="font-size:13px;color:var(--text-muted);margin:4px 0 0">
      <?= $adminCount ?> resources from admin &nbsp;·&nbsp; <?= count($myRes) ?> saved by you
    </p>
  </div>
  <button class="btn btn-primary" onclick="openMyModal()">＋ Save My Resource</button>
</div>

<!-- Tabs -->
<div class="rtab-bar">
  <button class="rtab <?= $tab==='admin'?'on':'' ?>" id="tbAdmin" onclick="switchTab('admin')">
    📚 From Admin
    <?php if($adminCount): ?>
    <span style="background:rgba(99,102,241,.15);color:var(--accent);padding:1px 7px;border-radius:10px;font-size:11px;margin-left:4px"><?= $adminCount ?></span>
    <?php endif ?>
  </button>
  <button class="rtab <?= $tab==='mine'?'on':'' ?>" id="tbMine" onclick="switchTab('mine')">
    🔖 My Saved
    <?php if(count($myRes)): ?>
    <span style="background:rgba(99,102,241,.15);color:var(--accent);padding:1px 7px;border-radius:10px;font-size:11px;margin-left:4px"><?= count($myRes) ?></span>
    <?php endif ?>
  </button>
</div>

<!-- ═══════════════ ADMIN TAB ═══════════════ -->
<div id="sec-admin" style="<?= $tab!=='admin'?'display:none':'' ?>">

  <!-- Type filter -->
  <div style="display:flex;flex-wrap:wrap;gap:7px;margin-bottom:10px">
    <a href="?tab=admin<?= $tagFilter?'&tag='.urlencode($tagFilter):'' ?>" class="fpill <?= !$typeFilter?'on':'' ?>">All Types</a>
    <?php foreach ($typeMap as $t=>[$ic,$col,$lbl,$btn]): if (!isset($aTypeCnt[$t])) continue; ?>
    <a href="?tab=admin&type=<?= $t ?><?= $tagFilter?'&tag='.urlencode($tagFilter):'' ?>"
       class="fpill <?= $typeFilter===$t?'on':'' ?>"
       style="<?= $typeFilter===$t?"border-color:$col;background:{$col}22;color:$col":'' ?>">
      <?= $ic ?> <?= $lbl ?> <span style="opacity:.65">(<?= $aTypeCnt[$t] ?>)</span>
    </a>
    <?php endforeach ?>
  </div>

  <!-- Subject tag filter -->
  <?php if (!empty($adminTags)): ?>
  <div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:16px;align-items:center">
    <span style="font-size:11px;color:var(--text-muted);font-weight:600">SUBJECT:</span>
    <a href="?tab=admin<?= $typeFilter?'&type='.$typeFilter:'' ?>" class="fpill <?= !$tagFilter?'on':'' ?>" style="padding:3px 11px">All</a>
    <?php foreach ($adminTags as $tag): ?>
    <a href="?tab=admin&tag=<?= urlencode($tag) ?><?= $typeFilter?'&type='.$typeFilter:'' ?>"
       class="fpill <?= $tagFilter===$tag?'on':'' ?>" style="padding:3px 11px">
      <?= htmlspecialchars($tag) ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php endif ?>

  <?php if (empty($adminRes)): ?>
  <div class="card"><div class="empty-state" style="padding:50px">
    <div class="empty-icon">📚</div>
    <h3>No resources from admin yet</h3>
    <p>Your teacher hasn't published any resources yet. Check back later!</p>
  </div></div>

  <?php else: ?>
  <?php foreach ($adminByType as $type => $items):
    [$ic,$col,$lbl,$openBtn] = $typeMap[$type] ?? ['🔗','#a855f7','Link','🔗 Open'];
  ?>
  <div style="margin-bottom:26px">
    <div class="type-heading">
      <div class="type-heading-icon" style="background:<?= $col ?>22;border:1px solid <?= $col ?>44"><?= $ic ?></div>
      <div>
        <div style="font-size:14px;font-weight:800;color:var(--text-primary)"><?= $lbl ?></div>
        <div style="font-size:12px;color:var(--text-muted)"><?= count($items) ?> resource<?= count($items)!=1?'s':'' ?></div>
      </div>
    </div>

    <div class="res-grid">
    <?php foreach ($items as $r): ?>
    <div class="res-card" style="border-top:3px solid <?= $col ?>">
      <!-- Badges row -->
      <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
        <span style="font-size:10px;font-weight:700;background:<?= $col ?>22;color:<?= $col ?>;padding:2px 8px;border-radius:20px"><?= $ic ?> <?= $lbl ?></span>
        <?php if ($r['subject_tag']): ?>
        <span style="font-size:10px;font-weight:700;background:rgba(99,102,241,.12);color:var(--accent);padding:2px 8px;border-radius:20px"><?= htmlspecialchars($r['subject_tag']) ?></span>
        <?php endif ?>
      </div>
      <!-- Title -->
      <div style="font-size:14px;font-weight:800;color:var(--text-primary);line-height:1.35">
        <?= htmlspecialchars($r['title']) ?>
      </div>
      <!-- Description -->
      <?php if ($r['notes']): ?>
      <div style="font-size:12px;color:var(--text-muted);line-height:1.5"><?= htmlspecialchars($r['notes']) ?></div>
      <?php endif ?>
      <!-- Open button -->
      <a href="<?= htmlspecialchars($r['url']) ?>" target="_blank" rel="noopener"
         class="res-open-btn" style="background:<?= $col ?>20;color:<?= $col ?>">
        <?= $openBtn ?>
        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15,3 21,3 21,9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
      </a>
      <div class="admin-badge-tag">📌 Added by Admin</div>
    </div>
    <?php endforeach ?>
    </div>
  </div>
  <?php endforeach ?>
  <?php endif ?>

</div><!-- /admin tab -->

<!-- ═══════════════ MY RESOURCES TAB ═══════════════ -->
<div id="sec-mine" style="<?= $tab!=='mine'?'display:none':'' ?>">

  <!-- Type filter -->
  <div style="display:flex;flex-wrap:wrap;gap:7px;margin-bottom:16px">
    <a href="?tab=mine" class="fpill <?= !$typeFilter?'on':'' ?>">All</a>
    <?php foreach ($typeMap as $t=>[$ic,$col,$lbl,$btn]): ?>
    <a href="?tab=mine&type=<?= $t ?>" class="fpill <?= $typeFilter===$t?'on':'' ?>"
       style="<?= $typeFilter===$t?"border-color:$col;background:{$col}22;color:$col":'' ?>">
      <?= $ic ?> <?= $lbl ?>
    </a>
    <?php endforeach ?>
  </div>

  <?php if (empty($myRes)): ?>
  <div class="card"><div class="empty-state" style="padding:50px">
    <div class="empty-icon">🔖</div>
    <h3>No personal resources yet</h3>
    <p>Click "＋ Save My Resource" to bookmark your own YouTube videos, PDFs, and links</p>
  </div></div>

  <?php else: ?>
  <?php foreach ($myBySubject as $subName => $subArr):
    $sc = $subArr[0]['subject_color'];
  ?>
  <div style="margin-bottom:24px">
    <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px">
      <span style="width:11px;height:11px;border-radius:50%;background:<?= htmlspecialchars($sc) ?>;display:inline-block;flex-shrink:0"></span>
      <span style="font-size:14px;font-weight:800;color:var(--text-primary)"><?= htmlspecialchars($subName) ?></span>
      <span style="font-size:12px;color:var(--text-muted)"><?= count($subArr) ?> saved</span>
    </div>
    <div class="res-grid">
    <?php foreach ($subArr as $r):
      [$ic,$col,$lbl,$openBtn] = $typeMap[$r['type']] ?? ['🔗','#a855f7','Link','🔗 Open'];
      if (str_contains($r['url'],'youtube.com')||str_contains($r['url'],'youtu.be')) { $ic='▶️';$col='#ef4444';$openBtn='▶ Watch on YouTube'; }
      if (str_contains($r['url'],'t.me')||str_contains($r['url'],'telegram.me'))     { $ic='📱';$col='#2AABEE';$openBtn='📱 Open Telegram'; }
    ?>
    <div class="res-card" style="border-top:3px solid <?= $col ?>">
      <div style="display:flex;align-items:center;justify-content:space-between;gap:8px">
        <span style="font-size:10px;font-weight:700;background:<?= $col ?>22;color:<?= $col ?>;padding:2px 8px;border-radius:20px"><?= $ic ?> <?= $lbl ?></span>
        <button onclick="deleteMyRes(<?= $r['id'] ?>)"
          style="background:rgba(239,68,68,.08);color:#ef4444;border:none;border-radius:6px;padding:3px 8px;cursor:pointer;font-size:12px">🗑</button>
      </div>
      <div style="font-size:14px;font-weight:800;color:var(--text-primary);line-height:1.35"><?= htmlspecialchars($r['title']) ?></div>
      <?php if ($r['notes']): ?>
      <div style="font-size:12px;color:var(--text-muted);line-height:1.5"><?= htmlspecialchars($r['notes']) ?></div>
      <?php endif ?>
      <a href="<?= htmlspecialchars($r['url']) ?>" target="_blank" rel="noopener"
         class="res-open-btn" style="background:<?= $col ?>20;color:<?= $col ?>">
        <?= $openBtn ?>
        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15,3 21,3 21,9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
      </a>
    </div>
    <?php endforeach ?>
    </div>
  </div>
  <?php endforeach ?>
  <?php endif ?>

</div><!-- /mine tab -->

<!-- ═══ Add My Resource Modal ═══ -->
<div class="modal-overlay" id="myResModal">
  <div class="modal" style="max-width:460px">
    <div class="modal-header">
      <span class="modal-title">🔖 Save My Resource</span>
      <button class="modal-close" onclick="document.getElementById('myResModal').classList.remove('active')">✕</button>
    </div>
    <div id="myResMsg" class="alert" style="display:none"></div>

    <div class="form-group">
      <label class="form-label">Subject *</label>
      <select id="mrSubject" class="form-control">
        <option value="">— Select Subject —</option>
        <?php foreach ($subjects as $s): ?>
        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
        <?php endforeach ?>
      </select>
    </div>
    <div class="form-group">
      <label class="form-label">Title *</label>
      <input type="text" id="mrTitle" class="form-control" placeholder="e.g. Electrostatics Full Chapter">
    </div>
    <div class="form-group">
      <label class="form-label">URL *</label>
      <input type="url" id="mrUrl" class="form-control" placeholder="https://..." oninput="mrDetect()">
      <div id="mrHint" style="display:none;font-size:12px;margin-top:5px;padding:6px 10px;border-radius:8px"></div>
    </div>
    <div class="form-group">
      <label class="form-label">Type</label>
      <select id="mrType" class="form-control">
        <option value="youtube">▶️ YouTube</option>
        <option value="telegram">📱 Telegram</option>
        <option value="pdf">📄 PDF</option>
        <option value="website">🌐 Website</option>
        <option value="notes">📝 Notes</option>
        <option value="book">📚 Book</option>
        <option value="link" selected>🔗 Other</option>
      </select>
    </div>
    <div class="form-group">
      <label class="form-label">Description (optional)</label>
      <textarea id="mrNotes" class="form-control" rows="2" placeholder="Short note..."></textarea>
    </div>
    <button class="btn btn-primary btn-full" onclick="saveMyRes()">💾 Save Resource</button>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
<script>
function switchTab(t) {
  document.getElementById('sec-admin').style.display = t==='admin' ? 'block' : 'none';
  document.getElementById('sec-mine').style.display  = t==='mine'  ? 'block' : 'none';
  document.getElementById('tbAdmin').classList.toggle('on', t==='admin');
  document.getElementById('tbMine').classList.toggle('on',  t==='mine');
  history.replaceState(null,'','?tab='+t);
}

function openMyModal() { document.getElementById('myResModal').classList.add('active'); }

function mrDetect() {
  var url  = document.getElementById('mrUrl').value;
  var hint = document.getElementById('mrHint');
  var sel  = document.getElementById('mrType');
  var opts = [
    {t:u=>u.includes('youtube.com')||u.includes('youtu.be'), v:'youtube', bg:'rgba(239,68,68,.1)', c:'#ef4444', tx:'▶️ YouTube detected'},
    {t:u=>u.includes('t.me')||u.includes('telegram.me'),    v:'telegram',bg:'rgba(42,171,238,.1)',c:'#2AABEE',tx:'📱 Telegram detected'},
    {t:u=>u.match(/\.pdf(\?.*)?$/i),                        v:'pdf',     bg:'rgba(245,158,11,.1)',c:'#f59e0b',tx:'📄 PDF detected'},
  ];
  var m = opts.find(o=>o.t(url));
  if (m && url.length>8) {
    sel.value=m.v; hint.style.display='block';
    hint.style.background=m.bg; hint.style.color=m.c; hint.textContent=m.tx;
  } else { hint.style.display='none'; }
}

async function saveMyRes() {
  var fd = new FormData();
  fd.append('action',     'add_mine');
  fd.append('subject_id', document.getElementById('mrSubject').value);
  fd.append('title',      document.getElementById('mrTitle').value);
  fd.append('url',        document.getElementById('mrUrl').value);
  fd.append('type',       document.getElementById('mrType').value);
  fd.append('notes',      document.getElementById('mrNotes').value);
  var msg = document.getElementById('myResMsg');
  msg.style.display='none';
  try {
    var res  = await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
    var data = await res.json();
    msg.style.display='flex'; msg.className='alert '+(data.success?'alert-success':'alert-error');
    msg.textContent=data.message;
    if (data.success) setTimeout(()=>{ location.href='?tab=mine'; },700);
  } catch(e) { msg.style.display='flex'; msg.className='alert alert-error'; msg.textContent='Error saving.'; }
}

async function deleteMyRes(id) {
  if(!(await stConfirm('Remove this resource?'))) return;
  var fd=new FormData(); fd.append('action','delete_mine'); fd.append('id',id);
  await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
  location.reload();
}
</script>
