<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

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

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

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';
$upload_dir = 'uploads/counselors/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle counselor creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_counselor'])) {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $specialization = $_POST['specialization'] ?? [];
    $max_students = $_POST['max_students'] ?? 30;
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validate form data
    if (empty($first_name) || empty($last_name) || empty($email) || empty($password)) {
        $error = "All required fields must be filled.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters long.";
    } elseif ($pdo->prepare("SELECT id FROM users WHERE email = ?")->execute([$email]) && $pdo->query("SELECT id FROM users WHERE email = '$email'")->fetch()) {
        $error = "An account with this email already exists.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();

            // Create user record
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (email, password_hash, user_type, is_active, created_at, updated_at) 
                                  VALUES (?, ?, 'counselor', 1, NOW(), NOW())");
            $stmt->execute([$email, $password_hash]);
            $user_id = $pdo->lastInsertId();

            // Handle profile photo upload
            $profile_photo = null;
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['name']) {
                $file_name = $_FILES['profile_photo']['name'];
                $file_tmp = $_FILES['profile_photo']['tmp_name'];
                $file_size = $_FILES['profile_photo']['size'];
                $file_error = $_FILES['profile_photo']['error'];

                if ($file_error === UPLOAD_ERR_OK && $file_size <= 5 * 1024 * 1024) {
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];

                    if (in_array($file_ext, $allowed_exts)) {
                        $unique_name = $user_id . '_counselor_' . time() . '.' . $file_ext;
                        $file_path = $upload_dir . $unique_name;

                        if (move_uploaded_file($file_tmp, $file_path)) {
                            $profile_photo = $file_path;
                        }
                    }
                }
            }

            // Create counselor profile
            $stmt = $pdo->prepare("INSERT INTO counselors (
                id, first_name, last_name, phone, profile_photo, specialization, 
                max_students, performance_rating, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, 0.00, NOW(), NOW())");

            $stmt->execute([
                $user_id, $first_name, $last_name, $phone, $profile_photo,
                json_encode($specialization), $max_students
            ]);

            // Create notification for the new counselor
            $pdo->prepare("INSERT INTO notifications (
                user_id, title, message, is_read, notification_type, created_at
            ) VALUES (?, ?, ?, 0, 'system', NOW())")->execute([
                $user_id,
                "Welcome to JV Overseas Education",
                "Your counselor account has been created. You can now log in with your email and password."
            ]);

            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "counselor_created",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created counselor account for {$first_name} {$last_name}"
            ]);

            // Commit transaction
            $pdo->commit();

            $success = "Counselor account created successfully! An email has been sent to the counselor with login instructions.";

            // Clear form data
            $_POST = array();

        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to create counselor account. Please try again.";
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-dashboard.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create Counselor - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <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="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .profile-upload {
            position: relative;
            display: inline-block;
        }
        .upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background: rgba(0,0,0,0.5);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.3s;
        }
        .profile-upload:hover .upload-overlay {
            opacity: 1;
        }
        .file-input {
            display: none;
        }
        .profile-img {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #3fb7fe;
        }
        .specialization-checkbox {
            margin-bottom: 10px;
        }
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #3fb7fe;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }
    </style>
</head>
<body>

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

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Admin Panel</h6>
        <h1 class="display-5">Create New Counselor Account</h1>
    </div>

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <div class="text-center">
            <a href="admin-manage-counselors.php" class="btn btn-primary">View All Counselors</a>
        </div>
    <?php else: ?>
        <form method="POST" enctype="multipart/form-data" novalidate>
            <div class="form-section">
                <h5 class="section-title">Personal Information</h5>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>First Name *</label>
                        <input type="text" name="first_name" class="form-control" 
                               value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Last Name *</label>
                        <input type="text" name="last_name" class="form-control" 
                               value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Email Address *</label>
                        <input type="email" name="email" class="form-control" 
                               value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Phone Number</label>
                        <input type="text" name="phone" class="form-control" 
                               value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Password *</label>
                        <input type="password" name="password" class="form-control" required>
                        <small class="form-text text-muted">Must be at least 6 characters</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Confirm Password *</label>
                        <input type="password" name="confirm_password" class="form-control" required>
                    </div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Profile Photo</h5>
                <div class="d-flex align-items-center">
                    <div class="profile-upload">
                        <img src="img/profile-placeholder.jpg" class="profile-img" alt="Profile" id="profilePreview">
                        <div class="upload-overlay">
                            <i class="fas fa-camera"></i>
                        </div>
                        <input type="file" name="profile_photo" id="profilePhoto" class="file-input" accept="image/*">
                    </div>
                    <div class="ml-4">
                        <p><strong>Upload Profile Photo</strong></p>
                        <p class="text-muted small">JPG, PNG, or GIF (max 5MB)</p>
                        <p class="text-muted small">Recommended: 400×400 pixels</p>
                    </div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Professional Details</h5>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Specialization *</label>
                        <?php
                        $specs = ['UK Universities', 'USA Universities', 'Canada Universities', 'Australia Universities', 'STEM Programs', 'Business Programs', 'Arts & Humanities'];
                        foreach ($specs as $spec): 
                            $checked = in_array($spec, $_POST['specialization'] ?? []) ? 'checked' : '';
                        ?>
                            <div class="form-check specialization-checkbox">
                                <input class="form-check-input" type="checkbox" name="specialization[]" value="<?= htmlspecialchars($spec) ?>" id="<?= strtolower(str_replace(' ', '_', $spec)) ?>" <?= $checked ?>>
                                <label class="form-check-label" for="<?= strtolower(str_replace(' ', '_', $spec)) ?>"><?= htmlspecialchars($spec) ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Maximum Students *</label>
                        <input type="number" name="max_students" class="form-control" min="1" max="50" 
                               value="<?= htmlspecialchars($_POST['max_students'] ?? '30') ?>" required>
                        <small class="form-text text-muted">Maximum number of students this counselor can handle</small>
                    </div>
                </div>
            </div>
            
            <div class="info-box">
                <h6><i class="fas fa-info-circle"></i> What Happens Next?</h6>
                <ul class="small">
                    <li>The counselor will receive an email with their login credentials</li>
                    <li>They can log in and update their profile information</li>
                    <li>You can assign students to this counselor from the manage counselors page</li>
                    <li>The counselor will appear in the counselor directory for students</li>
                </ul>
            </div>
            
            <div class="text-center">
                <button type="submit" name="create_counselor" class="btn btn-primary btn-lg px-5">Create Counselor Account</button>
            </div>
            
            <div class="text-center mt-3">
                <a href="admin-manage-counselors.php" class="btn btn-outline-primary">Cancel</a>
            </div>
        </form>
    <?php endif; ?>
</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>
<script>
    // Profile photo upload preview
    document.getElementById('profilePhoto').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('profilePreview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // Clicking on profile image triggers file select
    document.getElementById('profilePreview').addEventListener('click', function() {
        document.getElementById('profilePhoto').click();
    });

    // Confirm before form submission
    $('form').on('submit', function(e) {
        const firstName = $('input[name="first_name"]').val();
        const lastName = $('input[name="last_name"]').val();

        if (firstName && lastName && confirm(`You are about to create a counselor account for ${firstName} ${lastName}. Continue?`)) {
            return true;
        } else {
            e.preventDefault();
        }
    });
</script>
</body>
</html>
