File "profile.php"

Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/dashboard/profile.php
File size: 8.59 B (8.59 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor   Back

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

// Require login
requireLogin();

$user = getCurrentUser();
if (!$user) {
    redirect('/auth/login.php');
}


error_log('Profile access - User ID: ' . ($_SESSION['user_id'] ?? 'NOT SET'));
error_log('Profile access - User Type: ' . ($_SESSION['user_type'] ?? 'NOT SET'));
error_log('Profile access - User data: ' . json_encode($user));

$errors = [];
$successMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log('Profile form submitted - POST data: ' . json_encode($_POST));
    
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        error_log('Profile form - CSRF validation failed');
        $errors[] = 'Invalid request. Please try again.';
    } else {
        error_log('Profile form - CSRF validation passed');
        $name = sanitizeInput($_POST['name'] ?? '');
        $phone = sanitizeInput($_POST['phone'] ?? '');
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        error_log('Profile form - Processed data - Name: ' . $name . ', Phone: ' . $phone . ', Has Password: ' . (!empty($newPassword) ? 'YES' : 'NO'));

        if ($name === '') {
            $errors[] = 'Name is required.';
        }

        if ($phone !== '' && !validatePhone($phone)) {
            $errors[] = 'Please enter a valid phone number.';
        }

        $shouldUpdatePassword = $newPassword !== '' || $confirmPassword !== '';
        if ($shouldUpdatePassword) {
            if (!validatePassword($newPassword)) {
                $errors[] = 'New password must be at least 8 characters long and contain uppercase, lowercase, and number.';
            }
            if ($newPassword !== $confirmPassword) {
                $errors[] = 'New password and confirmation do not match.';
            }
        }

        if (empty($errors)) {
            try {
                $db = Database::getInstance();
                
                // Map user type to table name
                $tableMap = [
                    'auto_owner' => 'auto_owners',
                    'passenger' => 'passengers',
                    'operator' => 'operators',
                    'validator' => 'validators',
                    'admin' => 'admins',
                    'super_admin' => 'super_admins'
                ];
                
                $tableName = $tableMap[$_SESSION['user_type']] ?? null;
                if (!$tableName) {
                    error_log('Profile update - Invalid user type: ' . $_SESSION['user_type']);
                    throw new Exception('Invalid user type');
                }
                
                error_log('Profile update - Using table: ' . $tableName . ' for user ID: ' . $user['id']);

                if ($shouldUpdatePassword) {
                    error_log('Profile update - Updating with password');
                    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                    $db->query(
                        "UPDATE $tableName SET name = ?, phone = ?, password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                        [$name, $phone, $hashedPassword, $user['id']]
                    );
                } else {
                    error_log('Profile update - Updating without password');
                    $db->query(
                        "UPDATE $tableName SET name = ?, phone = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                        [$name, $phone, $user['id']]
                    );
                }
                
                error_log('Profile update - Database update completed successfully');

                // Refresh user in session variables
                $updatedUser = $db->fetch("SELECT * FROM $tableName WHERE id = ?", [$user['id']]);
                if ($updatedUser) {
                    $_SESSION['user_name'] = $updatedUser['name'];
                    $_SESSION['user_email'] = $updatedUser['email'];
                }

                $_SESSION['flash_message'] = 'Profile updated successfully.';
                $_SESSION['flash_type'] = 'success';

                // Reload page to show updated info and clear POST
                redirect('/dashboard/profile.php');
            } catch (Exception $e) {
                logError('Profile update error: ' . $e->getMessage());
                $errors[] = 'Failed to update profile. Please try again.';
            }
        }
    }
}

$pageTitle = 'Your Profile';
require_once '../includes/header.php';
?>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header">
                    <h5 class="mb-0">Account Profile</h5>
                    <small class="text-muted">
                        User Type: <?php echo ucfirst(str_replace('_', ' ', $_SESSION['user_type'])); ?> | 
                        User ID: <?php echo $_SESSION['user_id']; ?>
                    </small>
                </div>
                <div class="card-body">
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

                        <div class="mb-3">
                            <label class="form-label">Email (read-only)</label>
                            <input type="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" readonly>
                            <small class="text-muted">Email address cannot be changed for security reasons.</small>
                        </div>

                        <div class="mb-3">
                            <label for="name" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($_POST['name'] ?? $user['name']); ?>" 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($_POST['phone'] ?? ($user['phone'] ?? '')); ?>" placeholder="Optional">
                        </div>

                        <?php if (isBackendUser()): ?>
                        <div class="mb-3">
                            <label class="form-label">Status (read-only)</label>
                            <input type="text" class="form-control" value="<?php echo ucfirst(str_replace('_', ' ', $user['status'] ?? 'active')); ?>" readonly>
                            <small class="text-muted">Account status can only be changed by administrators.</small>
                        </div>
                        <?php endif; ?>

                        <hr>
                        <p class="text-muted mb-3">Change Password (optional)</p>

                        <div class="mb-3">
                            <label for="new_password" class="form-label">New Password</label>
                            <input type="password" class="form-control" id="new_password" name="new_password" placeholder="Leave blank to keep current password">
                        </div>

                        <div class="mb-3">
                            <label for="confirm_password" class="form-label">Confirm New Password</label>
                            <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Re-enter new password">
                        </div>

                        <div class="d-flex justify-content-end gap-2">
                            <a href="<?php echo url_for('dashboard/'); ?>" class="btn btn-outline-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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