Path : /home/vishqocm/pcib.in/backup_20250414/
File Upload :
Current File : /home/vishqocm//pcib.in/backup_20250414/profile.php

<?php
// Include header
include_once 'includes/header.php';

// Get user information from session
$student_id = $_SESSION['user_id'];
$success_message = '';
$error_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    // Get form data
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $address = $_POST['address'] ?? '';
    $city = $_POST['city'] ?? '';
    $state = $_POST['state'] ?? '';
    $zip_code = $_POST['zip_code'] ?? '';
    $bio = $_POST['bio'] ?? '';
    
    // Validate required fields
    if (empty($first_name) || empty($last_name) || empty($email)) {
        $error_message = "First name, last name, and email are required fields.";
    } else {
        try {
            // Begin transaction
            $conn->begin_transaction();
            
            // Update user profile
            $update_query = "
                UPDATE users SET 
                    first_name = ?,
                    last_name = ?,
                    email = ?,
                    phone = ?,
                    address = ?,
                    city = ?,
                    state = ?,
                    zip_code = ?,
                    bio = ?,
                    updated_at = NOW()
                WHERE id = ?
            ";
            
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("sssssssssi", $first_name, $last_name, $email, $phone, $address, $city, $state, $zip_code, $bio, $student_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Error updating profile information: " . $stmt->error);
            }
            
            // Handle profile image upload
            if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = '../uploads/profile_images/';
                
                // Create directory if it doesn't exist
                if (!file_exists($upload_dir)) {
                    if (!mkdir($upload_dir, 0777, true)) {
                        throw new Exception("Failed to create upload directory");
                    }
                }
                
                // Get file info
                $file_temp = $_FILES['profile_image']['tmp_name'];
                $file_name = $student_id . '_' . time() . '_' . basename($_FILES['profile_image']['name']);
                $file_size = $_FILES['profile_image']['size'];
                $file_type = $_FILES['profile_image']['type'];
                $file_path = $upload_dir . $file_name;
                
                // Validate file type
                $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                if (!in_array($file_type, $allowed_types)) {
                    throw new Exception("Invalid file type. Allowed types: JPEG, PNG, GIF");
                }
                
                // Validate file size (5MB max)
                if ($file_size > 5 * 1024 * 1024) {
                    throw new Exception("File size exceeds the maximum limit (5MB)");
                }
                
                // Move uploaded file
                if (move_uploaded_file($file_temp, $file_path)) {
                    // Get previous profile image to delete
                    $prev_image_query = "SELECT profile_image FROM users WHERE id = ?";
                    $stmt = $conn->prepare($prev_image_query);
                    $stmt->bind_param("i", $student_id);
                    $stmt->execute();
                    $prev_result = $stmt->get_result();
                    $prev_image = $prev_result->fetch_assoc()['profile_image'] ?? '';
                    
                    // Update profile image in database
                    $image_path = 'uploads/profile_images/' . $file_name;
                    $update_image_query = "UPDATE users SET profile_image = ? WHERE id = ?";
                    $stmt = $conn->prepare($update_image_query);
                    $stmt->bind_param("si", $image_path, $student_id);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("Error updating profile image: " . $stmt->error);
                    }
                    
                    // Delete previous profile image if exists
                    if (!empty($prev_image) && file_exists('../' . $prev_image) && $prev_image != 'assets/img/default-avatar.png') {
                        @unlink('../' . $prev_image);
                    }
                } else {
                    throw new Exception("Failed to upload profile image");
                }
            }
            
            // Commit transaction
            $conn->commit();
            $success_message = "Profile updated successfully!";
            
            // Update session variables
            $_SESSION['first_name'] = $first_name;
            $_SESSION['last_name'] = $last_name;
            $_SESSION['email'] = $email;
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            $error_message = $e->getMessage();
        }
    }
}

// Get user data
$query = "
    SELECT u.*, 
           COUNT(e.id) as total_courses
    FROM users u
    LEFT JOIN enrollments e ON u.id = e.user_id
    WHERE u.id = ?
    GROUP BY u.id
";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

// Check if attendance table exists and get attendance data
$has_attendance_data = false;
$attendance_percentage = 0;

$check_attendance_table = $conn->query("SHOW TABLES LIKE 'attendance'");
if ($check_attendance_table->num_rows > 0) {
    // Get attendance data
    $attendance_query = "
        SELECT 
            COUNT(*) as total_attendance_days,
            SUM(CASE WHEN a.status = 'present' THEN 1 ELSE 0 END) as total_present
        FROM attendance a 
        INNER JOIN enrollments e ON a.enrollment_id = e.id 
        WHERE e.user_id = ?
    ";
    $stmt = $conn->prepare($attendance_query);
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $attendance_result = $stmt->get_result();
    $attendance_data = $attendance_result->fetch_assoc();
    
    // Calculate attendance percentage
    $total_days = $attendance_data['total_attendance_days'] ?? 0;
    $present_days = $attendance_data['total_present'] ?? 0;
    
    if ($total_days > 0) {
        $attendance_percentage = round(($present_days / $total_days) * 100);
        $has_attendance_data = true;
    }
}

// Get enrolled courses
$courses_query = "
    SELECT c.id, c.title, c.image, c.description, 
           CONCAT(u.first_name, ' ', u.last_name) as instructor_name,
           e.enrollment_date, e.status
    FROM enrollments e
    INNER JOIN courses c ON e.course_id = c.id
    LEFT JOIN users u ON c.instructor_id = u.id
    WHERE e.user_id = ?
    ORDER BY e.enrollment_date DESC
    LIMIT 3
";

$stmt = $conn->prepare($courses_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$courses_result = $stmt->get_result();
$enrolled_courses = [];
while ($row = $courses_result->fetch_assoc()) {
    $enrolled_courses[] = $row;
}

// Get payment data
$payment_query = "
    SELECT SUM(amount) as total_paid,
           COUNT(*) as total_transactions
    FROM payments
    WHERE user_id = ? AND status IN ('completed', 'verified')
";
$stmt = $conn->prepare($payment_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$payment_result = $stmt->get_result();
$payment_data = $payment_result->fetch_assoc();
$total_paid = $payment_data['total_paid'] ?? 0;
$total_transactions = $payment_data['total_transactions'] ?? 0;

// Get document statistics
$document_query = "
    SELECT 
        COUNT(*) as total_documents,
        SUM(CASE WHEN status = 'verified' THEN 1 ELSE 0 END) as verified_documents,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_documents,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_documents
    FROM student_documents
    WHERE user_id = ?
";
$stmt = $conn->prepare($document_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$document_result = $stmt->get_result();
$document_data = $document_result->fetch_assoc();
?>

<div class="container-fluid py-4">
    <?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i> <?php echo $success_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>

    <div class="row">
        <!-- Profile Overview -->
        <div class="col-lg-4 mb-4">
            <div class="card shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="position-relative mx-auto mb-4" style="width: 150px; height: 150px;">
                        <img src="<?php echo !empty($user['profile_image']) ? '../' . $user['profile_image'] : '../assets/img/default-avatar.png'; ?>" 
                             class="rounded-circle shadow-sm" alt="Profile Image" 
                             style="width: 150px; height: 150px; object-fit: cover; border: 5px solid rgba(78, 115, 223, 0.1);">
                             
                        <label for="profile_image_upload" class="position-absolute bottom-0 end-0 bg-primary text-white rounded-circle p-2 cursor-pointer" style="cursor: pointer;">
                            <i class="fas fa-camera"></i>
                        </label>
                    </div>
                    
                    <h4 class="mb-1"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h4>
                    <p class="text-muted mb-3"><?php echo htmlspecialchars($user['email']); ?></p>
                    
                    <div class="mb-3">
                        <span class="badge bg-primary">Student</span>
                    </div>
                    
                    <div class="row text-center">
                        <div class="col-4 border-end">
                            <h5 class="mb-0"><?php echo $user['total_courses']; ?></h5>
                            <small class="text-muted">Courses</small>
                        </div>
                        <div class="col-4 border-end">
                            <h5 class="mb-0"><?php echo $document_data['total_documents'] ?? 0; ?></h5>
                            <small class="text-muted">Documents</small>
                        </div>
                        <div class="col-4">
                            <h5 class="mb-0"><?php echo $total_transactions; ?></h5>
                            <small class="text-muted">Payments</small>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-light">
                    <div class="d-grid">
                        <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                            <i class="fas fa-edit me-2"></i> Edit Profile
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Profile Details and Statistics -->
        <div class="col-lg-8 mb-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">Profile Information</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small">Full Name</label>
                                <div><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted small">Email Address</label>
                                <div><?php echo htmlspecialchars($user['email']); ?></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted small">Phone Number</label>
                                <div><?php echo !empty($user['phone']) ? htmlspecialchars($user['phone']) : 'Not provided'; ?></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small">Address</label>
                                <div><?php echo !empty($user['address']) ? htmlspecialchars($user['address']) : 'Not provided'; ?></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted small">City, State, Zip</label>
                                <div>
                                    <?php 
                                    $location = [];
                                    if (!empty($user['city'])) $location[] = $user['city'];
                                    if (!empty($user['state'])) $location[] = $user['state'];
                                    if (!empty($user['zip_code'])) $location[] = $user['zip_code'];
                                    echo !empty($location) ? htmlspecialchars(implode(', ', $location)) : 'Not provided'; 
                                    ?>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted small">Registered On</label>
                                <div><?php echo date('d M Y', strtotime($user['created_at'])); ?></div>
                            </div>
                        </div>
                    </div>
                    
                    <?php if (!empty($user['bio'])): ?>
                    <div class="mb-0">
                        <label class="form-label text-muted small">About Me</label>
                        <div><?php echo nl2br(htmlspecialchars($user['bio'])); ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Statistics Cards -->
            <div class="row">
                <?php if ($has_attendance_data): ?>
                <div class="col-md-4 mb-4">
                    <div class="card bg-success text-white h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="text-uppercase">Attendance</h6>
                                    <h2 class="mb-0"><?php echo $attendance_percentage; ?>%</h2>
                                </div>
                                <div>
                                    <i class="fas fa-calendar-check fa-3x opacity-50"></i>
                                </div>
                            </div>
                            <div class="mt-3">
                                <a href="attendance_report.php" class="text-white">View details <i class="fas fa-arrow-right ms-1"></i></a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="col-md-<?php echo $has_attendance_data ? '4' : '6'; ?> mb-4">
                    <div class="card bg-primary text-white h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="text-uppercase">Payments</h6>
                                    <h2 class="mb-0">₹<?php echo number_format($total_paid, 2); ?></h2>
                                </div>
                                <div>
                                    <i class="fas fa-money-bill-wave fa-3x opacity-50"></i>
                                </div>
                            </div>
                            <div class="mt-3">
                                <a href="payment_history.php" class="text-white">View details <i class="fas fa-arrow-right ms-1"></i></a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-<?php echo $has_attendance_data ? '4' : '6'; ?> mb-4">
                    <div class="card bg-info text-white h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="text-uppercase">Documents</h6>
                                    <h2 class="mb-0"><?php echo $document_data['verified_documents'] ?? 0; ?>/<?php echo $document_data['total_documents'] ?? 0; ?></h2>
                                </div>
                                <div>
                                    <i class="fas fa-file-alt fa-3x opacity-50"></i>
                                </div>
                            </div>
                            <div class="mt-3">
                                <a href="documents.php" class="text-white">View details <i class="fas fa-arrow-right ms-1"></i></a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Recent Courses -->
    <div class="row">
        <div class="col-12 mb-4">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Recent Courses</h5>
                    <a href="my_courses.php" class="btn btn-sm btn-light">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($enrolled_courses)): ?>
                    <div class="alert alert-info mb-0">
                        <i class="fas fa-info-circle me-2"></i> You are not enrolled in any courses yet.
                    </div>
                    <?php else: ?>
                    <div class="row">
                        <?php foreach ($enrolled_courses as $course): ?>
                        <div class="col-md-4">
                            <div class="card h-100">
                                <img src="<?php echo !empty($course['image']) ? '../' . $course['image'] : '../assets/img/course-placeholder.jpg'; ?>" 
                                     class="card-img-top" alt="<?php echo htmlspecialchars($course['title']); ?>"
                                     style="height: 140px; object-fit: cover;">
                                <div class="card-body">
                                    <h5 class="card-title"><?php echo htmlspecialchars($course['title']); ?></h5>
                                    <p class="card-text text-muted">
                                        <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($course['instructor_name']); ?>
                                    </p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="badge bg-<?php echo $course['status'] === 'completed' ? 'success' : 'primary'; ?>">
                                            <?php echo ucfirst($course['status']); ?>
                                        </span>
                                        <a href="course_details.php?id=<?php echo $course['id']; ?>" class="btn btn-sm btn-outline-primary">View</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Profile Modal -->
<div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="editProfileModalLabel">Edit Profile</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="first_name" class="form-label">First Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="last_name" class="form-label">Last Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="phone" class="form-label">Phone Number</label>
                            <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="address" class="form-label">Address</label>
                        <input type="text" class="form-control" id="address" name="address" value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>">
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="city" class="form-label">City</label>
                            <input type="text" class="form-control" id="city" name="city" value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="state" class="form-label">State</label>
                            <input type="text" class="form-control" id="state" name="state" value="<?php echo htmlspecialchars($user['state'] ?? ''); ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="zip_code" class="form-label">Zip Code</label>
                            <input type="text" class="form-control" id="zip_code" name="zip_code" value="<?php echo htmlspecialchars($user['zip_code'] ?? ''); ?>">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="bio" class="form-label">About Me</label>
                        <textarea class="form-control" id="bio" name="bio" rows="4"><?php echo htmlspecialchars($user['bio'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="profile_image" class="form-label">Profile Image</label>
                        <input type="file" class="form-control" id="profile_image" name="profile_image" accept="image/*">
                        <div class="form-text">Max size: 5MB. Allowed formats: JPEG, PNG, GIF</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="update_profile" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Hidden file input for profile image -->
<input type="file" id="profile_image_upload" accept="image/*" style="display: none;">

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Profile image upload via the camera icon
    const profileImageUpload = document.getElementById('profile_image_upload');
    const cameraIcon = document.querySelector('label[for="profile_image_upload"]');
    
    if (profileImageUpload && cameraIcon) {
        cameraIcon.addEventListener('click', function() {
            profileImageUpload.click();
        });
        
        profileImageUpload.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                // Open the edit profile modal
                const editProfileModal = new bootstrap.Modal(document.getElementById('editProfileModal'));
                editProfileModal.show();
                
                // Set the file in the modal's file input
                document.getElementById('profile_image').files = this.files;
            }
        });
    }
});
</script>

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