<?php
session_start();

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

require_once '../config/database.php';
require_once '../includes/access_control.php';

// Ensure table exists (with photo column)
$pdo->exec("CREATE TABLE IF NOT EXISTS management_board_members (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(150) NOT NULL,
  designation VARCHAR(150) DEFAULT NULL,
  board_role VARCHAR(100) DEFAULT NULL, -- সভাপতি/সচিব/সদস্য ইত্যাদি
  phone VARCHAR(50) DEFAULT NULL,
  email VARCHAR(120) DEFAULT NULL,
  photo VARCHAR(255) DEFAULT NULL,
  order_no INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Try to add photo column if missing (for older installs)
try {
    $pdo->query("SELECT photo FROM management_board_members LIMIT 1");
} catch (Exception $e) {
    try { $pdo->exec("ALTER TABLE management_board_members ADD COLUMN photo VARCHAR(255) NULL AFTER email"); } catch (Exception $e2) { /* ignore */ }
}

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

function saveUploadedPhoto(?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/jpg' => 'jpg'];
    
    // Check if finfo extension is available
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
    } else {
        // Fallback: use mime_content_type or guess from file extension
        if (function_exists('mime_content_type')) {
            $mime = mime_content_type($file['tmp_name']);
        } else {
            // Guess from file extension as last resort
            $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            if ($extension === 'jpg' || $extension === 'jpeg') {
                $mime = 'image/jpeg';
            } elseif ($extension === 'png') {
                $mime = 'image/png';
            } else {
                return null; // Unsupported extension
            }
        }
    }

    if (!isset($allowed[$mime])) return null;

    $ext = $allowed[$mime];
    $dir = dirname(__DIR__) . '/uploads/management_board';
    if (!is_dir($dir)) {
        if (!@mkdir($dir, 0755, true)) {
            error_log("Could not create upload directory: $dir");
            return null;
        }
    }
    // Ensure directory has proper permissions
    @chmod($dir, 0755);
    $name = 'mb_' . uniqid() . '.' . $ext;
    $dest = $dir . '/' . $name;
    if (move_uploaded_file($file['tmp_name'], $dest)) {
        // return relative path from project root
        return 'uploads/management_board/' . $name;
    }
    return null;
}

// Add member
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_member'])) {
    $name = trim($_POST['name'] ?? '');
    $designation = trim($_POST['designation'] ?? '');
    $board_role = trim($_POST['board_role'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');

    if ($name === '') {
        $error = 'নাম দিতে হবে';
    } else {
        try {
            $photo = saveUploadedPhoto($_FILES['photo'] ?? null);
            $maxOrder = (int)$pdo->query('SELECT COALESCE(MAX(order_no), 0) FROM management_board_members')->fetchColumn();
            $stmt = $pdo->prepare('INSERT INTO management_board_members (name, designation, board_role, phone, email, photo, order_no) VALUES (?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([$name, $designation, $board_role, $phone, $email, $photo, $maxOrder + 1]);
            $success = 'সদস্য যোগ হয়েছে';
        } catch (Exception $e) {
            $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'] ?? '');
    $board_role = trim($_POST['board_role'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');

    if ($id <= 0 || $name === '') {
        $error = 'অবৈধ ডাটা';
    } else {
        try {
            // Get current row for old photo
            $row = $pdo->prepare('SELECT photo FROM management_board_members WHERE id = ?');
            $row->execute([$id]);
            $current = $row->fetch(PDO::FETCH_ASSOC) ?: [];

            $newPhoto = saveUploadedPhoto($_FILES['photo'] ?? null);
            if ($newPhoto) {
                // Optionally delete old photo file
                if (!empty($current['photo'])) {
                    $oldPath = dirname(__DIR__) . '/' . $current['photo'];
                    if (is_file($oldPath) && file_exists($oldPath)) {
                        if (!@unlink($oldPath)) {
                            error_log("Could not delete old photo: $oldPath");
                        }
                    }
                }
                $stmt = $pdo->prepare('UPDATE management_board_members SET name=?, designation=?, board_role=?, phone=?, email=?, photo=? WHERE id=?');
                $stmt->execute([$name, $designation, $board_role, $phone, $email, $newPhoto, $id]);
            } else {
                $stmt = $pdo->prepare('UPDATE management_board_members SET name=?, designation=?, board_role=?, phone=?, email=? WHERE id=?');
                $stmt->execute([$name, $designation, $board_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 {
        // Delete old photo file
        $row = $pdo->prepare('SELECT photo FROM management_board_members WHERE id = ?');
        $row->execute([$id]);
        $current = $row->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($current['photo'])) {
            $oldPath = dirname(__DIR__) . '/' . $current['photo'];
            if (is_file($oldPath) && file_exists($oldPath)) {
                if (!@unlink($oldPath)) {
                    error_log("Could not delete photo during removal: $oldPath");
                }
            }
        }
        $stmt = $pdo->prepare('DELETE FROM management_board_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 management_board_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
$stmt = $pdo->query('SELECT * FROM management_board_members ORDER BY order_no ASC, id ASC');
$members = $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="../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"></i> প্রতিষ্ঠান পরিচালনা পর্ষদ</h3>
      </div>
    </div>

    <?php if ($success): ?><div class="alert alert-success mt-2"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger mt-2"><?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">
              <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>
                <input type="text" name="board_role" class="form-control" placeholder="উদাহরণ: সভাপতি/সচিব/সদস্য">
              </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>
              <div class="mb-3">
                <label class="form-label">ছবি (jpg/png)</label>
                <input type="file" name="photo" accept="image/jpeg,image/png" class="form-control">
              </div>
              <button class="btn btn-primary" name="add_member"><i class="fas fa-plus"></i> যোগ করুন</button>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>সদস্য তালিকা</strong>
            <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>ইমেইল</th>
                      <th style="width: 120px;">অ্যাকশন</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (empty($members)): ?>
                      <tr><td colspan="8" class="text-center text-muted">কোনো সদস্য যোগ করা হয়নি</td></tr>
                    <?php else: foreach ($members as $m): ?>
                      <tr>
                        <td>
                          <input type="number" class="form-control form-control-sm" value="<?php echo (int)$m['order_no']; ?>" 
                                 onchange="updateOrderValue(<?php echo (int)$m['id']; ?>, this.value)">
                          <input type="hidden" id="order_hidden_<?php echo (int)$m['id']; ?>" name="order[<?php echo (int)$m['id']; ?>]" value="<?php echo (int)$m['order_no']; ?>">
                        </td>
                        <td>
                          <?php if (!empty($m['photo'])): 
                              $fullImagePath = __DIR__ . '/../' . $m['photo'];
                              if (file_exists($fullImagePath) && is_readable($fullImagePath)): ?>
                            <img src="../<?php echo htmlspecialchars($m['photo']); ?>" alt="Profile Photo" class="profile-img-small" style="border: 2px solid #dee2e6;">
                          <?php else: ?>
                            <span class="text-muted small">Image Not Found</span>
                          <?php endif; 
                          else: ?>
                            <span class="text-muted small">No Image</span>
                          <?php endif; ?>
                        </td>
                      <td><?php echo htmlspecialchars($m['name']); ?></td>
                      <td><?php echo htmlspecialchars($m['board_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>
                        <button type="button" class="btn btn-sm btn-outline-danger" 
                                onclick="deleteMember(<?php echo (int)$m['id']; ?>)">
                          <i class="fas fa-trash"></i>
                        </button>
                      </td>
                    </tr>
                  <?php endforeach; endif; ?>
                </tbody>
              </table>
            </div>
            <div class="p-2 text-end">
              <form method="post" id="saveOrderForm">
                <?php foreach ($members as $m): ?>
                  <input type="hidden" name="order[<?php echo (int)$m['id']; ?>]" id="order_hidden_<?php echo (int)$m['id']; ?>" value="<?php echo (int)$m['order_no']; ?>">
                <?php endforeach; ?>
                <button class="btn btn-success" name="save_order" type="submit"><i class="fas fa-save"></i> অর্ডার সংরক্ষণ</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Edit Modal -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <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" enctype="multipart/form-data">
          <div class="modal-body">
            <input type="hidden" name="edit_id" id="edit_id">
            <div class="row g-2">
              <div class="col-md-6">
                <label class="form-label">নাম</label>
                <input type="text" name="name" id="edit_name" class="form-control" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">বোর্ড ভূমিকা</label>
                <input type="text" name="board_role" id="edit_board_role" class="form-control">
              </div>
              <div class="col-md-6">
                <label class="form-label">ডিজাইগনেশন</label>
                <input type="text" name="designation" id="edit_designation" class="form-control">
              </div>
              <div class="col-md-3">
                <label class="form-label">মোবাইল</label>
                <input type="text" name="phone" id="edit_phone" class="form-control">
              </div>
              <div class="col-md-3">
                <label class="form-label">ইমেইল</label>
                <input type="email" name="email" id="edit_email" class="form-control">
              </div>
              <div class="col-md-12">
                <label class="form-label">ছবি (আপডেট করতে চাইলে নতুনটি বাছুন)</label>
                <input type="file" name="photo" accept="image/jpeg,image/png" class="form-control">
                <div class="form-text">বর্তমান ছবি: <span id="current_photo"></span></div>
              </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_board_role').value = data.board_role || '';
      document.getElementById('edit_designation').value = data.designation || '';
      document.getElementById('edit_phone').value = data.phone || '';
      document.getElementById('edit_email').value = data.email || '';
      const cp = document.getElementById('current_photo');
      if (data.photo) {
        cp.innerHTML = '<a href="../' + data.photo + '" target="_blank">বর্তমান ছবি দেখুন</a>';
      } else {
        cp.textContent = 'কোনো ছবি নেই';
      }
      editModal.show();
    }
    
    function updateOrderValue(memberId, value) {
      const hiddenInput = document.getElementById('order_hidden_' + memberId);
      if (hiddenInput) {
        hiddenInput.value = value;
      }
    }
    
    function deleteMember(memberId) {
      if (confirm('মুছতে নিশ্চিত?')) {
        const form = document.createElement('form');
        form.method = 'post';
        form.style.display = 'none';
        
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'delete_id';
        input.value = memberId;
        
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
      }
    }
  </script>
</body>
</html>