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

// Authentication check
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 upload directory
$upload_dir = 'uploads/profiles/';
$default_photo = 'img/profile-placeholder.jpg';

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

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

// Handle profile photo upload only
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_photo'])) {
    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'];
        
        // Validate file
        if ($file_error !== UPLOAD_ERR_OK) {
            $error = "File upload error occurred.";
        } elseif ($file_size > 5 * 1024 * 1024) { // 5MB limit
            $error = "File size must be less than 5MB.";
        } else {
            // Get file extension
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array($file_ext, $allowed_exts)) {
                $error = "Only JPG, JPEG, PNG, and GIF files are allowed.";
            } else {
                // Generate unique filename
                $unique_name = $_SESSION['user_id'] . '_profile_' . time() . '.' . $file_ext;
                $file_path = $upload_dir . $unique_name;
                
                // Move uploaded file
                if (move_uploaded_file($file_tmp, $file_path)) {
                    // Remove old photo if it's not the default and exists
                    $old_photo = $student['profile_photo'] ?? '';
                    if ($old_photo && $old_photo !== $default_photo && file_exists($old_photo)) {
                        @unlink($old_photo);
                    }
                    
                    // Update profile photo in database
                    $pdo->prepare("UPDATE students SET profile_photo = ?, updated_at = NOW() WHERE id = ?")
                        ->execute([$file_path, $_SESSION['user_id']]);
                    
                    // Update session data
                    $_SESSION['profile_photo'] = $file_path;
                    
                    $success = "Profile photo updated successfully!";
                    
                    // Refresh student data
                    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
                    $stmt->execute([$_SESSION['user_id']]);
                    $student = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                } else {
                    $error = "Failed to save uploaded photo.";
                }
            }
        }
    } else {
        $error = "Please select a photo to upload.";
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Update Profile Photo - 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-container {
            max-width: 600px;
            margin: 40px auto;
        }
        .profile-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .profile-img {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #3fb7fe;
            margin: 0 auto 20px;
            display: block;
            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-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 {
            position: absolute;
            top: 0;
            left: 0;
            width: 150px;
            height: 150px;
            opacity: 0;
            cursor: pointer;
            z-index: 10;
        }
        .photo-instructions {
            margin: 20px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            font-size: 0.9em;
        }
        .btn-container {
            text-align: center;
            margin-top: 20px;
        }
        .back-link {
            display: block;
            text-align: center;
            margin-top: 20px;
            color: #3fb7fe;
            text-decoration: none;
        }
        .back-link:hover {
            text-decoration: underline;
        }
        /* Fix for file input */
        .upload-container {
            position: relative;
            display: inline-block;
        }
    </style>
</head>
<body>

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

<div class="container py-5">
    <div class="profile-container">
        <div class="profile-card">
            <h2 class="text-center mb-4">Update Profile Photo</h2>
            
            <?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; ?>
            
            <form method="POST" enctype="multipart/form-data">
                <div class="text-center">
                    <!-- Profile Photo Upload Section -->
                    <div class="upload-container">
                        <img src="<?= htmlspecialchars($current_photo) ?>" 
                             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/*" required>
                    </div>
                    
                    <h4><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></h4>
                    <p class="text-muted">Student ID: <?= $_SESSION['user_id'] ?></p>
                </div>
                
                <div class="photo-instructions">
                    <h6><i class="fas fa-info-circle"></i> Photo Guidelines</h6>
                    <ul class="mb-0">
                        <li>File format: JPG, JPEG, PNG, or GIF</li>
                        <li>Maximum size: 5MB</li>
                        <li>Recommended size: 400×400 pixels</li>
                        <li>Use a clear, recent photo with good lighting</li>
                    </ul>
                </div>
                
                <div class="btn-container">
                    <button type="submit" name="upload_photo" class="btn btn-primary btn-lg">
                        <i class="fas fa-upload"></i> Upload New Photo
                    </button>
                </div>
            </form>
            
            <a href="student-profile.php" class="back-link">
                <i class="fas fa-arrow-left"></i> Back to Profile
            </a>
        </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>
    // Make sure the file input is triggered when clicking on the image or overlay
    document.getElementById('profilePreview').addEventListener('click', function() {
        document.getElementById('profilePhoto').click();
    });
    
    // Handle file selection
    document.getElementById('profilePhoto').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // Validate file type
            const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
            if (!allowedTypes.includes(file.type)) {
                alert('Please select a valid image file (JPG, PNG, or GIF).');
                e.target.value = '';
                return;
            }
            
            // Validate file size (5MB)
            if (file.size > 5 * 1024 * 1024) {
                alert('File size must be less than 5MB.');
                e.target.value = '';
                return;
            }
            
            // Update preview
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('profilePreview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
    
    // Form submission confirmation
    document.querySelector('form').addEventListener('submit', function(e) {
        const fileInput = document.getElementById('profilePhoto');
        if (fileInput.files.length === 0) {
            e.preventDefault();
            alert('Please select a photo to upload.');
            return false;
        }
    });
</script>
</body>
</html>