<?php
// admin/users/teachers.php
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

if(!function_exists('clean')){
    function clean($data) { return htmlspecialchars(strip_tags(trim($data))); }
}

// --- UPDATED AUTH CHECK ---
// Use in_array to allow both 'admin' and 'subadmin' roles
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../../auth/login.php");
    exit();
}

// Handle Delete Teacher
if (isset($_GET['delete_id'])) {
    $id = (int)$_GET['delete_id'];
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'teacher'");
    $stmt->execute([$id]);
    header("Location: teachers.php?success=Teacher deleted successfully");
    exit();
}

// Handle Adding a Teacher
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_teacher'])) {
    $fullname = clean($_POST['fullname']);
    $email = clean($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $section_id = !empty($_POST['section_id']) ? $_POST['section_id'] : null;
    $class_id = !empty($_POST['class_id']) ? $_POST['class_id'] : null;
    $role = 'teacher';

    $check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $check->execute([$email]);
    
    if ($check->rowCount() == 0) {
        $stmt = $pdo->prepare("INSERT INTO users (fullname, email, password, role, section_id, class_id) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$fullname, $email, $password, $role, $section_id, $class_id]);
        $success = "Teacher registered successfully!";
    } else {
        $error = "This email is already registered.";
    }
}

$sections = $pdo->query("SELECT * FROM sections ORDER BY id ASC")->fetchAll();
$classes = $pdo->query("SELECT c.*, s.section_name FROM classes c JOIN sections s ON c.section_id = s.id ORDER BY s.id, c.class_name ASC")->fetchAll();

$query = "SELECT u.*, s.section_name, c.class_name 
          FROM users u 
          LEFT JOIN sections s ON u.section_id = s.id 
          LEFT JOIN classes c ON u.class_id = c.id 
          WHERE u.role = 'teacher' 
          ORDER BY u.fullname ASC";
$teachers = $pdo->query($query)->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Teachers | <?php echo htmlspecialchars($school_name); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #34495e; --accent: #3498db; --success: #2ecc71; --danger: #e74c3c; --warning: #f39c12; }
        
        body { font-family: 'Inter', 'Segoe UI', sans-serif; background: #f4f7f6; margin: 0; padding: 10px; color: #333; }
        .container { background: white; padding: 20px; border-radius: 12px; max-width: 1150px; margin: 10px auto; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        
        .back-link { text-decoration: none; color: var(--accent); font-weight: 600; font-size: 14px; display: inline-block; margin-bottom: 15px; }
        
        .registration-box { background: #f9f9f9; padding: 20px; border-radius: 10px; border: 1px solid #eee; margin-bottom: 30px; }
        .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 15px; margin-bottom: 15px; }
        
        input, select { padding: 12px; border: 1px solid #ddd; border-radius: 6px; width: 100%; box-sizing: border-box; font-size: 14px; }
        
        .btn-submit { padding: 12px; background: var(--success); color: white; border: none; cursor: pointer; border-radius: 6px; font-weight: bold; transition: 0.3s; }
        .btn-submit:hover { background: #27ae60; opacity: 0.9; }

        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th { background: var(--primary); color: white; padding: 15px; text-align: left; font-size: 12px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid #eee; font-size: 14px; }
        
        .badge { padding: 5px 10px; border-radius: 20px; font-size: 11px; font-weight: bold; color: white; display: inline-block; margin-right: 4px; }
        .bg-section { background: var(--accent); }
        .bg-class { background: #9b59b6; }

        .actions { display: flex; gap: 8px; }
        .btn-edit { background: var(--warning); color: white; padding: 8px 12px; text-decoration: none; border-radius: 4px; font-size: 12px; }
        .btn-del { background: var(--danger); color: white; padding: 8px 12px; text-decoration: none; border-radius: 4px; font-size: 12px; }

        @media (max-width: 768px) {
            .form-row { grid-template-columns: 1fr; }
            table, thead, tbody, th, td, tr { display: block; }
            thead tr { position: absolute; top: -9999px; left: -9999px; }
            tr { border: 1px solid #eee; margin-bottom: 15px; border-radius: 10px; padding: 10px; background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
            td { border: none; position: relative; padding-left: 45%; text-align: right; min-height: 35px; }
            td:before { 
                position: absolute; left: 15px; width: 40%; padding-right: 10px; 
                white-space: nowrap; text-align: left; font-weight: bold; color: #7f8c8d;
                content: attr(data-label); 
            }
            .actions { justify-content: flex-end; }
        }
    </style>
</head>
<body>

<div class="container">
    <a href="../dashboard.php" class="back-link"><i class="fa fa-arrow-left"></i> Dashboard</a>
    <h2 style="margin: 0 0 20px 0;">Manage Teachers</h2>

    <?php if(isset($success) || isset($_GET['success'])): ?>
        <div style="background: #d4edda; color: #155724; padding: 12px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #c3e6cb;">
            <i class="fa fa-check-circle"></i> <?php echo $success ?? $_GET['success']; ?>
        </div>
    <?php endif; ?>

    <div class="registration-box">
        <h4 style="margin-top:0;"><i class="fa fa-user-plus"></i> Add New Teacher</h4>
        <form method="POST">
            <div class="form-row">
                <input type="text" name="fullname" placeholder="Full Name" required>
                <input type="email" name="email" placeholder="Email Address" required>
                <input type="password" name="password" placeholder="Password" required>
            </div>
            <div class="form-row">
                <select name="section_id">
                    <option value="">-- Select Section --</option>
                    <?php foreach($sections as $sec): ?>
                        <option value="<?= $sec['id'] ?>"><?= $sec['section_name'] ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="class_id">
                    <option value="">-- Select Class --</option>
                    <?php foreach($classes as $cl): ?>
                        <option value="<?= $cl['id'] ?>"><?= $cl['class_name'] ?> (<?= $cl['section_name'] ?>)</option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" name="add_teacher" class="btn-submit">Register Teacher</button>
            </div>
        </form>
    </div>

    <table>
        <thead>
            <tr>
                <th>Full Name</th>
                <th>Email</th>
                <th>Assignments</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($teachers as $t): ?>
            <tr>
                <td data-label="Full Name"><strong><?php echo htmlspecialchars($t['fullname']); ?></strong></td>
                <td data-label="Email"><?php echo htmlspecialchars($t['email']); ?></td>
                <td data-label="Assignments">
                    <?php if($t['section_name']): ?>
                        <span class="badge bg-section"><?php echo $t['section_name']; ?></span>
                    <?php endif; ?>
                    <?php if($t['class_name']): ?>
                        <span class="badge bg-class"><?php echo $t['class_name']; ?></span>
                    <?php endif; ?>
                    <?php if(!$t['section_name'] && !$t['class_name']) echo "<small style='color:gray;'>None</small>"; ?>
                </td>
                <td data-label="Status"><span style="color:var(--success); font-weight:bold;"><i class="fa fa-circle" style="font-size: 8px;"></i> Active</span></td>
                <td data-label="Actions">
                    <div class="actions">
                        <a href="edit_teacher.php?id=<?= $t['id'] ?>" class="btn-edit"><i class="fa fa-edit"></i> Edit</a>
                        <a href="?delete_id=<?= $t['id'] ?>" class="btn-del" onclick="return confirm('Delete this teacher?')"><i class="fa fa-trash"></i></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

</body>
</html>