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

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'counselor') {
    header('Location: counselor-login.php');
    exit;
}

// Get counselor data
$stmt = $pdo->prepare("SELECT c.*, u.email, u.last_login, u.is_active
                      FROM counselors c 
                      JOIN users u ON c.id = u.id 
                      WHERE c.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$counselor = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$counselor) {
    die("Counselor profile not found.");
}

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

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $email = $_POST['email'] ?? '';
    $specialization = $_POST['specialization'] ?? '';
    $max_students = $_POST['max_students'] ?? '';

    if ($first_name && $last_name && $email) {
        try {
            // Update user email
            $pdo->prepare("UPDATE users SET email = ? WHERE id = ?")->execute([$email, $_SESSION['user_id']]);
            // Update counselor profile
            $pdo->prepare("UPDATE counselors SET 
                first_name = ?, 
                last_name = ?, 
                phone = ?, 
                specialization = ?, 
                max_students = ? 
                WHERE id = ?")
                ->execute([$first_name, $last_name, $phone, $specialization, $max_students, $_SESSION['user_id']]);
            
            $success = "Profile updated successfully!";
            $_SESSION['first_name'] = $first_name;
            $_SESSION['last_name'] = $last_name;
            
            // Refresh counselor data
            $stmt = $pdo->prepare("SELECT c.*, u.email FROM counselors c JOIN users u ON c.id = u.id WHERE c.id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $counselor = $stmt->fetch(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            $error = "Failed to update profile. Please try again.";
        }
    } else {
        $error = "All fields are required.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Profile - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .profile-img {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #3fb7fe;
        }
    </style>
</head>
<body>

<?php include 'counselor-navbar.php'; ?>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="text-center">
                <img src="<?= htmlspecialchars($counselor['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" class="profile-img mb-3" alt="Profile">
                <h4><?= htmlspecialchars($counselor['first_name'] . ' ' . $counselor['last_name']) ?></h4>
                <p class="text-muted">Counselor ID: <?= $_SESSION['user_id'] ?></p>
            </div>
        </div>
        <div class="col-lg-8">
            <div class="section-title mb-4">
                <h1 class="display-6">Edit Profile</h1>
            </div>
            <?php if (isset($success)): ?>
                <div class="alert alert-success"><?= $success ?></div>
            <?php elseif (isset($error)): ?>
                <div class="alert alert-danger"><?= $error ?></div>
            <?php endif; ?>
            <form method="POST">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>First Name</label>
                        <input type="text" name="first_name" class="form-control" value="<?= htmlspecialchars($counselor['first_name']) ?>" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label>Last Name</label>
                        <input type="text" name="last_name" class="form-control" value="<?= htmlspecialchars($counselor['last_name']) ?>" required>
                    </div>
                </div>
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($counselor['phone']) ?>">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($counselor['email']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Specialization</label>
                    <input type="text" name="specialization" class="form-control" value="<?= htmlspecialchars($counselor['specialization']) ?>">
                    <small class="form-text text-muted">e.g., UK Universities, STEM Programs</small>
                </div>
                <div class="form-group">
                    <label>Maximum Students</label>
                    <input type="number" name="max_students" class="form-control" value="<?= htmlspecialchars($counselor['max_students']) ?>" min="1" max="50">
                    <small class="form-text text-muted">Maximum number of students you can handle</small>
                </div>
                <button type="submit" class="btn btn-primary">Save Changes</button>
            </form>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
</body>
</html>