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

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

// Ensure table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS exam_committee_members (
  id INT AUTO_INCREMENT PRIMARY KEY,
  exam_id INT DEFAULT NULL,
  session VARCHAR(20) DEFAULT NULL,
  name VARCHAR(150) NOT NULL,
  designation VARCHAR(150) DEFAULT NULL,
  role VARCHAR(50) DEFAULT NULL, -- আহ্বায়ক / সদস্য
  phone VARCHAR(50) DEFAULT NULL,
  email VARCHAR(120) DEFAULT NULL,
  order_no INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (exam_id) REFERENCES exams(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

// Add member
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_member'])) {
    $name = trim($_POST['name'] ?? '');
    $designation = trim($_POST['designation'] ?? '');
    $role = trim($_POST['role'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $exam_id = !empty($_POST['exam_id']) ? (int)$_POST['exam_id'] : null;
    $sessionSel = trim($_POST['session'] ?? '');

    if ($name === '') {
        $error = 'নাম দিতে হবে';
    } else {
        try {
            $maxOrder = (int)$pdo->query('SELECT COALESCE(MAX(order_no), 0) FROM exam_committee_members')->fetchColumn();
            $stmt = $pdo->prepare('INSERT INTO exam_committee_members (exam_id, session, name, designation, role, phone, email, order_no) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([$exam_id, $sessionSel ?: null, $name, $designation, $role, $phone, $email, $maxOrder + 1]);
            $success = 'সদস্য যোগ হয়েছে';
        } catch (Exception $e) {
            $error = 'সংরক্ষণে সমস্যা: ' . $e->getMessage();
        }
    }
}

// Add all teachers as committee members
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_all_teachers'])) {
    try {
        // Get all active teachers
        $stmt = $pdo->query("SELECT first_name, last_name, designation, phone, email FROM teachers WHERE status = 'active' ORDER BY first_name, last_name");
        $teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($teachers)) {
            $error = 'কোনো সক্রিয় শিক্ষক খুঁজে পাওয়া যায়নি';
        } else {
            // Get current max order number
            $maxOrder = (int)$pdo->query('SELECT COALESCE(MAX(order_no), 0) FROM exam_committee_members')->fetchColumn();
            
            // Begin transaction
            $pdo->beginTransaction();
            
            // Prepare insert statement
            $insertStmt = $pdo->prepare('INSERT INTO exam_committee_members (name, designation, role, phone, email, order_no) VALUES (?, ?, ?, ?, ?, ?)');
            
            // Insert each teacher
            foreach ($teachers as $index => $teacher) {
                $name = trim($teacher['first_name'] . ' ' . $teacher['last_name']);
                $designation = $teacher['designation'] ?? 'শিক্ষক';
                $role = 'সদস্য'; // Default role
                $phone = $teacher['phone'] ?? '';
                $email = $teacher['email'] ?? '';
                $orderNo = $maxOrder + $index + 1;
                
                $insertStmt->execute([$name, $designation, $role, $phone, $email, $orderNo]);
            }
            
            // Commit transaction
            $pdo->commit();
            $success = 'সব শিক্ষক কমিটিতে যোগ হয়েছেন (' . count($teachers) . ' জন)';
        }
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = 'শিক্ষকদের যোগ করতে সমস্যা: ' . $e->getMessage();
    }
}

// Update member
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_member'])) {
    $id = (int)($_POST['edit_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $designation = trim($_POST['designation'] ?? '');
    $role = trim($_POST['role'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $exam_id = !empty($_POST['exam_id']) ? (int)$_POST['exam_id'] : null;
    $sessionSel = trim($_POST['session'] ?? '');

    if ($id <= 0 || $name === '') {
        $error = 'অবৈধ ডাটা';
    } else {
        try {
            $stmt = $pdo->prepare('UPDATE exam_committee_members SET exam_id = ?, session = ?, name = ?, designation = ?, role = ?, phone = ?, email = ? WHERE id = ?');
            $stmt->execute([$exam_id, ($sessionSel !== '' ? $sessionSel : null), $name, $designation, $role, $phone, $email, $id]);
            $success = 'আপডেট সম্পন্ন হয়েছে';
        } catch (Exception $e) {
            $error = 'আপডেটে সমস্যা: ' . $e->getMessage();
        }
    }
}

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

// Save order
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_order'])) {
    $orders = $_POST['order'] ?? [];
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare('UPDATE exam_committee_members SET order_no = ? WHERE id = ?');
        foreach ($orders as $id => $ord) {
            $id = (int)$id; $ord = (int)$ord;
            $stmt->execute([$ord, $id]);
        }
        $pdo->commit();
        $success = 'অর্ডার সংরক্ষিত হয়েছে';
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = 'অর্ডার সংরক্ষণে সমস্যা: ' . $e->getMessage();
    }
}

// Fetch members
// Fetch filter params
$filter_exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;
$filter_session = trim($_GET['session'] ?? '');

$where = [];
$params = [];
if ($filter_exam_id) { $where[] = 'exam_id = ?'; $params[] = $filter_exam_id; }
if ($filter_session !== '') { $where[] = 'session = ?'; $params[] = $filter_session; }
$sql = 'SELECT * FROM exam_committee_members';
if ($where) { $sql .= ' WHERE ' . implode(' AND ', $where); }
$sql .= ' ORDER BY order_no ASC, id ASC';

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Exams for dropdown
$examsList = $pdo->query("SELECT id, name, session FROM exams ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

// Get teacher count for information
$teacherCount = (int)$pdo->query("SELECT COUNT(*) FROM teachers WHERE status = 'active'")->fetchColumn();

?>
<!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="../assets/css/style.css" rel="stylesheet">
</head>
<body>
  <!-- Navigation -->
  <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">
    <div class="row">
      <div class="col-md-12">
        <h3><i class="fas fa-users-cog"></i> পরীক্ষা কমিটি</h3>
      </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-4">
        <div class="card">
          <div class="card-header"><strong>নতুন সদস্য যোগ করুন</strong></div>
          <div class="card-body">
            <form method="post">
              <div class="mb-2">
                <label class="form-label">পরীক্ষা (ঐচ্ছিক)</label>
                <select name="exam_id" class="form-select">
                  <option value="">-- Select Exam --</option>
                  <?php foreach ($examsList as $e): ?>
                    <option value="<?php echo (int)$e['id']; ?>"><?php echo htmlspecialchars($e['name'] . ($e['session']? ' - '.$e['session'] : '')); ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="mb-2">
                <label class="form-label">সেশন (ঐচ্ছিক)</label>
                <input type="text" name="session" class="form-control" placeholder="উদাহরণ: 2024">
              </div>
              <div class="mb-2">
                <label class="form-label">নাম</label>
                <input type="text" name="name" class="form-control" required>
              </div>
              <div class="mb-2">
                <label class="form-label">পদবি</label>
                <input type="text" name="designation" class="form-control" placeholder="উদাহরণ: সহকারী শিক্ষক">
              </div>
              <div class="mb-2">
                <label class="form-label">ভূমিকা</label>
                <select name="role" class="form-select">
                  <option value="">নির্বাচন করুন</option>
                  <option value="আহ্বায়ক">আহ্বায়ক</option>
                  <option value="সদস্য">সদস্য</option>
                </select>
              </div>
              <div class="row">
                <div class="col-6 mb-2">
                  <label class="form-label">মোবাইল</label>
                  <input type="text" name="phone" class="form-control">
                </div>
                <div class="col-6 mb-2">
                  <label class="form-label">ইমেইল</label>
                  <input type="email" name="email" class="form-control">
                </div>
              </div>
              <button class="btn btn-primary" name="add_member"><i class="fas fa-plus"></i> যোগ করুন</button>
              <button class="btn btn-success" name="add_all_teachers" onclick="return confirm('আপনি কি সব সক্রিয় শিক্ষকদের কমিটিতে যোগ করতে চান?')"><i class="fas fa-user-plus"></i> সব শিক্ষক যোগ করুন</button>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="card">
          <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
            <strong>সদস্য তালিকা</strong>
            <div>
              <span class="badge bg-info">সক্রিয় শিক্ষক: <?php echo $teacherCount; ?> জন</span>
            </div>
            <form method="get" class="d-flex align-items-center gap-2">
              <select name="exam_id" class="form-select form-select-sm" style="min-width: 240px;">
                <option value="0">সব পরীক্ষা</option>
                <?php foreach ($examsList as $e): ?>
                  <option value="<?php echo (int)$e['id']; ?>" <?php echo ($filter_exam_id == (int)$e['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($e['name'] . ($e['session']? ' - '.$e['session'] : '')); ?></option>
                <?php endforeach; ?>
              </select>
              <input type="text" name="session" class="form-control form-control-sm" placeholder="সেশন" value="<?php echo htmlspecialchars($filter_session); ?>" style="max-width: 120px;">
              <button class="btn btn-sm btn-outline-primary">ফিল্টার</button>
              <a href="exam_committee.php" class="btn btn-sm btn-outline-secondary">রিসেট</a>
            </form>
            <form method="post" class="m-0 p-0">
              <button class="btn btn-sm btn-success" name="save_order"><i class="fas fa-save"></i> অর্ডার সংরক্ষণ</button>
            </form>
          </div>
          <div class="card-body p-0">
            <form method="post">
              <div class="table-responsive">
                <table class="table table-striped table-hover align-middle mb-0">
                  <thead class="table-light">
                    <tr>
                      <th style="width: 70px;">অর্ডার</th>
                      <th>নাম</th>
                      <th>ভূমিকা</th>
                      <th>পদবি</th>
                      <th>মোবাইল</th>
                      <th>ইমেইল</th>
                      <th style="width: 120px;">অ্যাকশন</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (empty($members)): ?>
                      <tr><td colspan="7" class="text-center text-muted">কোনো সদস্য যোগ করা হয়নি</td></tr>
                    <?php else: foreach ($members as $m): ?>
                      <tr>
                        <td>
                          <input type="number" class="form-control form-control-sm" name="order[<?php echo (int)$m['id']; ?>]" value="<?php echo (int)$m['order_no']; ?>">
                        </td>
                        <td>
                          <div class="fw-semibold"><?php echo htmlspecialchars($m['name']); ?></div>
                          <div class="small text-muted">Exam: <?php echo htmlspecialchars($m['exam_id'] ?? '-'); ?> | Session: <?php echo htmlspecialchars($m['session'] ?? '-'); ?></div>
                        </td>
                        <td><?php echo htmlspecialchars($m['role']); ?></td>
                        <td><?php echo htmlspecialchars($m['designation']); ?></td>
                        <td><?php echo htmlspecialchars($m['phone']); ?></td>
                        <td><?php echo htmlspecialchars($m['email']); ?></td>
                        <td class="d-flex gap-1">
                          <button type="button" class="btn btn-sm btn-outline-primary" 
                                  onclick='openEdit(<?php echo json_encode($m, 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)$m['id']; ?>">
                            <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                          </form>
                        </td>
                      </tr>
                    <?php endforeach; endif; ?>
                  </tbody>
                </table>
              </div>
              <div class="p-2 text-end">
                <button class="btn btn-success" name="save_order"><i class="fas fa-save"></i> অর্ডার সংরক্ষণ</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Edit Modal -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">সদস্য সম্পাদনা</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="post">
          <div class="modal-body">
            <input type="hidden" name="edit_id" id="edit_id">
            <div class="mb-2">
              <label class="form-label">পরীক্ষা (ঐচ্ছিক)</label>
              <select name="exam_id" id="edit_exam_id" class="form-select">
                <option value="">-- Select Exam --</option>
                <?php foreach ($examsList as $e): ?>
                  <option value="<?php echo (int)$e['id']; ?>"><?php echo htmlspecialchars($e['name'] . ($e['session']? ' - '.$e['session'] : '')); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-2">
              <label class="form-label">সেশন (ঐচ্ছিক)</label>
              <input type="text" name="session" id="edit_session" class="form-control">
            </div>
            <div class="mb-2">
              <label class="form-label">নাম</label>
              <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>
            <div class="mb-2">
              <label class="form-label">পদবি</label>
              <input type="text" name="designation" id="edit_designation" class="form-control">
            </div>
            <div class="mb-2">
              <label class="form-label">ভূমিকা</label>
              <select name="role" id="edit_role" class="form-select">
                <option value="">নির্বাচন করুন</option>
                <option value="আহ্বায়ক">আহ্বায়ক</option>
                <option value="সদস্য">সদস্য</option>
              </select>
            </div>
            <div class="row">
              <div class="col-6 mb-2">
                <label class="form-label">মোবাইল</label>
                <input type="text" name="phone" id="edit_phone" class="form-control">
              </div>
              <div class="col-6 mb-2">
                <label class="form-label">ইমেইল</label>
                <input type="email" name="email" id="edit_email" class="form-control">
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
            <button class="btn btn-primary" name="update_member"><i class="fas fa-save"></i> সংরক্ষণ</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    let editModal;
    document.addEventListener('DOMContentLoaded', function() {
      editModal = new bootstrap.Modal(document.getElementById('editModal'));
    });
    function openEdit(data) {
      document.getElementById('edit_id').value = data.id || '';
      document.getElementById('edit_name').value = data.name || '';
      document.getElementById('edit_designation').value = data.designation || '';
      document.getElementById('edit_role').value = data.role || '';
      document.getElementById('edit_phone').value = data.phone || '';
      document.getElementById('edit_email').value = data.email || '';
      document.getElementById('edit_session').value = data.session || '';
      document.getElementById('edit_exam_id').value = data.exam_id || '';
      editModal.show();
    }
  </script>
</body>
</html>