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

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

// Create table if not exists
$pdo->exec("CREATE TABLE IF NOT EXISTS academic_sessions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  session_name VARCHAR(100) NOT NULL,              -- e.g., 2024-2025
  start_date DATE NULL,
  end_date DATE NULL,
  is_current TINYINT(1) DEFAULT 0,
  status ENUM('active','inactive') DEFAULT 'active',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uniq_name (session_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

function setCurrentSession(PDO $pdo, int $sessionId) {
    // set all to 0 then selected to 1
    $pdo->beginTransaction();
    $pdo->exec("UPDATE academic_sessions SET is_current = 0");
    $stmt = $pdo->prepare("UPDATE academic_sessions SET is_current = 1 WHERE id = ?");
    $stmt->execute([$sessionId]);
    // ensure settings table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        id INT PRIMARY KEY AUTO_INCREMENT,
        setting_key VARCHAR(100) UNIQUE,
        setting_value TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    // update academic_year in settings with session name
    $name = $pdo->prepare("SELECT session_name FROM academic_sessions WHERE id = ?");
    $name->execute([$sessionId]);
    $val = (string)($name->fetchColumn() ?: '');
    $st = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('academic_year', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $st->execute([$val]);
    $pdo->commit();
}

// Add / Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_session'])) {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['session_name'] ?? '');
    $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    $status = $_POST['status'] ?? 'active';
    $make_current = isset($_POST['is_current']);

    if ($name === '') {
        $error = 'সেশন নাম প্রয়োজন';
    } else {
        try {
            if ($id > 0) {
                $stmt = $pdo->prepare('UPDATE academic_sessions SET session_name=?, start_date=?, end_date=?, status=? WHERE id=?');
                $stmt->execute([$name, $start_date, $end_date, $status, $id]);
                if ($make_current) { setCurrentSession($pdo, $id); }
                $success = 'সেশন আপডেট হয়েছে';
            } else {
                $stmt = $pdo->prepare('INSERT INTO academic_sessions (session_name, start_date, end_date, status) VALUES (?,?,?,?)');
                $stmt->execute([$name, $start_date, $end_date, $status]);
                $newId = (int)$pdo->lastInsertId();
                if ($make_current && $newId) { setCurrentSession($pdo, $newId); }
                $success = 'সেশন যোগ হয়েছে';
            }
        } catch (Exception $e) {
            $error = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Set current (quick action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_current'])) {
    $sid = (int)$_POST['set_current'];
    try { setCurrentSession($pdo, $sid); $success = 'বর্তমান সেশন সেট হয়েছে'; } catch (Exception $e) { $error = 'ত্রুটি: '.$e->getMessage(); }
}

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

// Fetch
$sessions = $pdo->query('SELECT * FROM academic_sessions ORDER BY is_current DESC, start_date DESC, id DESC')->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>
    /* Apply Hind Siliguri for Bangla rendering across the page */
    body { font-family: 'Hind Siliguri', 'Noto Sans Bengali', Arial, sans-serif; }
  </style>
</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">
              <input type="hidden" name="id" id="id">
              <div class="mb-2">
                <label class="form-label">সেশন নাম</label>
                <input class="form-control" name="session_name" id="session_name" placeholder="যেমন: ২০২৪-২০২৫" required>
              </div>
              <div class="row">
                <div class="col-6 mb-2">
                  <label class="form-label">শুরুর তারিখ</label>
                  <input type="date" class="form-control" name="start_date" id="start_date">
                </div>
                <div class="col-6 mb-2">
                  <label class="form-label">শেষের তারিখ</label>
                  <input type="date" class="form-control" name="end_date" id="end_date">
                </div>
              </div>
              <div class="mb-2">
                <label class="form-label">স্ট্যাটাস</label>
                <select class="form-select" name="status" id="status">
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </select>
              </div>
              <div class="form-check mb-3">
                <input class="form-check-input" type="checkbox" name="is_current" id="is_current">
                <label class="form-check-label" for="is_current">বর্তমান সেশন হিসেবে সেট করুন</label>
              </div>
              <button class="btn btn-primary" name="save_session"><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 style="width:180px">অ্যাকশন</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($sessions)): ?>
                  <tr><td colspan="5" class="text-center text-muted">কোন সেশন নেই</td></tr>
                <?php else: foreach ($sessions as $s): ?>
                  <tr>
                    <td><?php if (!empty($s['is_current'])): ?><span class="badge bg-success">Current</span><?php endif; ?></td>
                    <td class="fw-semibold"><?php echo htmlspecialchars($s['session_name'] ?? ''); ?></td>
                    <td>
                      <small class="text-muted">
                        <?php echo !empty($s['start_date']) ? date('d-m-Y', strtotime($s['start_date'])) : '-'; ?>
                        —
                        <?php echo !empty($s['end_date']) ? date('d-m-Y', strtotime($s['end_date'])) : '-'; ?>
                      </small>
                    </td>
                    <td><span class="badge bg-<?php echo (($s['status'] ?? 'active')==='active') ? 'primary' : 'secondary'; ?>"><?php echo htmlspecialchars($s['status'] ?? 'active'); ?></span></td>
                    <td>
                      <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick='editRow(<?php echo json_encode($s, 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)($s['id'] ?? 0); ?>">
                          <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php if (empty($s['is_current'])): ?>
                        <form method="post">
                          <input type="hidden" name="set_current" value="<?php echo (int)($s['id'] ?? 0); ?>">
                          <button class="btn btn-outline-success"><i class="fas fa-check"></i> Current</button>
                        </form>
                        <?php endif; ?>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    function editRow(s){
      document.getElementById('id').value = s.id;
      document.getElementById('session_name').value = s.session_name || '';
      document.getElementById('start_date').value = s.start_date || '';
      document.getElementById('end_date').value = s.end_date || '';
      document.getElementById('status').value = s.status || 'active';
      document.getElementById('is_current').checked = s.is_current == 1;
      window.scrollTo({top:0, behavior:'smooth'});
    }
    function resetForm(){
      document.getElementById('id').value = '';
      document.getElementById('session_name').value = '';
      document.getElementById('start_date').value = '';
      document.getElementById('end_date').value = '';
      document.getElementById('status').value = 'active';
      document.getElementById('is_current').checked = false;
    }
  </script>
</body>
</html>