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

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

// Get student data
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

// Set default photo
$default_photo = 'img/profile-placeholder.jpg';
$upload_dir = 'uploads/profiles/';

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

// Validate current photo
$current_photo = $student['profile_photo'] ?? $default_photo;
if (empty($current_photo) || !file_exists($current_photo)) {
    $current_photo = $default_photo;
}

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

// Handle profile information update (without photo)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['upload_photo'])) {
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $email = $_POST['email'] ?? '';

    if ($first_name && $last_name && $email) {
        try {
            // Update user email
            $pdo->prepare("UPDATE users SET email = ? WHERE id = ?")
                ->execute([$email, $_SESSION['user_id']]);
            
            // Update student profile (without touching profile_photo)
            $pdo->prepare("UPDATE students SET 
                first_name = ?, 
                last_name = ?, 
                phone = ?, 
                updated_at = NOW() 
                WHERE id = ?")
                ->execute([$first_name, $last_name, $phone, $_SESSION['user_id']]);
            
            $success = "Profile information updated successfully!";
            
            // Update session data
            $_SESSION['first_name'] = $first_name;
            $_SESSION['last_name'] = $last_name;
            
            // Refresh student data
            $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $student = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Update current photo in case it changed elsewhere
            $current_photo = $student['profile_photo'] ?? $default_photo;
            if (empty($current_photo) || !file_exists($current_photo)) {
                $current_photo = $default_photo;
            }
            
        } catch (Exception $e) {
            $error = "Failed to update profile. Please try again.";
        }
    } else {
        $error = "All required fields must be filled.";
    }
}
?>

<!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;
            cursor: pointer;
            transition: all 0.3s;
        }
        .profile-img:hover {
            transform: scale(1.05);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .profile-section {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }
        .photo-actions {
            margin-top: 15px;
        }
        .photo-actions a {
            display: inline-block;
            margin-right: 10px;
            color: #3fb7fe;
            text-decoration: none;
        }
        .photo-actions a:hover {
            text-decoration: underline;
        }
        .section-title {
            border-bottom: 2px solid #3fb7fe;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>

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

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h1 class="display-5">My Profile</h1>
    </div>

    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php elseif (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-4 mb-4">
            <!-- Profile Photo Section -->
            <div class="profile-section text-center">
                <img src="<?= htmlspecialchars($current_photo) ?>" 
                     class="profile-img mb-3" alt="Profile">
                <h4><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></h4>
                <p class="text-muted">Student ID: <?= $_SESSION['user_id'] ?></p>
                
                <div class="photo-actions">
                    <a href="upload-profile-photo.php">
                        <i class="fas fa-camera"></i> Change Photo
                    </a>
                    <?php if ($student['profile_photo'] && $student['profile_photo'] !== $default_photo): ?>
                    <a href="#" id="removePhoto" style="color: #dc3545;">
                        <i class="fas fa-trash"></i> Remove
                    </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Personal Info -->
            <div class="profile-section">
                <h6><i class="fas fa-info-circle"></i> Personal Information</h6>
                <p><strong>Email:</strong> <?= htmlspecialchars($_SESSION['email']) ?></p>
                <p><strong>Phone:</strong> <?= htmlspecialchars($student['phone'] ?? 'Not set') ?></p>
                <p><strong>Status:</strong> 
                <?php 
                $profile_status = $student['status'] ?? 'prospective';
                $badge_class = $profile_status === 'active' ? 'success' : 
                               ($profile_status === 'prospective' ? 'info' : 'secondary');
                ?>
                <span class="badge badge-<?= htmlspecialchars($badge_class) ?>">
                    <?= ucfirst(htmlspecialchars($profile_status)) ?>
                </span></p>
            </div>
        </div>
        
        <div class="col-lg-8">
            <!-- Profile Information Form -->
            <div class="profile-section">
                <h5 class="section-title">Edit Profile Information</h5>
                
                <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($student['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($student['last_name']) ?>" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" class="form-control" 
                               value="<?= htmlspecialchars($student['phone']) ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Email *</label>
                        <input type="email" name="email" class="form-control" 
                               value="<?= htmlspecialchars($_SESSION['email']) ?>" required>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Save Profile Information</button>
                </form>
            </div>

            <!-- Academic Background -->
            <div class="profile-section">
                <h5 class="section-title">Academic Background</h5>
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Education Level:</strong> <?= htmlspecialchars($student['education_level'] ?? 'Not specified') ?></p>
                        <p><strong>Current Institution:</strong> <?= htmlspecialchars($student['current_institution'] ?? 'Not specified') ?></p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>GPA:</strong> <?= htmlspecialchars($student['gpa'] ?? 'Not specified') ?></p>
                        <p><strong>Budget:</strong> $<?= number_format($student['budget'] ?? 0) ?></p>
                    </div>
                </div>
            </div>

            <!-- Preferred Destinations -->
            <?php if ($student['preferred_countries']): ?>
            <div class="profile-section">
                <h5 class="section-title">Preferred Destinations</h5>
                <div class="row">
                    <?php 
                    $countries = json_decode($student['preferred_countries'], true) ?: [];
                    foreach ($countries as $country): ?>
                    <div class="col-md-4 mb-2">
                        <span class="badge badge-primary"><?= htmlspecialchars($country) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </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>
<script>
    // Remove photo confirmation
    document.getElementById('removePhoto')?.addEventListener('click', function(e) {
        e.preventDefault();
        if (confirm('Are you sure you want to remove your profile photo? You will be using the default placeholder.')) {
            alert('Photo removal would be processed here. For full functionality, implement server-side removal.');
        }
    });
</script>
</body>
</html>