<?php
require_once '../includes/config.php';

// Check if user is logged in
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../auth/login.php');
    exit();
}

$title = "My Profile";

// Initialize variables
$message = '';
$message_type = '';
$user_id = $_SESSION['user_id'];

// Get current user data
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'i', $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (!$result || mysqli_num_rows($result) == 0) {
    header('Location: logout.php');
    exit();
}

$user = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_profile'])) {
        $full_name = escape($conn, trim($_POST['full_name']));
        $email = escape($conn, trim($_POST['email']));
        $contact_number = escape($conn, trim($_POST['contact_number']));
        $address = escape($conn, trim($_POST['address']));
        
        // Validate email
        if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $message = 'Invalid email address.';
            $message_type = 'danger';
        } else {
            // Check if email already exists
            $check_sql = "SELECT id FROM users WHERE email = ? AND id != ?";
            $check_stmt = mysqli_prepare($conn, $check_sql);
            mysqli_stmt_bind_param($check_stmt, 'si', $email, $user_id);
            mysqli_stmt_execute($check_stmt);
            mysqli_stmt_store_result($check_stmt);
            
            if (mysqli_stmt_num_rows($check_stmt) > 0) {
                $message = 'Email already exists.';
                $message_type = 'danger';
            } else {
                // Update profile
                $update_sql = "UPDATE users SET 
                              full_name = ?, 
                              email = ?, 
                              contact_number = ?, 
                              address = ?, 
                              updated_at = NOW() 
                              WHERE id = ?";
                
                $update_stmt = mysqli_prepare($conn, $update_sql);
                mysqli_stmt_bind_param($update_stmt, 'ssssi', 
                    $full_name, $email, $contact_number, $address, $user_id);
                
                if (mysqli_stmt_execute($update_stmt)) {
                    // Update session data
                    $_SESSION['full_name'] = $full_name;
                    $_SESSION['email'] = $email;
                    
                    $message = 'Profile updated!';
                    $message_type = 'success';
                    
                    // Refresh user data
                    $user['full_name'] = $full_name;
                    $user['email'] = $email;
                    $user['contact_number'] = $contact_number;
                    $user['address'] = $address;
                } else {
                    $message = 'Error updating profile.';
                    $message_type = 'danger';
                }
                mysqli_stmt_close($update_stmt);
            }
            mysqli_stmt_close($check_stmt);
        }
    }
    
    // Handle password change
    elseif (isset($_POST['change_password'])) {
        $current_password = trim($_POST['current_password']);
        $new_password = trim($_POST['new_password']);
        $confirm_password = trim($_POST['confirm_password']);
        
        // Validate passwords
        if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
            $message = 'All fields required.';
            $message_type = 'danger';
        } elseif ($new_password !== $confirm_password) {
            $message = 'Passwords do not match.';
            $message_type = 'danger';
        } elseif (strlen($new_password) < 6) {
            $message = 'Password must be at least 6 characters.';
            $message_type = 'danger';
        } else {
            // Verify current password
            $check_sql = "SELECT password FROM users WHERE id = ?";
            $check_stmt = mysqli_prepare($conn, $check_sql);
            mysqli_stmt_bind_param($check_stmt, 'i', $user_id);
            mysqli_stmt_execute($check_stmt);
            mysqli_stmt_bind_result($check_stmt, $hashed_password);
            mysqli_stmt_fetch($check_stmt);
            mysqli_stmt_close($check_stmt);
            
            if (!password_verify($current_password, $hashed_password)) {
                $message = 'Current password incorrect.';
                $message_type = 'danger';
            } else {
                // Hash new password
                $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                
                // Update password
                $update_sql = "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?";
                $update_stmt = mysqli_prepare($conn, $update_sql);
                mysqli_stmt_bind_param($update_stmt, 'si', $new_hashed_password, $user_id);
                
                if (mysqli_stmt_execute($update_stmt)) {
                    $message = 'Password changed!';
                    $message_type = 'success';
                } else {
                    $message = 'Error changing password.';
                    $message_type = 'danger';
                }
                mysqli_stmt_close($update_stmt);
            }
        }
    }
    
    // Handle profile picture upload
    elseif (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == 0) {
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
        $max_file_size = 2 * 1024 * 1024; // 2MB
        
        $file_name = $_FILES['profile_picture']['name'];
        $file_tmp = $_FILES['profile_picture']['tmp_name'];
        $file_size = $_FILES['profile_picture']['size'];
        
        // Get file extension
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        // Validate file
        if (!in_array($file_ext, $allowed_extensions)) {
            $message = 'Only JPG, PNG, GIF allowed.';
            $message_type = 'danger';
        } elseif ($file_size > $max_file_size) {
            $message = 'File must be < 2MB.';
            $message_type = 'danger';
        } else {
            // Create uploads directory
            $upload_dir = '../uploads/profile_pictures/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Generate unique filename
            $new_filename = 'profile_' . $user_id . '_' . time() . '.' . $file_ext;
            $destination = $upload_dir . $new_filename;
            
            // Delete old profile picture
            if (!empty($user['profile_picture'])) {
                $old_file = '../' . $user['profile_picture'];
                if (file_exists($old_file)) {
                    @unlink($old_file);
                }
            }
            
            // Move uploaded file
            if (move_uploaded_file($file_tmp, $destination)) {
                // Update database
                $relative_path = 'uploads/profile_pictures/' . $new_filename;
                $update_sql = "UPDATE users SET profile_picture = ?, updated_at = NOW() WHERE id = ?";
                $update_stmt = mysqli_prepare($conn, $update_sql);
                mysqli_stmt_bind_param($update_stmt, 'si', $relative_path, $user_id);
                
                if (mysqli_stmt_execute($update_stmt)) {
                    $user['profile_picture'] = $relative_path;
                    $_SESSION['profile_picture'] = $relative_path;
                    $message = 'Profile picture updated!';
                    $message_type = 'success';
                } else {
                    $message = 'Error updating picture.';
                    $message_type = 'danger';
                }
                mysqli_stmt_close($update_stmt);
            } else {
                $message = 'Error uploading file.';
                $message_type = 'danger';
            }
        }
    }
}

include '../includes/header.php';
?>

<style>
/* Compact Styles */
body {
    background-color: #f8f9fa;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-size: 14px;
}

.container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 15px;
}

.profile-header {
    background:  #166b0e;
    color: white;
    padding: 15px;
    border-radius: 8px 8px 0 0;
}

.profile-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 15px;
    overflow: hidden;
}

.profile-picture-container {
    width: 100px;
    height: 100px;
    margin: 10px auto 10px;
    position: relative;
}

.profile-picture {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid white;
    box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.profile-picture-upload {
    position: absolute;
    bottom: 5px;
    right: 5px;
    background:  #166b0e;
    color: white;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 12px;
}

.stats-card {
    background: white;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    margin-bottom: 15px;
}

.info-item {
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    font-size: 13px;
}

.info-label {
    font-weight: 600;
    color: #6c757d;
    font-size: 12px;
    margin-bottom: 3px;
}

.info-value {
    font-size: 13px;
}

.badge-role {
    background:#cfee43;
    color: rgb(0, 0, 0);
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.form-control, .form-select {
    font-size: 13px;
    padding: 6px 10px;
    height: 35px;
}

.btn {
    font-size: 13px;
    padding: 6px 12px;
}

.btn-sm {
    padding: 4px 10px;
    font-size: 12px;
}

.table {
    font-size: 13px;
}

.table th {
    font-size: 12px;
    padding: 10px;
    background-color: #f8f9fa;
}

.table td {
    padding: 8px;
}

.badge {
    font-size: 11px;
    padding: 3px 8px;
}

.alert {
    padding: 8px 12px;
    font-size: 13px;
}

.modal-content {
    font-size: 13px;
}

.modal-header {
    padding: 12px 15px;
}

.modal-body {
    padding: 15px;
}

.modal-footer {
    padding: 10px 15px;
}

@media (max-width: 768px) {
    .container {
        padding: 10px;
    }
    
    .profile-header {
        padding: 12px;
    }
    
    .profile-picture-container {
        width: 80px;
        height: 80px;
        margin: -40px auto 8px;
    }
    
    .profile-picture-upload {
        width: 25px;
        height: 25px;
        font-size: 10px;
    }
}
</style>

<div class="container">
    <!-- Profile Header -->
    <div class="profile-header mb-3">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1 class="h4 mb-0">My Profile</h1>
                <small class="opacity-75">Manage account information</small>
            </div>
            <span class="badge-role">
                <i class="bi bi-shield-check me-1"></i> <?php echo htmlspecialchars(ucfirst($user['role'])); ?>
            </span>
        </div>
    </div>

    <!-- Message Alert -->
    <?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show mb-3 py-2" role="alert" style="font-size: 13px;">
        <i class="bi bi-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-1"></i>
        <?php echo $message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close" style="font-size: 10px;"></button>
    </div>
    <?php endif; ?>

    <!-- Profile Picture -->
    <div class="profile-card">
        <div class="text-center p-3">
            <div class="profile-picture-container">
                <?php if (!empty($user['profile_picture'])): ?>
                    <img src="../<?php echo htmlspecialchars($user['profile_picture']); ?>" 
                         alt="Profile" 
                         class="profile-picture">
                <?php else: ?>
                    <div class="profile-picture d-flex align-items-center justify-content-center bg-primary text-white">
                        <i class="bi bi-person" style="font-size: 40px;"></i>
                    </div>
                <?php endif; ?>
                
                <div class="profile-picture-upload" data-bs-toggle="modal" data-bs-target="#uploadModal">
                    <i class="bi bi-camera"></i>
                </div>
            </div>
            
            <h4 class="mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h4>
            <p class="text-muted mb-2"><?php echo htmlspecialchars($user['email']); ?></p>
            
            <div>
                <span class="badge bg-info me-1">
                    <i class="bi bi-person-badge"></i> ID: <?php echo $user_id; ?>
                </span>
                <span class="badge bg-secondary">
                    <i class="bi bi-calendar"></i> <?php echo date('M Y', strtotime($user['created_at'])); ?>
                </span>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <!-- Personal Information -->
        <div class="col-lg-8">
            <div class="profile-card">
                <div class="card-header bg-white border-bottom py-2">
                    <h6 class="mb-0"><i class="bi bi-person-lines-fill me-1"></i> Personal Information</h6>
                </div>
                <div class="card-body p-3">
                    <form method="POST" action="" id="profileForm">
                        <div class="row g-2">
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Full Name *</label>
                                <input type="text" class="form-control" name="full_name" 
                                       value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Email *</label>
                                <input type="email" class="form-control" name="email" 
                                       value="<?php echo htmlspecialchars($user['email']); ?>" required>
                            </div>
                            
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Contact</label>
                                <input type="tel" class="form-control" name="contact_number" 
                                       value="<?php echo htmlspecialchars($user['contact_number'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Address</label>
                                <input type="text" class="form-control" name="address" 
                                       value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>">
                            </div>
                            
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Username</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['username']); ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Created</label>
                                <input type="text" class="form-control" 
                                       value="<?php echo date('m/d/Y', strtotime($user['created_at'])); ?>" readonly>
                            </div>
                            
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Role</label>
                                <input type="text" class="form-control" 
                                       value="<?php echo htmlspecialchars(ucfirst($user['role'])); ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Status</label>
                                <input type="text" class="form-control" 
                                       value="<?php echo $user['status'] == 1 ? 'Active' : 'Inactive'; ?>" readonly>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center mt-3 pt-2 border-top">
                            <small class="text-muted">
                                Updated: <?php echo date('m/d/Y h:i A', strtotime($user['updated_at'])); ?>
                            </small>
                            <button type="submit" class="btn btn-primary btn-sm" name="update_profile">
                                <i class="bi bi-save me-1"></i> Save
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Change Password -->
            <div class="profile-card mt-3">
                <div class="card-header bg-white border-bottom py-2">
                    <h6 class="mb-0"><i class="bi bi-key-fill me-1"></i> Change Password</h6>
                </div>
                <div class="card-body p-3">
                    <form method="POST" action="" id="passwordForm">
                        <div class="row g-2">
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Current Password *</label>
                                <div class="input-group input-group-sm">
                                    <input type="password" class="form-control" name="current_password" id="current_password" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('current_password')">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label">New Password *</label>
                                <div class="input-group input-group-sm">
                                    <input type="password" class="form-control" name="new_password" id="new_password" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('new_password')">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Confirm Password *</label>
                                <div class="input-group input-group-sm">
                                    <input type="password" class="form-control" name="confirm_password" id="confirm_password" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirm_password')">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="alert alert-info py-2 mt-2 mb-2" style="font-size: 12px;">
                            <i class="bi bi-info-circle me-1"></i>
                            Password must be at least 6 characters
                        </div>
                        
                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-warning btn-sm" name="change_password">
                                <i class="bi bi-key me-1"></i> Change Password
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Account Stats -->
            <div class="stats-card">
                <div class="d-flex align-items-center mb-2">
                    <div class="bg-primary text-white rounded p-2 me-2">
                        <i class="bi bi-speedometer2"></i>
                    </div>
                    <h6 class="mb-0">Account Overview</h6>
                </div>
                
                <div class="info-item">
                    <div class="info-label">User ID</div>
                    <div class="info-value"><?php echo $user_id; ?></div>
                </div>
                
                <div class="info-item">
                    <div class="info-label">Role</div>
                    <div class="info-value"><?php echo htmlspecialchars(ucfirst($user['role'])); ?></div>
                </div>
                
                <div class="info-item">
                    <div class="info-label">Status</div>
                    <div class="info-value">
                        <?php if ($user['status'] == 1): ?>
                            <span class="badge bg-success">
                                <i class="bi bi-check-circle me-1"></i> Active
                            </span>
                        <?php else: ?>
                            <span class="badge bg-danger">
                                <i class="bi bi-x-circle me-1"></i> Inactive
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-label">Last Login</div>
                    <div class="info-value">
                        <?php 
                        $last_login = !empty($user['last_login']) ? date('m/d/Y h:i A', strtotime($user['last_login'])) : 'Never';
                        echo $last_login;
                        ?>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="stats-card mt-3">
                <div class="d-flex align-items-center mb-2">
                    <div class="bg-info text-white rounded p-2 me-2">
                        <i class="bi bi-lightning"></i>
                    </div>
                    <h6 class="mb-0">Quick Actions</h6>
                </div>
                
                <div class="d-grid gap-2">
                    <a href="dashboard.php" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-speedometer2 me-1"></i> Dashboard
                    </a>
                    <button class="btn btn-outline-success btn-sm" onclick="window.print()">
                        <i class="bi bi-printer me-1"></i> Print
                    </button>
                    <a href="../auth/logout.php" class="btn btn-outline-danger btn-sm">
                        <i class="bi bi-box-arrow-right me-1"></i> Logout
                    </a>
                </div>
            </div>

            <!-- Security Tips -->
            <div class="stats-card mt-3">
                <div class="d-flex align-items-center mb-2">
                    <div class="bg-warning text-white rounded p-2 me-2">
                        <i class="bi bi-shield-check"></i>
                    </div>
                    <h6 class="mb-0">Security Tips</h6>
                </div>
                
                <div style="font-size: 12px;">
                    <div class="mb-1">
                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                        Use strong password
                    </div>
                    <div class="mb-1">
                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                        Update regularly
                    </div>
                    <div class="mb-1">
                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                        Logout when done
                    </div>
                    <div>
                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                        Keep info updated
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h6 class="modal-title mb-0" id="uploadModalLabel">
                    <i class="bi bi-camera me-1"></i> Upload Photo
                </h6>
                <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 py-2">
                    <div class="alert alert-info py-1 mb-2" style="font-size: 11px;">
                        <i class="bi bi-info-circle me-1"></i>
                        JPG, PNG, GIF (Max 2MB)
                    </div>
                    
                    <div class="mb-2">
                        <label for="profile_picture" class="form-label">Select Image</label>
                        <input type="file" class="form-control form-control-sm" id="profile_picture" name="profile_picture" accept="image/*">
                    </div>
                    
                    <div class="preview-container text-center mt-2" style="display: none;">
                        <img id="imagePreview" class="img-fluid rounded" style="max-height: 150px;">
                    </div>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm">Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php 
$page_scripts = '
<script>
// Toggle password visibility
function togglePassword(fieldId) {
    const field = document.getElementById(fieldId);
    const type = field.getAttribute("type") === "password" ? "text" : "password";
    field.setAttribute("type", type);
}

// Image preview
document.getElementById("profile_picture").addEventListener("change", function(e) {
    const preview = document.getElementById("imagePreview");
    const previewContainer = document.querySelector(".preview-container");
    
    if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            previewContainer.style.display = "block";
        }
        reader.readAsDataURL(this.files[0]);
    } else {
        previewContainer.style.display = "none";
    }
});

// Form validation
document.getElementById("profileForm").addEventListener("submit", function(e) {
    const email = this.querySelector("input[name=\'email\']").value;
    if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {
        e.preventDefault();
        alert("Invalid email address.");
        return false;
    }
    return true;
});

document.getElementById("passwordForm").addEventListener("submit", function(e) {
    const newPassword = this.querySelector("input[name=\'new_password\']").value;
    const confirmPassword = this.querySelector("input[name=\'confirm_password\']").value;
    
    if (newPassword.length < 6) {
        e.preventDefault();
        alert("Password must be at least 6 characters.");
        return false;
    }
    
    if (newPassword !== confirmPassword) {
        e.preventDefault();
        alert("Passwords do not match.");
        return false;
    }
    
    return true;
});
</script>
';

include '../includes/footer.php';
?>