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

// Admin only
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

// Ensure academic_calendar table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS academic_calendar (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    description TEXT NULL,
    event_date DATE NOT NULL,
    end_date DATE NULL,
    event_type ENUM('holiday', 'exam', 'event', 'other') DEFAULT 'other',
    is_recurring BOOLEAN DEFAULT FALSE,
    recurring_pattern VARCHAR(50) NULL,
    status ENUM('active','inactive') DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

// Create/Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_calendar_event'])) {
    $id = (int)($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $event_date = trim($_POST['event_date'] ?? '');
    $end_date = trim($_POST['end_date'] ?? '');
    $event_type = $_POST['event_type'] ?? 'other';
    $is_recurring = isset($_POST['is_recurring']) ? 1 : 0;
    $recurring_pattern = trim($_POST['recurring_pattern'] ?? '');
    $status = $_POST['status'] ?? 'active';

    if ($title === '' || $event_date === '') {
        $error = 'শিরোনাম ও তারিখ প্রয়োজন';
    } elseif ($end_date !== '' && $end_date < $event_date) {
        $error = 'শেষ তারিখ শুরুর তারিখের পরে হতে হবে';
    } else {
        try {
            if ($id > 0) {
                $stmt = $pdo->prepare('UPDATE academic_calendar SET title=?, description=?, event_date=?, end_date=?, event_type=?, is_recurring=?, recurring_pattern=?, status=? WHERE id=?');
                $stmt->execute([$title, $description, $event_date, $end_date ?: null, $event_type, $is_recurring, $recurring_pattern, $status, $id]);
                $success = 'একাডেমিক ইভেন্ট আপডেট হয়েছে';
            } else {
                $stmt = $pdo->prepare('INSERT INTO academic_calendar (title, description, event_date, end_date, event_type, is_recurring, recurring_pattern, status) VALUES (?,?,?,?,?,?,?,?)');
                $stmt->execute([$title, $description, $event_date, $end_date ?: null, $event_type, $is_recurring, $recurring_pattern, $status]);
                $success = 'একাডেমিক ইভেন্ট যোগ হয়েছে';
            }
        } catch (Exception $e) {
            $error = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    try {
        $stmt = $pdo->prepare('DELETE FROM academic_calendar WHERE id = ?');
        $stmt->execute([$id]);
        $success = 'একাডেমিক ইভেন্ট মুছে ফেলা হয়েছে';
    } catch (Exception $e) {
        $error = 'মুছতে সমস্যা: ' . $e->getMessage();
    }
}

// Fetch list
$stmt = $pdo->query("SELECT * FROM academic_calendar ORDER BY event_date DESC, id DESC");
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get upcoming holidays for dashboard display
$stmt = $pdo->prepare("SELECT * FROM academic_calendar WHERE event_type='holiday' AND event_date >= CURDATE() AND status='active' ORDER BY event_date ASC LIMIT 5");
$stmt->execute();
$upcoming_holidays = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <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="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;
    }
  </style>
  <style>
    .event-type-holiday { border-left: 4px solid #dc3545; }
    .event-type-exam { border-left: 4px solid #fd7e14; }
    .event-type-event { border-left: 4px solid #0d6efd; }
    .event-type-other { border-left: 4px solid #6c757d; }
    .recurring-badge { background-color: #ffc107; color: #000; }
  </style>
</head>
<body>
    <header class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <span class="navbar-brand">একাডেমিক ক্যালেন্ডার</span>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php"><i class="fas fa-home"></i> হোম</a>
                <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
            </div>
        </div>
    </header>

  <div class="container-fluid mt-4">
    <div class="row">
      <div class="col-12">
        <h1><i class="fas fa-calendar-alt"></i> একাডেমিক ক্যালেন্ডার</h1>
        <p class="text-muted">বিভিন্ন ছুটি, পরীক্ষা এবং গুরুত্বপূর্ণ ইভেন্ট ম্যানেজ করুন</p>
      </div>
    </div>

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

    <div class="row g-3">
      <div class="col-lg-6">
        <div class="card">
          <div class="card-header"><strong>নতুন/এডিট ইভেন্ট</strong></div>
          <div class="card-body">
            <form method="post">
              <input type="hidden" name="id" id="id">
              <div class="mb-2">
                <label class="form-label">শিরোনাম *</label>
                <input class="form-control" name="title" id="title" required>
              </div>
              <div class="mb-2">
                <label class="form-label">বিবরণ</label>
                <textarea class="form-control" name="description" id="description" rows="2"></textarea>
              </div>
              <div class="row">
                <div class="col-md-6 mb-2">
                  <label class="form-label">শুরুর তারিখ *</label>
                  <input type="date" class="form-control" name="event_date" id="event_date" required>
                </div>
                <div class="col-md-6 mb-2">
                  <label class="form-label">শেষ তারিখ</label>
                  <input type="date" class="form-control" name="end_date" id="end_date">
                </div>
              </div>
              <div class="row">
                <div class="col-md-6 mb-2">
                  <label class="form-label">ধরন</label>
                  <select class="form-select" name="event_type" id="event_type">
                    <option value="holiday">ছুটি</option>
                    <option value="exam">পরীক্ষা</option>
                    <option value="event">ইভেন্ট</option>
                    <option value="other">অন্যান্য</option>
                  </select>
                </div>
                <div class="col-md-6 mb-2">
                  <label class="form-label">স্ট্যাটাস</label>
                  <select class="form-select" name="status" id="status">
                    <option value="active">সক্রিয়</option>
                    <option value="inactive">নিষ্ক্রিয়</option>
                  </select>
                </div>
              </div>
              <div class="mb-2">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="is_recurring" id="is_recurring">
                  <label class="form-check-label" for="is_recurring">পুনরাবৃত্তি হয়</label>
                </div>
              </div>
              <div class="mb-2" id="recurring_field" style="display:none;">
                <label class="form-label">পুনরাবৃত্তি প্যাটার্ন</label>
                <input type="text" class="form-control" name="recurring_pattern" id="recurring_pattern" placeholder="যেমন: প্রতি বছর, প্রতি মাসে">
              </div>
              <button class="btn btn-primary" name="save_calendar_event"><i class="fas fa-save"></i> সংরক্ষণ</button>
              <button class="btn btn-secondary" type="button" onclick="resetForm()"><i class="fas fa-eraser"></i> রিসেট</button>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-6">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>একাডেমিক ইভেন্ট তালিকা</strong>
            <span class="badge bg-primary"><?php echo count($items); ?> টি ইভেন্ট</span>
          </div>
          <div class="card-body table-responsive p-0">
            <table class="table table-striped align-middle mb-0">
              <thead class="table-light">
                <tr>
                  <th>তারিখ</th>
                  <th>শিরোনাম</th>
                  <th>ধরন</th>
                  <th>পুনরাবৃত্তি</th>
                  <th>অবস্থা</th>
                  <th style="width:140px">কার্যক্রম</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($items)): ?>
                  <tr><td colspan="6" class="text-center text-muted">কোন ইভেন্ট নেই</td></tr>
                <?php else: foreach ($items as $it): ?>
                  <tr class="event-type-<?php echo $it['event_type']; ?>">
                    <td>
                      <?php 
                      echo date('d/m/Y', strtotime($it['event_date']));
                      if (!empty($it['end_date']) && $it['end_date'] != $it['event_date']) {
                        echo ' - ' . date('d/m/Y', strtotime($it['end_date']));
                      }
                      ?>
                    </td>
                    <td>
                      <div class="fw-semibold"><?php echo htmlspecialchars($it['title']); ?></div>
                      <?php if (!empty($it['description'])): ?>
                        <small class="text-muted"><?php echo htmlspecialchars(mb_strimwidth(strip_tags($it['description']), 0, 50, '...', 'UTF-8')); ?></small>
                      <?php endif; ?>
                    </td>
                    <td>
                      <?php 
                      $type_labels = [
                        'holiday' => '<span class="badge bg-danger">ছুটি</span>',
                        'exam' => '<span class="badge bg-warning">পরীক্ষা</span>',
                        'event' => '<span class="badge bg-primary">ইভেন্ট</span>',
                        'other' => '<span class="badge bg-secondary">অন্যান্য</span>'
                      ];
                      echo $type_labels[$it['event_type']] ?? $type_labels['other'];
                      ?>
                    </td>
                    <td>
                      <?php if ($it['is_recurring']): ?>
                        <span class="badge recurring-badge">হ্যাঁ</span>
                      <?php else: ?>
                        <span class="badge bg-light text-dark">না</span>
                      <?php endif; ?>
                    </td>
                    <td>
                      <?php if ($it['status'] === 'active'): ?>
                        <span class="badge bg-success">সক্রিয়</span>
                      <?php else: ?>
                        <span class="badge bg-secondary">নিষ্ক্রিয়</span>
                      <?php endif; ?>
                    </td>
                    <td>
                      <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick='editRow(<?php echo json_encode($it, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT); ?>)'><i class="fas fa-edit"></i></button>
                        <form method="post" onsubmit="return confirm('মুছতে নিশ্চিত?');" style="display:inline;">
                          <input type="hidden" name="delete_id" value="<?php echo (int)$it['id']; ?>">
                          <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
                        </form>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Upcoming Holidays Dashboard -->
    <div class="row mt-4">
      <div class="col-12">
        <div class="card">
          <div class="card-header"><strong>আসন্ন ছুটি</strong></div>
          <div class="card-body">
            <?php if (empty($upcoming_holidays)): ?>
              <div class="text-center text-muted">কোন আসন্ন ছুটি নেই</div>
            <?php else: ?>
              <ul class="list-group">
                <?php foreach ($upcoming_holidays as $holiday): ?>
                  <li class="list-group-item">
                    <div class="d-flex justify-content-between">
                      <div>
                        <strong><?php echo htmlspecialchars($holiday['title']); ?></strong>
                        <?php if ($holiday['is_recurring']): ?>
                          <span class="badge recurring-badge">পুনরাবৃত্তি</span>
                        <?php endif; ?>
                      </div>
                      <small class="text-muted">
                        <?php 
                        echo date('d/m/Y', strtotime($holiday['event_date']));
                        if (!empty($holiday['end_date']) && $holiday['end_date'] != $holiday['event_date']) {
                          echo ' - ' . date('d/m/Y', strtotime($holiday['end_date']));
                        }
                        ?>
                      </small>
                    </div>
                    <?php if (!empty($holiday['description'])): ?>
                      <small class="text-muted"><?php echo htmlspecialchars(mb_strimwidth($holiday['description'], 0, 50, '...', 'UTF-8')); ?></small>
                    <?php endif; ?>
                  </li>
                <?php endforeach; ?>
              </ul>
            <?php endif; ?>
          </div>
        </div>
      </div>
  </div>

  <script>
  function editRow(it){
    document.getElementById('id').value = it.id;
    document.getElementById('title').value = it.title || '';
    document.getElementById('description').value = it.description || '';
    document.getElementById('event_date').value = it.event_date || '';
    document.getElementById('end_date').value = it.end_date || '';
    document.getElementById('event_type').value = it.event_type || 'other';
    document.getElementById('status').value = it.status || 'active';
    
    if (it.is_recurring == 1) {
      document.getElementById('is_recurring').checked = true;
      document.getElementById('recurring_field').style.display = 'block';
    } else {
      document.getElementById('is_recurring').checked = false;
      document.getElementById('recurring_field').style.display = 'none';
    }
    
    document.getElementById('recurring_pattern').value = it.recurring_pattern || '';
    
    window.scrollTo({top:0, behavior:'smooth'});
  }
  
  function resetForm(){
    document.getElementById('id').value='';
    document.getElementById('title').value='';
    document.getElementById('description').value='';
    document.getElementById('event_date').value='';
    document.getElementById('end_date').value='';
    document.getElementById('event_type').value='other';
    document.getElementById('status').value='active';
    document.getElementById('is_recurring').checked = false;
    document.getElementById('recurring_field').style.display = 'none';
    document.getElementById('recurring_pattern').value = '';
  }
  
  // Toggle recurring field visibility
  document.getElementById('is_recurring').addEventListener('change', function() {
    document.getElementById('recurring_field').style.display = this.checked ? 'block' : 'none';
  });
  </script>
  
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>