<?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 events table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS events (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    description TEXT NULL,
    event_date DATE NOT NULL,
    location VARCHAR(200) NULL,
    cover_image VARCHAR(255) NULL,
    status ENUM('upcoming','past','cancelled') DEFAULT 'upcoming',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

function saveCover(?array $file): ?string {
    if (!$file || empty($file['name'])) return null;
    if (!is_uploaded_file($file['tmp_name'])) return null;
    $allowed = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/jpg'=>'jpg'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    if (!isset($allowed[$mime])) return null;
    $ext = $allowed[$mime];
    $dir = dirname(__DIR__) . '/uploads/events';
    if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
    $name = 'ev_' . uniqid() . '.' . $ext;
    $dest = $dir . '/' . $name;
    if (move_uploaded_file($file['tmp_name'], $dest)) {
        return 'uploads/events/' . $name;
    }
    return null;
}

// Create/Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_event'])) {
    $id = (int)($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $event_date = trim($_POST['event_date'] ?? '');
    $location = trim($_POST['location'] ?? '');
    $status = $_POST['status'] ?? 'upcoming';

    if ($title === '' || $event_date === '') {
        $error = 'শিরোনাম ও তারিখ প্রয়োজন';
    } else {
        try {
            if ($id > 0) {
                $row = $pdo->prepare('SELECT cover_image FROM events WHERE id=?');
                $row->execute([$id]);
                $cur = $row->fetch(PDO::FETCH_ASSOC) ?: [];
                $newCover = saveCover($_FILES['cover'] ?? null);
                if ($newCover) {
                    if (!empty($cur['cover_image'])) {
                        $old = dirname(__DIR__) . '/' . $cur['cover_image'];
                        if (is_file($old)) { @unlink($old); }
                    }
                    $stmt = $pdo->prepare('UPDATE events SET title=?, description=?, event_date=?, location=?, status=?, cover_image=? WHERE id=?');
                    $stmt->execute([$title, $description, $event_date, $location, $status, $newCover, $id]);
                } else {
                    $stmt = $pdo->prepare('UPDATE events SET title=?, description=?, event_date=?, location=?, status=? WHERE id=?');
                    $stmt->execute([$title, $description, $event_date, $location, $status, $id]);
                }
                $success = 'ইভেন্ট আপডেট হয়েছে';
            } else {
                $cover = saveCover($_FILES['cover'] ?? null);
                $stmt = $pdo->prepare('INSERT INTO events (title, description, event_date, location, status, cover_image) VALUES (?,?,?,?,?,?)');
                $stmt->execute([$title, $description, $event_date, $location, $status, $cover]);
                $success = 'ইভেন্ট যোগ হয়েছে';
            }
        } catch (Exception $e) {
            $error = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    try {
        $row = $pdo->prepare('SELECT cover_image FROM events WHERE id=?');
        $row->execute([$id]);
        $cur = $row->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($cur['cover_image'])) {
            $old = dirname(__DIR__) . '/' . $cur['cover_image'];
            if (is_file($old)) { @unlink($old); }
        }
        $stmt = $pdo->prepare('DELETE FROM events WHERE id = ?');
        $stmt->execute([$id]);
        $success = 'ইভেন্ট মুছে ফেলা হয়েছে';
    } catch (Exception $e) {
        $error = 'মুছতে সমস্যা: ' . $e->getMessage();
    }
}

// Fetch list
$stmt = $pdo->query("SELECT * FROM events ORDER BY event_date DESC, id DESC");
$items = $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">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
      <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
      <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="settings.php"><i class="fas fa-cogs"></i> সেটিংস</a>
        <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
      </div>
    </div>
  </nav>

  <div class="container-fluid mt-4">
    <?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-4">
        <div class="card">
          <div class="card-header"><strong>নতুন/এডিট ইভেন্ট</strong></div>
          <div class="card-body">
            <form method="post" enctype="multipart/form-data">
              <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="3"></textarea>
              </div>
              <div class="row">
                <div class="col-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-6 mb-2">
                  <label class="form-label">স্ট্যাটাস</label>
                  <select class="form-select" name="status" id="status">
                    <option value="upcoming">Upcoming</option>
                    <option value="past">Past</option>
                    <option value="cancelled">Cancelled</option>
                  </select>
                </div>
              </div>
              <div class="mb-2">
                <label class="form-label">স্থান</label>
                <input class="form-control" name="location" id="location">
              </div>
              <div class="mb-3">
                <label class="form-label">কভার ইমেজ (ঐচ্ছিক)</label>
                <input type="file" class="form-control" name="cover" accept="image/*">
              </div>
              <button class="btn btn-primary" name="save_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-8">
        <div class="card">
          <div class="card-header"><strong>ইভেন্ট তালিকা</strong></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>
                    <td><?php echo htmlspecialchars($it['event_date']); ?></td>
                    <td>
                      <div class="fw-semibold"><?php echo htmlspecialchars($it['title']); ?></div>
                      <small class="text-muted"><?php echo htmlspecialchars(mb_strimwidth(strip_tags($it['description'] ?? ''),0,80,'...','UTF-8')); ?></small>
                    </td>
                    <td><?php echo htmlspecialchars($it['location'] ?: ''); ?></td>
                    <td><span class="badge bg-<?php echo $it['status']==='upcoming'?'success':($it['status']==='past'?'secondary':'danger'); ?>"><?php echo htmlspecialchars($it['status']); ?></span></td>
                    <td><?php if (!empty($it['cover_image'])): ?><img src="../<?php echo htmlspecialchars($it['cover_image']); ?>" style="height:40px"><?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('মুছতে নিশ্চিত?');">
                          <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>
  </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('location').value = it.location || '';
    document.getElementById('status').value = it.status || 'upcoming';
    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('location').value='';
    document.getElementById('status').value='upcoming';
  }
  </script>
</body>
</html>