<?php
session_start();
require_once __DIR__ . '/config/database.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    http_response_code(404);
    echo 'Invalid notice ID';
    exit;
}

// Load notice (public: active, published, not expired)
$notice = null;
try {
    $stmt = $pdo->prepare("SELECT n.*, c.name AS class_name, c.section AS class_section, u.username AS created_by_name
                           FROM notices n
                           LEFT JOIN classes c ON n.class_id = c.id
                           LEFT JOIN users u ON n.created_by = u.id
                           WHERE n.id = ?
                             AND n.status = 'active'
                             AND n.publish_date <= CURDATE()
                             AND (n.expiry_date IS NULL OR n.expiry_date >= CURDATE())");
    $stmt->execute([$id]);
    $notice = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

if (!$notice) {
    http_response_code(404);
    echo 'Notice not found or not available';
    exit;
}

// Load attachments
$attachments = [];
try {
    $stmtA = $pdo->prepare("SELECT id, file_path, original_name, mime_type, file_size, created_at
                             FROM notices_attachments WHERE notice_id = ? ORDER BY id ASC");
    $stmtA->execute([$id]);
    $attachments = $stmtA->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) { $attachments = []; }

function bn_date($date) { return $date ? date('d-m-Y', strtotime($date)) : ''; }
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo htmlspecialchars($notice['title']); ?> - নোটিশ</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/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">
  <link href="bidda/assets/css/jessoreboard-theme.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <style>
    body { 
      font-family: 'Hind Siliguri', sans-serif !important;
      background: #f5f7fa; 
    }
    .card { 
      border: 0; 
      border-radius: 14px; 
      box-shadow: 0 10px 25px rgba(0,103,71,0.1); 
      border-top: 4px solid #006747;
      transition: all 0.3s ease;
    }
    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 35px rgba(0,103,71,0.2);
      border-top-color: #F42A41;
    }
    .notice-content { 
      white-space: pre-wrap;
      line-height: 1.8;
      font-size: 1.05rem;
    }
    .navbar {
      background: linear-gradient(135deg, #006747 0%, #004d35 100%) !important;
      border-bottom: 3px solid #F42A41;
      box-shadow: 0 4px 20px rgba(0,103,71,0.3);
    }
    .navbar-brand {
      color: #fff !important;
      font-weight: 700;
      text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
    }
    .btn-primary {
      background: linear-gradient(135deg, #006747 0%, #004d35 100%) !important;
      border: none;
      font-weight: 600;
    }
    .btn-primary:hover {
      background: linear-gradient(135deg, #004d35 0%, #006747 100%) !important;
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0,103,71,0.4);
    }
    .btn-outline-primary {
      border-color: #006747;
      color: #006747;
      font-weight: 600;
    }
    .btn-outline-primary:hover {
      background: #006747;
      border-color: #006747;
      transform: translateY(-2px);
    }
    .btn-outline-secondary {
      font-weight: 600;
    }
    .badge.bg-danger {
      background: linear-gradient(135deg, #F42A41 0%, #d32f2f 100%) !important;
    }
    .badge.bg-warning {
      background: linear-gradient(135deg, #f57c00 0%, #ff6b35 100%) !important;
    }
    .badge.bg-info {
      background: linear-gradient(135deg, #1976d2 0%, #0066cc 100%) !important;
    }
    h3 {
      color: #006747;
      font-weight: 700;
    }
    hr {
      border-color: #006747;
      opacity: 0.2;
    }
  </style>
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container">
      <a class="navbar-brand" href="index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
      <div class="ms-auto d-flex gap-2">
        <a class="btn btn-outline-light" href="javascript:window.print()"><i class="fas fa-print"></i> প্রিন্ট</a>
        <a class="btn btn-primary" href="login.php"><i class="fas fa-sign-in-alt"></i> লগইন</a>
      </div>
    </div>
  </nav>

  <div class="container my-4">
    <div class="card">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start">
          <div>
            <h3 class="mb-1"><?php echo htmlspecialchars($notice['title']); ?></h3>
            <div class="text-muted small">
              <i class="far fa-calendar"></i> প্রকাশ: <?php echo bn_date($notice['publish_date']); ?>
              <?php if (!empty($notice['expiry_date'])): ?> | <i class="far fa-clock"></i> মেয়াদ: <?php echo bn_date($notice['expiry_date']); ?><?php endif; ?>
              <?php if (!empty($notice['created_by_name'])): ?> | <i class="fas fa-user"></i> <?php echo htmlspecialchars($notice['created_by_name']); ?><?php endif; ?>
            </div>
            <div class="mt-1">
              <?php
                $priority = $notice['priority'];
                $badge = $priority==='urgent'?'danger':($priority==='high'?'warning':($priority==='medium'?'info':'secondary'));
              ?>
              <span class="badge bg-<?php echo $badge; ?>">প্রায়োরিটি: <?php echo htmlspecialchars($priority); ?></span>
              <span class="badge bg-light text-dark">
                <i class="fas fa-users"></i>
                <?php
                  switch ($notice['target_audience']) {
                    case 'all': echo 'সবার জন্য'; break;
                    case 'students': echo 'ছাত্র-ছাত্রী'; break;
                    case 'teachers': echo 'শিক্ষক'; break;
                    case 'parents': echo 'অভিভাবক'; break;
                    case 'specific_class':
                      echo ($notice['class_name'] ? ($notice['class_name'] . ' - ' . $notice['class_section']) : 'নির্দিষ্ট ক্লাস');
                      break;
                  }
                ?>
              </span>
            </div>
          </div>
        </div>

        <hr>

        <div class="notice-content">
          <?php echo nl2br(htmlspecialchars($notice['content'])); ?>
        </div>

        <?php if (!empty($attachments)): ?>
          <hr>
          <h6 class="mb-2"><i class="fas fa-paperclip"></i> সংযুক্তি</h6>
          <div class="row g-3">
            <?php foreach ($attachments as $a): ?>
              <?php
                $path = htmlspecialchars($a['file_path']);
                $name = htmlspecialchars($a['original_name']);
                $mime = strtolower($a['mime_type'] ?? '');
                $isImage = (strpos($mime, 'image/') === 0) || preg_match('/\.(jpg|jpeg|png|gif)$/i', $a['file_path']);
                $isPdf = (strpos($mime, 'application/pdf') === 0) || preg_match('/\.pdf$/i', $a['file_path']);
                $isWord = (strpos($mime, 'application/msword') === 0) || 
                          (strpos($mime, 'application/vnd.openxmlformats-officedocument.wordprocessingml') === 0) ||
                          preg_match('/\.(doc|docx)$/i', $a['file_path']);
                $aid = (int)$a['id'];
                $fullUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $path;
              ?>
              <div class="col-md-6 col-lg-4">
                <div class="card h-100">
                  <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                      <div class="me-2 text-truncate" title="<?php echo $name; ?>">
                        <i class="far fa-file"></i> <?php echo $name; ?>
                      </div>
                      <small class="text-muted"><?php echo $a['file_size'] ? number_format($a['file_size']/1024,1).' KB' : ''; ?></small>
                    </div>
                    <?php if ($isImage): ?>
                      <div class="border rounded mb-2 p-1">
                        <img src="<?php echo $path; ?>" alt="" style="max-height:180px; width:100%; object-fit:contain;">
                      </div>
                      <div class="d-flex gap-2">
                        <a class="btn btn-sm btn-outline-primary" href="<?php echo $path; ?>" target="_blank"><i class="fas fa-external-link-alt"></i> নতুন ট্যাবে</a>
                      </div>
                    <?php elseif ($isPdf): ?>
                      <div id="pv-<?php echo $aid; ?>" class="border rounded mb-2 p-1" style="display:none;">
                        <object data="<?php echo $path; ?>" type="application/pdf" style="width:100%; height:60vh;">
                          <p>আপনার ব্রাউজারে PDF প্রিভিউ সমর্থিত নয়। <a href="<?php echo $path; ?>" target="_blank">নতুন ট্যাবে খুলুন</a>.</p>
                        </object>
                      </div>
                      <div class="d-flex gap-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="togglePreview('pv-<?php echo $aid; ?>')"><i class="far fa-eye"></i> প্রিভিউ</button>
                        <a class="btn btn-sm btn-outline-primary" href="<?php echo $path; ?>" target="_blank"><i class="fas fa-external-link-alt"></i> নতুন ট্যাবে</a>
                      </div>
                    <?php elseif ($isWord): ?>
                      <div class="text-center py-3">
                        <i class="fas fa-file-word" style="font-size: 4rem; color: #2b579a;"></i>
                        <p class="small text-muted mt-2 mb-2">Word ডকুমেন্ট</p>
                      </div>
                      <div class="alert alert-info small mb-2">
                        <i class="fas fa-info-circle"></i> ডাউনলোড করে Microsoft Word, LibreOffice বা Google Docs এ খুলুন।
                      </div>
                      <div class="d-grid">
                        <a class="btn btn-primary" href="<?php echo $path; ?>" download>
                          <i class="fas fa-download"></i> ডাউনলোড করুন
                        </a>
                      </div>
                    <?php else: ?>
                      <div class="d-flex gap-2">
                        <a class="btn btn-sm btn-outline-primary" href="<?php echo $path; ?>" download>
                          <i class="fas fa-download"></i> ডাউনলোড
                        </a>
                      </div>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>

        <div class="mt-3">
          <a class="btn btn-outline-primary" href="index.php#notices"><i class="fas fa-arrow-left"></i> ফিরে যান</a>
        </div>
      </div>
    </div>
  </div>
  <script>
    function togglePreview(id){
      const el = document.getElementById(id);
      if (!el) return;
      el.style.display = (el.style.display === 'none' || el.style.display === '') ? 'block' : 'none';
      if (el.style.display === 'block') {
        el.scrollIntoView({behavior:'smooth', block:'center'});
      }
    }
  </script>
</body>
</html>
