<?php
require_once __DIR__ . '/../../includes/dashboard-config.php';

// For role-specific pages, add:
checkRoleAccess(ROLE_STUDENT); // or ROLE_COUNSELOR or ROLE_ADMIN
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

if (!isLoggedIn() || !hasRole('admin')) {
    header('Location: ../login.php');
    exit();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_counselor'])) {
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $specialization = json_encode(explode(',', $_POST['specialization']));
        $max_students = $_POST['max_students'];
        
        // Create user account first
        $password = generateRandomPassword();
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        try {
            $pdo->beginTransaction();
            
            $stmt = $pdo->prepare("INSERT INTO users (email, password_hash, user_type) VALUES (?, ?, 'counselor')");
            $stmt->execute([$email, $password_hash]);
            $user_id = $pdo->lastInsertId();
            
            $stmt = $pdo->prepare("INSERT INTO counselors 
                                 (id, first_name, last_name, phone, specialization, max_students) 
                                 VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$user_id, $first_name, $last_name, $phone, $specialization, $max_students]);
            
            $pdo->commit();
            
            // Send welcome email with credentials
            $subject = "Your JV Overseas Counselor Account";
            $body = "
                <h2>Welcome to JV Overseas Education!</h2>
                <p>Your counselor account has been created with the following credentials:</p>
                <p><strong>Email:</strong> $email<br>
                <strong>Password:</strong> $password</p>
                <p>Please log in and change your password immediately.</p>
            ";
            
            if (sendEmail($email, $subject, $body)) {
                $_SESSION['success_message'] = "Counselor added successfully! Credentials sent to their email.";
            } else {
                $_SESSION['success_message'] = "Counselor added, but failed to send email. Password: $password";
            }
            
            header("Location: counselors.php");
            exit();
        } catch (PDOException $e) {
            $pdo->rollBack();
            $_SESSION['error_message'] = "Error adding counselor: " . $e->getMessage();
        }
    } elseif (isset($_POST['update_counselor'])) {
        $counselor_id = $_POST['id'];
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $phone = $_POST['phone'];
        $specialization = json_encode(explode(',', $_POST['specialization']));
        $max_students = $_POST['max_students'];
        
        try {
            $stmt = $pdo->prepare("UPDATE counselors 
                                 SET first_name = ?, last_name = ?, phone = ?, 
                                     specialization = ?, max_students = ? 
                                 WHERE id = ?");
            $stmt->execute([$first_name, $last_name, $phone, $specialization, $max_students, $counselor_id]);
            
            $_SESSION['success_message'] = "Counselor updated successfully!";
            header("Location: counselors.php");
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating counselor: " . $e->getMessage();
        }
    } elseif (isset($_POST['delete_counselor'])) {
        $counselor_id = $_POST['id'];
        
        try {
            $pdo->beginTransaction();
            
            // First reassign any assigned students
            $pdo->prepare("UPDATE students SET assigned_counselor_id = NULL WHERE assigned_counselor_id = ?")
                ->execute([$counselor_id]);
                
            // Then delete the counselor and user account
            $pdo->prepare("DELETE FROM counselors WHERE id = ?")->execute([$counselor_id]);
            $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$counselor_id]);
            
            $pdo->commit();
            
            $_SESSION['success_message'] = "Counselor deleted successfully!";
            header("Location: counselors.php");
            exit();
        } catch (PDOException $e) {
            $pdo->rollBack();
            $_SESSION['error_message'] = "Error deleting counselor: " . $e->getMessage();
        }
    }
}

// Get all counselors with their current student count
$counselors = $pdo->query("
    SELECT c.*, u.email, u.is_active, 
           COUNT(s.id) as current_students,
           ROUND(COUNT(s.id) * 100.0 / c.max_students, 1) as load_percentage
    FROM counselors c
    JOIN users u ON c.id = u.id
    LEFT JOIN students s ON c.id = s.assigned_counselor_id
    GROUP BY c.id
    ORDER BY c.first_name
")->fetchAll(PDO::FETCH_ASSOC);

include '../../includes/header.php';
?>

<div class="container py-5">
    <h2 class="mb-4">Counselor Management</h2>
    
    <?php displayMessages(); ?>
    
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">All Counselors</h5>
            <button class="btn btn-primary" data-toggle="modal" data-target="#addCounselorModal">
                <i class="fas fa-plus"></i> Add Counselor
            </button>
        </div>
        <div class="card-body">
            <?php if (count($counselors) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Counselor</th>
                                <th>Contact</th>
                                <th>Specialization</th>
                                <th>Students</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($counselors as $counselor): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($counselor['first_name'].' '.$counselor['last_name']) ?></strong><br>
                                        <small class="text-muted"><?= htmlspecialchars($counselor['email']) ?></small>
                                    </td>
                                    <td><?= htmlspecialchars($counselor['phone']) ?></td>
                                    <td>
                                        <?php 
                                        $specializations = json_decode($counselor['specialization']);
                                        echo implode(', ', $specializations); 
                                        ?>
                                    </td>
                                    <td>
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar <?= 
                                                $counselor['load_percentage'] > 90 ? 'bg-danger' : 
                                                ($counselor['load_percentage'] > 70 ? 'bg-warning' : 'bg-success') ?>" 
                                                role="progressbar" 
                                                style="width: <?= $counselor['load_percentage'] ?>%" 
                                                aria-valuenow="<?= $counselor['load_percentage'] ?>" 
                                                aria-valuemin="0" 
                                                aria-valuemax="100">
                                                <?= $counselor['current_students'] ?>/<?= $counselor['max_students'] ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?= $counselor['is_active'] ? 'success' : 'danger' ?>">
                                            <?= $counselor['is_active'] ? 'Active' : 'Inactive' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary edit-counselor" 
                                                data-id="<?= $counselor['id'] ?>"
                                                data-first_name="<?= htmlspecialchars($counselor['first_name']) ?>"
                                                data-last_name="<?= htmlspecialchars($counselor['last_name']) ?>"
                                                data-phone="<?= htmlspecialchars($counselor['phone']) ?>"
                                                data-specialization="<?= htmlspecialchars(implode(',', json_decode($counselor['specialization']))) ?>"
                                                data-max_students="<?= $counselor['max_students'] ?>">
                                            Edit
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete-counselor" 
                                                data-id="<?= $counselor['id'] ?>">
                                            Delete
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info">
                    No counselors found. Add your first counselor.
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Counselor Modal -->
<div class="modal fade" id="addCounselorModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Counselor</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="first_name">First Name</label>
                            <input type="text" class="form-control" id="first_name" name="first_name" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="last_name">Last Name</label>
                            <input type="text" class="form-control" id="last_name" name="last_name" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="phone">Phone</label>
                        <input type="text" class="form-control" id="phone" name="phone">
                    </div>
                    
                    <div class="form-group">
                        <label for="specialization">Specialization (comma separated)</label>
                        <input type="text" class="form-control" id="specialization" name="specialization" 
                               placeholder="e.g., USA,UK,Engineering" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="max_students">Max Students</label>
                        <input type="number" class="form-control" id="max_students" name="max_students" 
                               min="1" value="30" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_counselor" class="btn btn-primary">Add Counselor</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Counselor Modal -->
<div class="modal fade" id="editCounselorModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" id="edit_id" name="id">
                <input type="hidden" name="update_counselor" value="1">
                
                <div class="modal-header">
                    <h5 class="modal-title">Edit Counselor</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="edit_first_name">First Name</label>
                            <input type="text" class="form-control" id="edit_first_name" name="first_name" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="edit_last_name">Last Name</label>
                            <input type="text" class="form-control" id="edit_last_name" name="last_name" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_phone">Phone</label>
                        <input type="text" class="form-control" id="edit_phone" name="phone">
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_specialization">Specialization (comma separated)</label>
                        <input type="text" class="form-control" id="edit_specialization" name="specialization" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_max_students">Max Students</label>
                        <input type="number" class="form-control" id="edit_max_students" name="max_students" min="1" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Counselor</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteCounselorModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" id="delete_id" name="id">
                <input type="hidden" name="delete_counselor" value="1">
                
                <div class="modal-header">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this counselor? This action cannot be undone.</p>
                    <p>All students assigned to this counselor will be unassigned.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Counselor</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Edit counselor modal
document.querySelectorAll('.edit-counselor').forEach(button => {
    button.addEventListener('click', function() {
        document.getElementById('edit_id').value = this.dataset.id;
        document.getElementById('edit_first_name').value = this.dataset.first_name;
        document.getElementById('edit_last_name').value = this.dataset.last_name;
        document.getElementById('edit_phone').value = this.dataset.phone;
        document.getElementById('edit_specialization').value = this.dataset.specialization;
        document.getElementById('edit_max_students').value = this.dataset.max_students;
        $('#editCounselorModal').modal('show');
    });
});

// Delete counselor modal
document.querySelectorAll('.delete-counselor').forEach(button => {
    button.addEventListener('click', function() {
        document.getElementById('delete_id').value = this.dataset.id;
        $('#deleteCounselorModal').modal('show');
    });
});
</script>

<?php include '../../includes/footer.php'; ?>