# Code Implementation Guide

## Overview
This guide explains the code structure and how the authentication system works in the header.

---

## 1. TOP BAR AUTHENTICATION HTML

### Location: `header.html` (Lines 354-360)

```html
<!-- Authentication Buttons in Top Bar -->
<?php if (isset($_SESSION['user_id'])): ?>
    <!-- USER IS LOGGED IN -->
    <li class="topbar-user-menu">
        <div class="dropdown dropdown-hover">
            <button class="topbar-user-btn dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="fas fa-user-circle"></i> <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'User'); ?>
            </button>
            <ul class="dropdown-menu dropdown-menu-end" style="background: #1a1f3a; border: 1px solid var(--primary);">
                <li><a class="dropdown-item" href="member-dashboard.php" style="color: #fff;"><i class="fas fa-chart-line"></i> Dashboard</a></li>
                <li><hr class="dropdown-divider" style="border-color: rgba(255,255,255,0.2);"></li>
                <li><a class="dropdown-item" href="auth/logout.php" style="color: #ff5e14;"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
            </ul>
        </div>
    </li>
<?php else: ?>
    <!-- USER IS NOT LOGGED IN -->
    <li><button type="button" class="topbar-btn-login" data-bs-toggle="modal" data-bs-target="#loginModal">Login</button></li>
    <li><button type="button" class="topbar-btn-register" data-bs-toggle="modal" data-bs-target="#registerModal">Register</button></li>
<?php endif; ?>
```

### How It Works:
1. **PHP Check**: `isset($_SESSION['user_id'])` checks if user is logged in
2. **If Logged In**: Shows user profile dropdown with options
3. **If Not Logged In**: Shows Login and Register buttons that trigger modals

---

## 2. CSS STYLES FOR TOP BAR BUTTONS

### Location: `header.html` (Lines 507-583)

```css
/* ===== Top Bar Authentication Styles ===== */
.topbar-btn-login,
.topbar-btn-register {
    padding: 8px 16px;
    border: none;
    border-radius: 5px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 13px;
    display: inline-block;
}

/* LOGIN BUTTON - Outline Style */
.topbar-btn-login {
    background-color: transparent;
    color: #ff5e14;
    border: 1px solid #ff5e14;
    margin-right: 8px;
}

.topbar-btn-login:hover {
    background-color: #ff5e14;
    color: white;
    transform: translateY(-2px);
}

/* REGISTER BUTTON - Solid Style */
.topbar-btn-register {
    background-color: #ff5e14;
    color: #fff;
}

.topbar-btn-register:hover {
    background-color: #ff7f3f;
    transform: translateY(-2px);
}

/* USER PROFILE MENU */
.topbar-user-menu {
    margin-left: 10px !important;
}

.topbar-user-btn {
    background: transparent;
    border: none;
    color: #ff5e14;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.3s ease;
    padding: 8px 12px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.topbar-user-btn:hover {
    color: #ff7f3f;
}
```

### Style Breakdown:
- **Padding**: 8px top/bottom, 16px left/right
- **Font Size**: 13px (smaller than main header buttons)
- **Transition**: 0.3s ease for smooth animations
- **Hover Effect**: Lift animation + color change
- **Border Radius**: 5px for slightly rounded corners

---

## 3. RESPONSIVE STYLES

### Location: `header.html` (Lines 718-725)

```css
/* Responsive topbar buttons on mobile */
@media (max-width: 991px) {
    .topbar-btn-login,
    .topbar-btn-register,
    .topbar-user-menu {
        display: none !important;
    }

    .mobile-auth-buttons,
    .mobile-user-profile {
        display: none !important;
        position: relative !important;
    }
}
```

### Mobile Behavior:
- Buttons hide from top bar on mobile (< 992px)
- Mobile auth buttons appear in the mobile menu instead
- Mobile user profile shows in mobile menu when logged in

---

## 4. MODAL SCRIPTS

### Login Modal

```html
<!-- Login Modal -->
<div class="modal fade auth-modal" id="loginModal" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 450px;">
        <div class="modal-content">
            <div class="modal-header d-flex justify-content-between align-items-center">
                <h5 class="modal-title" id="loginModalLabel">Welcome Back</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="loginForm" method="POST" action="auth/login.php">
                    <div class="form-group">
                        <label class="form-label">Email Address</label>
                        <input type="email" name="email" class="form-control" placeholder="Enter your email" required>
                    </div>
                    <div class="form-group password-toggle">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" placeholder="Enter your password" required>
                        <button type="button" class="toggle-password" onclick="togglePassword(this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="form-check d-flex align-items-center">
                        <input class="form-check-input" type="checkbox" id="rememberLogin">
                        <label class="form-check-label" for="rememberLogin">Remember me</label>
                    </div>
                    <button type="submit" class="btn btn-primary mt-3">Login Now</button>
                </form>
                <div class="toggle-form">
                    Don't have an account? <a onclick="switchToRegister()">Create one</a>
                </div>
            </div>
        </div>
    </div>
</div>
```

### Register Modal
```html
<!-- Register Modal -->
<div class="modal fade auth-modal" id="registerModal" tabindex="-1" aria-labelledby="registerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 450px;">
        <div class="modal-content">
            <div class="modal-header d-flex justify-content-between align-items-center">
                <h5 class="modal-title" id="registerModalLabel">Create Account</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="registerForm" method="POST" action="auth/register.php">
                    <div class="form-group">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Email Address</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" name="phone" class="form-control" required>
                    </div>
                    <div class="form-group password-toggle">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" required>
                        <button type="button" class="toggle-password" onclick="togglePassword(this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="form-group password-toggle">
                        <label class="form-label">Confirm Password</label>
                        <input type="password" name="confirm_password" class="form-control" required>
                        <button type="button" class="toggle-password" onclick="togglePassword(this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <button type="submit" class="btn btn-primary mt-3">Create Account</button>
                </form>
                <div class="toggle-form">
                    Already have an account? <a onclick="switchToLogin()">Login here</a>
                </div>
            </div>
        </div>
    </div>
</div>
```

---

## 5. JAVASCRIPT FUNCTIONALITY

### AJAX Form Submission (Login)

```javascript
document.getElementById('loginForm')?.addEventListener('submit', function(e) {
    e.preventDefault();

    const form = this;
    const formData = new FormData(form);

    fetch(form.action, {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(response => {
        if (response.status === 'success') {
            Swal.fire({
                icon: 'success',
                title: 'Welcome Back 💪',
                text: response.message,
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                window.location.href = response.redirect;
            });
        } else {
            Swal.fire('Login Failed', response.message, 'error');
        }
    })
    .catch(err => {
        Swal.fire('Error', 'Network error. Please try again.', 'error');
    });
});
```

### AJAX Form Submission (Register)

```javascript
document.getElementById('registerForm')?.addEventListener('submit', function(e) {
    e.preventDefault();

    const form = this;
    const formData = new FormData(form);

    fetch(form.action, {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(response => {
        if (response.status === 'success') {
            Swal.fire({
                icon: 'success',
                title: 'Account Created 🎉',
                text: response.message || 'You are now logged in',
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                window.location.href = response.redirect;
            });
        } else {
            Swal.fire('Error', response.message || 'Something went wrong', 'error');
        }
    })
    .catch(err => {
        Swal.fire('Error', 'Network error. Please try again.', 'error');
    });
});
```

### Password Toggle Function

```javascript
function togglePassword(button) {
    const input = button.previousElementSibling;
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}
```

### Modal Switching Functions

```javascript
function switchToLogin() {
    const registerModal = bootstrap.Modal.getInstance(document.getElementById('registerModal'));
    const loginModal = new bootstrap.Modal(document.getElementById('loginModal'));
    registerModal.hide();
    setTimeout(() => loginModal.show(), 300);
}

function switchToRegister() {
    const loginModal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
    const registerModal = new bootstrap.Modal(document.getElementById('registerModal'));
    loginModal.hide();
    setTimeout(() => registerModal.show(), 300);
}
```

### Mobile Menu Authentication Handler

```javascript
function updateMobileMenuAuth() {
    // Only update on mobile/tablet screens (max-width: 991px)
    if (window.innerWidth > 991) {
        return; // Don't show mobile menu on desktop
    }

    const mobileAuthButtons = document.getElementById('mobileAuthButtons');
    const mobileUserProfile = document.getElementById('mobileUserProfile');
    const mobileUserName = document.getElementById('mobileUserName');

    if (!mobileAuthButtons || !mobileUserProfile) {
        return;
    }

    // Check if user is logged in via PHP session check
    const isLoggedIn = document.body.getAttribute('data-user-logged-in') === 'true';
    const userName = document.body.getAttribute('data-user-name') || 'User';

    if (isLoggedIn) {
        mobileAuthButtons.classList.remove('show');
        mobileUserProfile.classList.add('show');
        mobileUserName.textContent = userName;
    } else {
        mobileAuthButtons.classList.add('show');
        mobileUserProfile.classList.remove('show');
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    updateMobileMenuAuth();

    // Close mobile menu when link is clicked
    const mobileMenuLinks = document.querySelectorAll('.header-nav a, .mobile-user-menu a');
    const navbarCollapse = document.getElementById('navbarNavDropdown');
    
    mobileMenuLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (navbarCollapse && navbarCollapse.classList.contains('show')) {
                const bsCollapse = new bootstrap.Collapse(navbarCollapse, {
                    toggle: false
                });
                bsCollapse.hide();
            }
        });
    });
});

// Re-check on window resize
window.addEventListener('resize', function() {
    updateMobileMenuAuth();
});
```

---

## 6. AUTH FILES EXPECTED

Your authentication files should be in `/auth/` folder:

### `/auth/login.php`
```php
<?php
session_start();
header('Content-Type: application/json');

$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

// Validate credentials
if ($email && $password) {
    // Check against database
    // If success:
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_name'] = $user['full_name'];
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Login successful',
        'redirect' => 'member-dashboard.php'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid email or password'
    ]);
}
?>
```

### `/auth/register.php`
```php
<?php
session_start();
header('Content-Type: application/json');

$full_name = $_POST['full_name'] ?? '';
$email = $_POST['email'] ?? '';
$phone = $_POST['phone'] ?? '';
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

// Validate input
if ($full_name && $email && $password === $confirm_password) {
    // Insert into database
    // If success:
    $_SESSION['user_id'] = $newUserId;
    $_SESSION['user_name'] = $full_name;
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Registration successful',
        'redirect' => 'member-dashboard.php'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid input or passwords do not match'
    ]);
}
?>
```

### `/auth/logout.php`
```php
<?php
session_start();
session_destroy();
header('Location: ../index.php');
?>
```

---

## 7. SESSION MANAGEMENT

### In any page that uses the header:

```php
<?php
session_start();

// Check if user is logged in
if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    $user_name = $_SESSION['user_name'];
    // User is logged in
} else {
    // User is not logged in
}

// Include header
include 'header.html';
?>
```

---

## 8. DATABASE SCHEMA (Example)

```sql
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    phone VARCHAR(20) NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```

---

## 9. KEY DIFFERENCES FROM OLD IMPLEMENTATION

| Aspect | Before | After |
|--------|--------|-------|
| **Auth Location** | Sticky Header | Top Bar (Contact Strip) |
| **Button Style** | Multiple variants | Consistent topbar style |
| **Visibility** | Always visible on desktop | Hidden on mobile (<992px) |
| **User Profile** | Dropdown in sticky header | Dropdown in top bar |
| **Mobile Auth** | Mobile menu buttons | Same mobile menu buttons |
| **Sticky Header** | Had auth buttons | Cleaner - no auth buttons |
| **Get Appointment** | Moved around | Now clearly visible in sticky header |

---

## 10. TROUBLESHOOTING CODE ISSUES

### Issue: Buttons don't show

```javascript
// Debug in console
console.log('Session user_id:', document.body.getAttribute('data-user-logged-in'));
console.log('Session user_name:', document.body.getAttribute('data-user-name'));
```

### Issue: Login doesn't work

```javascript
// Check AJAX response
fetch('auth/login.php', {
    method: 'POST',
    body: new FormData(document.getElementById('loginForm'))
})
.then(res => res.json())
.then(data => console.log(data)); // Check response
```

### Issue: Mobile buttons don't appear

```javascript
// Check if function runs
console.log('Window width:', window.innerWidth);
updateMobileMenuAuth(); // Manually trigger
```

---

This code guide provides all the necessary implementation details for the new header authentication system!
