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

$UPLOAD_DIR = __DIR__ . '/assets/uploads/subject_files/';
$UPLOAD_REL = 'assets/uploads/subject_files/';
if (!is_dir($UPLOAD_DIR)) mkdir($UPLOAD_DIR, 0755, true);

$MAX_SIZE = 25 * 1024 * 1024; // 25MB per file
$EXT_MAP = [
    'pdf' => 'pdf',
    'doc' => 'doc', 'docx' => 'doc',
    'ppt' => 'ppt', 'pptx' => 'ppt',
    'xls' => 'sheet', 'xlsx' => 'sheet', 'csv' => 'sheet',
    'jpg' => 'image', 'jpeg' => 'image', 'png' => 'image', 'gif' => 'image', 'webp' => 'image',
    'txt' => 'text',
];

function ft_icon($type) {
    return [
        'pdf' => '📕', 'doc' => '📄', 'ppt' => '📊', 'sheet' => '📈',
        'image' => '🖼️', 'text' => '📝',
    ][$type] ?? '📁';
}

// ── AJAX actions ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'upload_file') {
        $subId = (int)($_POST['subject_id'] ?? 0);
        $desc  = sanitize($_POST['description'] ?? '');
        if (!$subId) jsonResponse(['success' => false, 'message' => 'Please choose a subject.']);

        $chk = $pdo->prepare("SELECT id FROM subjects WHERE id=? AND user_id=?");
        $chk->execute([$subId, $uid]);
        if (!$chk->fetch()) jsonResponse(['success' => false, 'message' => 'Invalid subject.']);

        if (!isset($_FILES['upload']) || $_FILES['upload']['error'] !== 0) {
            jsonResponse(['success' => false, 'message' => 'No file received, or upload error.']);
        }
        $file = $_FILES['upload'];
        if ($file['size'] > $MAX_SIZE) jsonResponse(['success' => false, 'message' => 'File too large (max 25MB).']);

        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!isset($EXT_MAP[$ext])) {
            jsonResponse(['success' => false, 'message' => 'File type not allowed. Allowed: PDF, Word, PowerPoint, Excel, images, text.']);
        }
        $type = $EXT_MAP[$ext];
        $storedName = 'sf_' . $uid . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $dest = $UPLOAD_DIR . $storedName;

        if (move_uploaded_file($file['tmp_name'], $dest)) {
            $rel = $UPLOAD_REL . $storedName;
            $origName = sanitize($file['name']);
            $pdo->prepare("INSERT INTO subject_files (user_id,subject_id,file_name,stored_name,file_path,file_type,mime_type,file_size,description) VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$uid, $subId, $origName, $storedName, $rel, $type, $file['type'], $file['size'], $desc]);
            jsonResponse(['success' => true, 'message' => 'File uploaded!', 'id' => $pdo->lastInsertId()]);
        } else {
            jsonResponse(['success' => false, 'message' => 'Could not save file on server.']);
        }
    }

    if ($action === 'delete_file') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("SELECT file_path FROM subject_files WHERE id=? AND user_id=?");
        $stmt->execute([$id, $uid]);
        $path = $stmt->fetchColumn();
        if ($path) {
            $pdo->prepare("DELETE FROM subject_files WHERE id=? AND user_id=?")->execute([$id, $uid]);
            $abs = __DIR__ . '/' . $path;
            if (file_exists($abs)) @unlink($abs);
        }
        jsonResponse(['success' => true]);
    }

    if ($action === 'rename_file') {
        $id = (int)($_POST['id'] ?? 0);
        $name = sanitize($_POST['name'] ?? '');
        if (!$name) jsonResponse(['success' => false, 'message' => 'Name cannot be empty.']);
        $pdo->prepare("UPDATE subject_files SET file_name=? WHERE id=? AND user_id=?")->execute([$name, $id, $uid]);
        jsonResponse(['success' => true]);
    }

    jsonResponse(['success' => false, 'message' => 'Unknown action.']);
}

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

$filterSub = (int)($_GET['subject'] ?? 0);
$sql = "SELECT f.*, s.name AS subject_name, s.color AS subject_color FROM subject_files f
        JOIN subjects s ON s.id = f.subject_id WHERE f.user_id = ?";
$params = [$uid];
if ($filterSub) { $sql .= " AND f.subject_id = ?"; $params[] = $filterSub; }
$sql .= " ORDER BY f.created_at DESC";
$filesQ = $pdo->prepare($sql);
$filesQ->execute($params);
$files = $filesQ->fetchAll();

$totalSize = 0;
$allSizeQ = $pdo->prepare("SELECT COALESCE(SUM(file_size),0) FROM subject_files WHERE user_id=?");
$allSizeQ->execute([$uid]);
$totalSize = (int)$allSizeQ->fetchColumn();

require_once 'includes/header.php';
renderHeader('Subject Files', 'subject-files');
?>
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px;flex-wrap:wrap">
  <div>
    <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">📁 Subject Files</div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:3px">Keep documents, images & slides organised by subject</div>
  </div>
  <div style="display:flex;align-items:center;gap:12px">
    <div style="font-size:12px;color:var(--text-muted)"><?= count($files) ?> files · <?= number_format($totalSize/1024/1024, 1) ?>MB used</div>
    <button class="btn btn-primary" onclick="document.getElementById('uploadModal').classList.add('active')">+ Upload File</button>
  </div>
</div>

<!-- Subject filter tabs -->
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px">
  <a href="?" class="btn <?= $filterSub ? 'btn-secondary' : 'btn-primary' ?> btn-sm">All</a>
  <?php foreach ($subjects as $s): ?>
    <a href="?subject=<?= $s['id'] ?>" class="btn <?= $filterSub === (int)$s['id'] ? 'btn-primary' : 'btn-secondary' ?> btn-sm"><?= htmlspecialchars($s['name']) ?></a>
  <?php endforeach; ?>
</div>

<?php if (empty($files)): ?>
  <div class="empty-state">
    <div class="empty-icon">📁</div>
    <h3>No files yet</h3>
    <p>Upload notes, slides, or scanned documents and keep them organised by subject.</p>
  </div>
<?php else: ?>
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px">
    <?php foreach ($files as $f): ?>
      <div class="card" id="sf-<?= $f['id'] ?>" style="border-left:3px solid <?= htmlspecialchars($f['subject_color'] ?: '#6366f1') ?>">
        <div style="display:flex;align-items:flex-start;gap:10px">
          <div style="font-size:28px;flex-shrink:0"><?= ft_icon($f['file_type']) ?></div>
          <div style="flex:1;min-width:0">
            <div id="sf-name-<?= $f['id'] ?>" style="font-size:14px;font-weight:700;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?= htmlspecialchars($f['file_name']) ?>"><?= htmlspecialchars($f['file_name']) ?></div>
            <div style="font-size:11px;color:var(--text-muted);margin-top:3px">
              <span class="badge badge-purple"><?= htmlspecialchars($f['subject_name']) ?></span>
              <?= number_format($f['file_size']/1024,0) ?> KB · <?= date('M j, Y', strtotime($f['created_at'])) ?>
            </div>
            <?php if ($f['description']): ?><div style="font-size:12px;color:var(--text-secondary);margin-top:6px"><?= htmlspecialchars($f['description']) ?></div><?php endif; ?>
          </div>
        </div>
        <div style="display:flex;gap:6px;margin-top:12px">
          <?php if ($f['file_type'] === 'pdf'): ?>
            <a class="btn btn-secondary btn-sm" href="pdf-annotate.php?file=<?= $f['id'] ?>" style="flex:1;text-align:center">✏️ Annotate</a>
          <?php elseif ($f['file_type'] === 'image'): ?>
            <a class="btn btn-secondary btn-sm" href="<?= htmlspecialchars(SITE_URL.'/'.$f['file_path']) ?>" target="_blank" style="flex:1;text-align:center">👁️ View</a>
          <?php else: ?>
            <a class="btn btn-secondary btn-sm" href="<?= htmlspecialchars(SITE_URL.'/'.$f['file_path']) ?>" target="_blank" style="flex:1;text-align:center">👁️ Open</a>
          <?php endif; ?>
          <a class="btn btn-secondary btn-sm" href="<?= htmlspecialchars(SITE_URL.'/'.$f['file_path']) ?>" download title="Download">⬇️</a>
          <button class="btn btn-secondary btn-sm" onclick="renameFile(<?= $f['id'] ?>)" title="Rename">✏️</button>
          <button class="btn btn-danger btn-sm" onclick="deleteFile(<?= $f['id'] ?>)" title="Delete">🗑️</button>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<!-- Upload Modal -->
<div class="modal-overlay" id="uploadModal">
  <div class="modal" style="max-width:440px">
    <div class="modal-header">
      <h3 class="modal-title">Upload File</h3>
      <button class="modal-close" onclick="document.getElementById('uploadModal').classList.remove('active')">✕</button>
    </div>
    <div class="form-group">
      <label class="form-label">Subject</label>
      <select id="uSubject" class="form-input">
        <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">File</label>
      <input type="file" id="uFile" class="form-input" accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.csv,.jpg,.jpeg,.png,.gif,.webp,.txt">
      <div style="font-size:11px;color:var(--text-muted);margin-top:5px">PDF, Word, PowerPoint, Excel, images, or text · max 25MB</div>
    </div>
    <div class="form-group">
      <label class="form-label">Note (optional)</label>
      <input type="text" id="uDesc" class="form-input" placeholder="e.g. Chapter 5 summary notes">
    </div>
    <div id="uMsg" style="display:none;margin-bottom:12px"></div>
    <button class="btn btn-primary" style="width:100%" onclick="uploadFile()">Upload</button>
  </div>
</div>

<script>
async function uploadFile() {
  const subject = document.getElementById('uSubject').value;
  const fileInput = document.getElementById('uFile');
  const msg = document.getElementById('uMsg');
  if (!subject) { msg.style.display='block'; msg.className='alert alert-error'; msg.textContent='Please select a subject.'; return; }
  if (!fileInput.files.length) { msg.style.display='block'; msg.className='alert alert-error'; msg.textContent='Please choose a file.'; return; }

  const fd = new FormData();
  fd.append('action', 'upload_file');
  fd.append('subject_id', subject);
  fd.append('description', document.getElementById('uDesc').value);
  fd.append('upload', fileInput.files[0]);

  msg.style.display='block'; msg.className='alert alert-info'; msg.textContent='Uploading…';
  const r = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body: fd });
  const data = await r.json();
  if (data.success) location.reload();
  else { msg.className='alert alert-error'; msg.textContent = data.message || 'Upload failed.'; }
}

async function post(data) {
  const fd = new FormData();
  Object.entries(data).forEach(([k,v]) => fd.append(k, v));
  const r = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body: fd });
  return r.json();
}

async function deleteFile(id) {
  if (!(await stConfirm('Delete this file permanently?'))) return;
  await post({ action:'delete_file', id });
  const el = document.getElementById('sf-' + id);
  if (el) el.remove();
}

async function renameFile(id) {
  const cur = document.getElementById('sf-name-' + id).textContent;
  const name = prompt('Rename file:', cur);
  if (name === null || !name.trim()) return;
  await post({ action:'rename_file', id, name: name.trim() });
  document.getElementById('sf-name-' + id).textContent = name.trim();
}
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
