<?php
/**
 * User Profile Page
 * GHAMECC Choir Management Platform
 */

// Include authentication functions
require_once 'includes/auth.php';
require_once 'config/database.php';
require_once 'config/logger.php';

// Require login
requireLogin();

// Get user information
$userId = $_SESSION['user_id'];
$userFullName = $_SESSION['full_name'] ?? $_SESSION['username'];
$userRole = $_SESSION['role'] ?? '';
$userDioceseId = $_SESSION['diocese_id'] ?? null;
$userCircuitId = $_SESSION['circuit_id'] ?? null;
$userSocietyId = $_SESSION['society_id'] ?? null;

// Set base path for includes
$basePath = '.';

// Process form submission
$message = '';
$messageType = '';

// Get user data
global $conn;
$userData = null;
$memberData = null;

try {
    // Get user data
    $stmt = $conn->prepare("SELECT u.*, r.role_key, r.name as role_name 
                           FROM users u 
                           JOIN roles r ON u.role_id = r.id
                           WHERE u.id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $userData = $result->fetch_assoc();
        
        // Get associated member data if exists
        if (!empty($userData['member_id'])) {
            $memberStmt = $conn->prepare("SELECT * FROM members WHERE id = ?");
            $memberStmt->bind_param("i", $userData['member_id']);
            $memberStmt->execute();
            $memberResult = $memberStmt->get_result();
            
            if ($memberResult->num_rows > 0) {
                $memberData = $memberResult->fetch_assoc();
            }
            
            $memberStmt->close();
        }
    }
    
    $stmt->close();
    
    // Get entity names
    $dioceseName = '';
    $circuitName = '';
    $societyName = '';
    
    if ($userData['diocese_id']) {
        $diocese = fetchRow("SELECT name FROM dioceses WHERE id = ?", [$userData['diocese_id']]);
        if ($diocese) {
            $dioceseName = $diocese['name'];
        }
    }
    
    if ($userData['circuit_id']) {
        $circuit = fetchRow("SELECT name FROM circuits WHERE id = ?", [$userData['circuit_id']]);
        if ($circuit) {
            $circuitName = $circuit['name'];
        }
    }
    
    if ($userData['society_id']) {
        $society = fetchRow("SELECT name FROM societies WHERE id = ?", [$userData['society_id']]);
        if ($society) {
            $societyName = $society['name'];
        }
    }
} catch (Exception $e) {
    logError("Error retrieving user profile data: " . $e->getMessage());
    $message = 'Error retrieving profile data. Please try again later.';
    $messageType = 'danger';
}

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_profile') {
        $fullName = trim($_POST['full_name']);
        $email = trim($_POST['email']);
        $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
        
        // Validate input
        if (empty($fullName) || empty($email)) {
            $message = 'Name and email are required.';
            $messageType = 'danger';
        } else {
            try {
                // Update user data
                $stmt = $conn->prepare("UPDATE users SET full_name = ?, email = ?, phone = ? WHERE id = ?");
                $stmt->bind_param("sssi", $fullName, $email, $phone, $userId);
                
                if ($stmt->execute()) {
                    // Update session data
                    $_SESSION['full_name'] = $fullName;
                    
                    $message = 'Profile updated successfully.';
                    $messageType = 'success';
                    logInfo("User ID $userId updated their profile");
                    
                    // Refresh user data
                    $userData['full_name'] = $fullName;
                    $userData['email'] = $email;
                    $userData['phone'] = $phone;
                } else {
                    $message = 'Error updating profile: ' . $conn->error;
                    $messageType = 'danger';
                    logError("Failed to update profile for User ID $userId: " . $conn->error);
                }
                
                $stmt->close();
            } catch (Exception $e) {
                $message = 'Error updating profile: ' . $e->getMessage();
                $messageType = 'danger';
                logError("Exception updating profile for User ID $userId: " . $e->getMessage());
            }
        }
    } elseif ($_POST['action'] === 'upload_photo') {
        // Handle profile photo upload
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'includes/uploads/profile_images/';
            
            // Create directory if it doesn't exist
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileExtension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array(strtolower($fileExtension), $allowedExtensions)) {
                $message = 'Only JPG, JPEG, PNG, and GIF files are allowed.';
                $messageType = 'danger';
            } else {
                // Generate unique filename
                $newFilename = 'user_' . $userId . '_' . time() . '.' . $fileExtension;
                $targetFile = $uploadDir . $newFilename;
                
                if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $targetFile)) {
                    // Update user record with new profile image
                    $stmt = $conn->prepare("UPDATE users SET profile_image = ? WHERE id = ?");
                    $stmt->bind_param("si", $newFilename, $userId);
                    
                    if ($stmt->execute()) {
                        // Delete old profile image if exists
                        if (!empty($userData['profile_image']) && $userData['profile_image'] !== $newFilename) {
                            $oldFile = $uploadDir . $userData['profile_image'];
                            if (file_exists($oldFile)) {
                                unlink($oldFile);
                            }
                        }
                        
                        $message = 'Profile image updated successfully.';
                        $messageType = 'success';
                        $userData['profile_image'] = $newFilename;
                        logInfo("User ID $userId updated their profile image");
                    } else {
                        $message = 'Error updating profile image in database: ' . $conn->error;
                        $messageType = 'danger';
                        logError("Failed to update profile image for User ID $userId: " . $conn->error);
                    }
                    
                    $stmt->close();
                } else {
                    $message = 'Error uploading profile image.';
                    $messageType = 'danger';
                    logError("Failed to upload profile image for User ID $userId");
                }
            }
        } else {
            $message = 'No image selected or upload error occurred.';
            $messageType = 'danger';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - GHAMECC Choir Management</title>
    
    <?php include 'includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        .profile-image-container {
            width: 150px;
            height: 150px;
            overflow: hidden;
            border-radius: 50%;
            margin: 0 auto 20px;
            position: relative;
        }
        .profile-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .profile-image-upload {
            position: absolute;
            bottom: 0;
            right: 0;
            background: rgba(0,0,0,0.5);
            color: white;
            padding: 5px;
            border-radius: 50%;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">My Profile</h1>
                </div>
                
                <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <?php if ($userData): ?>
                <div class="row">
                    <!-- Profile Summary Card -->
                    <div class="col-md-4 mb-4">
                        <div class="card shadow">
                            <div class="card-body text-center">
                                <div class="profile-image-container">
                                    <?php if (!empty($userData['profile_image'])): ?>
                                        <img src="includes/uploads/profile_images/<?php echo htmlspecialchars($userData['profile_image']); ?>" alt="Profile Image" class="profile-image">
                                    <?php else: ?>
                                        <img src="assets/img/default-profile.png" alt="Default Profile" class="profile-image">
                                    <?php endif; ?>
                                    <div class="profile-image-upload" data-bs-toggle="modal" data-bs-target="#uploadPhotoModal">
                                        <i class="fas fa-camera"></i>
                                    </div>
                                </div>
                                
                                <h4><?php echo htmlspecialchars($userData['full_name']); ?></h4>
                                <p class="text-muted"><?php echo htmlspecialchars($userData['role_name'] ?? $userData['role_key']); ?></p>
                                
                                <div class="mt-3">
                                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                                        <i class="fas fa-edit me-2"></i>Edit Profile
                                    </button>
                                    <a href="change-password.php" class="btn btn-outline-secondary btn-sm ms-2">
                                        <i class="fas fa-key me-2"></i>Change Password
                                    </a>
                                </div>
                            </div>
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item">
                                    <i class="fas fa-envelope me-2"></i> <?php echo htmlspecialchars($userData['email'] ?? 'Not set'); ?>
                                </li>
                                <li class="list-group-item">
                                    <i class="fas fa-phone me-2"></i> <?php echo htmlspecialchars($userData['phone'] ?? 'Not set'); ?>
                                </li>
                                <li class="list-group-item">
                                    <i class="fas fa-user-shield me-2"></i> Status: 
                                    <span class="badge bg-<?php echo $userData['status'] === 'active' ? 'success' : 'danger'; ?>">
                                        <?php echo ucfirst(htmlspecialchars($userData['status'])); ?>
                                    </span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    
                    <!-- Organization Details -->
                    <div class="col-md-8">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Organization Details</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <tbody>
                                            <?php if (!empty($dioceseName)): ?>
                                            <tr>
                                                <th width="30%">Diocese</th>
                                                <td><?php echo htmlspecialchars($dioceseName); ?></td>
                                            </tr>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($circuitName)): ?>
                                            <tr>
                                                <th>Circuit</th>
                                                <td><?php echo htmlspecialchars($circuitName); ?></td>
                                            </tr>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($societyName)): ?>
                                            <tr>
                                                <th>Society</th>
                                                <td><?php echo htmlspecialchars($societyName); ?></td>
                                            </tr>
                                            <?php endif; ?>
                                            
                                            <tr>
                                                <th>Role</th>
                                                <td><?php echo htmlspecialchars($userData['role_name'] ?? $userData['role_key']); ?></td>
                                            </tr>
                                            
                                            <tr>
                                                <th>Account Created</th>
                                                <td><?php echo htmlspecialchars($userData['created_at']); ?></td>
                                            </tr>
                                            
                                            <tr>
                                                <th>Last Login</th>
                                                <td><?php echo !empty($userData['last_login']) ? htmlspecialchars($userData['last_login']) : 'Not available'; ?></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($memberData): ?>
                        <!-- Member Details -->
                        <div class="card shadow">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Member Details</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <tbody>
                                            <tr>
                                                <th width="30%">Full Name</th>
                                                <td><?php echo htmlspecialchars($memberData['first_name'] . ' ' . $memberData['last_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Contact Number</th>
                                                <td><?php echo htmlspecialchars($memberData['contact_number_1'] ?? 'Not set'); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Email</th>
                                                <td><?php echo htmlspecialchars($memberData['email'] ?? 'Not set'); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Address</th>
                                                <td><?php echo htmlspecialchars($memberData['address'] ?? 'Not set'); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Department</th>
                                                <td><?php echo htmlspecialchars($memberData['department'] ?? 'Not set'); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Position</th>
                                                <td><?php echo htmlspecialchars($memberData['position'] ?? 'Not set'); ?></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-danger">
                    <p>Error loading profile data. Please try again later or contact support.</p>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- Edit Profile Modal -->
    <div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editProfileModalLabel">Edit Profile</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_profile">
                        
                        <div class="mb-3">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="username" value="<?php echo htmlspecialchars($userData['username'] ?? ''); ?>" readonly>
                            <div class="form-text">Username cannot be changed.</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="full_name" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($userData['full_name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($userData['email'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="phone" class="form-label">Phone</label>
                            <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($userData['phone'] ?? ''); ?>">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Upload Photo Modal -->
    <div class="modal fade" id="uploadPhotoModal" tabindex="-1" aria-labelledby="uploadPhotoModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadPhotoModalLabel">Upload Profile Photo</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="" enctype="multipart/form-data">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="upload_photo">
                        
                        <div class="mb-3">
                            <label for="profile_image" class="form-label">Select Image</label>
                            <input type="file" class="form-control" id="profile_image" name="profile_image" accept="image/*" required>
                            <div class="form-text">Allowed formats: JPG, JPEG, PNG, GIF. Max size: 2MB.</div>
                        </div>
                        
                        <div class="mb-3">
                            <div id="imagePreview" class="mt-3 text-center" style="display: none;">
                                <img src="" alt="Image Preview" style="max-width: 100%; max-height: 200px;">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Upload</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Image preview
            $('#profile_image').change(function() {
                const file = this.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('#imagePreview').show();
                        $('#imagePreview img').attr('src', e.target.result);
                    }
                    reader.readAsDataURL(file);
                }
            });
        });
    </script>
</body>
</html>
