# LIVE SERVER FIX GUIDE - Password Change Feature

**Current Error**: `View [client.change-password] not found`
**Root Cause**: Blade view file placed in wrong directory on live server
**Status**: IN PROGRESS - File structure is correct locally, needs fixing on live

---

## CRITICAL FILE STRUCTURE

The view file MUST be in this exact location on the live server:
```
/home/dextragr/public_html/will/resources/views/client/change-password.blade.php
```

NOT in any other location. The Blade template engine looks for files in `resources/views/` with the dot notation `client.change-password` mapping to:
- Directory: `resources/views/client/`
- File: `change-password.blade.php` (with .blade.php extension)

---

## ALL FILES THAT NEED TO BE ON LIVE SERVER

### 1. **Database Migration** (NEW)
**Location**: `database/migrations/2026_09_01_141422_add_password_changed_to_users.php`
**Action**: Copy to live server

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('password_changed_at')->nullable()->after('password');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('password_changed_at');
        });
    }
};
```

---

### 2. **Middleware** (NEW)
**Location**: `app/Http/Middleware/CheckPasswordChanged.php`
**Action**: Copy to live server

```php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPasswordChanged
{
    public function handle(Request $request, Closure $next): Response
    {
        // Only apply to client role
        if (auth()->check() && auth()->user()->role === 'client') {
            // If password has never been changed (password_changed_at is null), redirect to password change
            if (is_null(auth()->user()->password_changed_at)) {
                // Don't redirect if already on password change page
                if (!$request->is('client/change-password*')) {
                    return redirect()->route('client.change-password')->with('warning', 'For your security, please change your password on first login.');
                }
            }
        }

        return $next($request);
    }
}
```

---

### 3. **View Template** (NEW) - **⚠️ CRITICAL: This is the file causing the error**
**Location**: `resources/views/client/change-password.blade.php`
**Action**: Copy to live server (verify exact directory)

**File Size**: ~10KB (Blade template with form, validation, and JavaScript)

---

### 4. **Controller** (UPDATED)
**Location**: `app/Http/Controllers/ClientController.php`
**Action**: Update existing file - Add 2 methods

**Methods to add at line 4373 (around end of file, before closing brace)**:

```php
    /**
     * Show password change form
     */
    public function showChangePassword()
    {
        return view('client.change-password');
    }

    /**
     * Update password
     */
    public function updatePassword(Request $request)
    {
        $user = auth()->user();

        // Validate input
        $validated = $request->validate([
            'current_password' => 'required|current_password',
            'password' => 'required|string|min:8|regex:/[A-Z]/|regex:/[a-z]/|regex:/[0-9]/|confirmed',
            'password_confirmation' => 'required',
        ]);

        // Update password
        $user->update([
            'password' => bcrypt($validated['password']),
            'password_changed_at' => now(),
        ]);

        // Log the password change
        \Log\Activity::create([
            'user_id' => $user->id,
            'action' => 'Password changed',
            'module' => 'Auth',
            'description' => 'Client changed password',
        ]);

        return redirect()->route('client.dashboard')->with('success', 'Password changed successfully!');
    }
```

---

### 5. **Model** (UPDATED)
**Location**: `app/Models/User.php`
**Action**: Update existing file - Add 2 locations

**Location 1 - Fillable Array** (around line 30):
Add `'password_changed_at'` to the fillable array:
```php
protected $fillable = [
    'name',
    'email',
    'password',
    'password_changed_at',  // ADD THIS
    'role',
    'phone',
    'status',
    // ... other fields
];
```

**Location 2 - Casts Array** (around line 45):
Add to casts:
```php
protected $casts = [
    'email_verified_at' => 'datetime',
    'password_changed_at' => 'datetime',  // ADD THIS
    // ... other casts
];
```

---

### 6. **Routes** (UPDATED)
**Location**: `routes/web.php`
**Action**: Update existing file - Add 2 routes (around line 1105)

Add these routes inside the client middleware group:
```php
    // Password Change Routes - Mandatory on first login
    Route::get('/change-password', [ClientController::class, 'showChangePassword'])->name('client.change-password');
    Route::post('/change-password', [ClientController::class, 'updatePassword'])->name('client.update-password');
```

---

## STEP-BY-STEP DEPLOYMENT COMMANDS

### Step 1: Find the misplaced file
```bash
find /home/dextragr/public_html/will -name "change-password.blade.php" -type f
```
This will show you where the file currently is.

### Step 2: Remove it from wrong location (if found)
```bash
rm /path/to/wrong/location/change-password.blade.php
```

### Step 3: Ensure correct directory exists
```bash
mkdir -p /home/dextragr/public_html/will/resources/views/client
```

### Step 4: Copy the view file to correct location
If uploading via FTP/File Manager:
- Ensure file goes to: `public_html/will/resources/views/client/change-password.blade.php`

### Step 5: Run the database migration
```bash
cd /home/dextragr/public_html/will
php artisan migrate
```

If the migration already ran, you can skip this. To check:
```bash
php artisan migrate:status
```

### Step 6: Clear Laravel cache
```bash
cd /home/dextragr/public_html/will
php artisan view:clear
php artisan cache:clear
php artisan config:clear
php artisan optimize
```

### Step 7: Test the feature
1. Go to: `https://will.dextragroups.com/client/login`
2. Login with a client account (IC number as password)
3. Should redirect to: `https://will.dextragroups.com/client/change-password`
4. Should see the password change form

---

## DIRECT SQL ALTERNATIVE (If migration fails)

If you cannot run `php artisan migrate`, execute this SQL directly:

```sql
ALTER TABLE users ADD COLUMN password_changed_at TIMESTAMP NULL DEFAULT NULL AFTER password;

INSERT INTO migrations (migration, batch) 
VALUES ('2026_09_01_141422_add_password_changed_to_users', 1)
ON DUPLICATE KEY UPDATE batch=1;
```

Run this in your database using phpMyAdmin or command line:
```bash
mysql -u username -p database_name < migrations.sql
```

---

## VERIFICATION CHECKLIST

After deployment, verify each file:

- [ ] `resources/views/client/change-password.blade.php` exists (NOT in any other location)
- [ ] `app/Http/Middleware/CheckPasswordChanged.php` exists
- [ ] `database/migrations/2026_09_01_141422_add_password_changed_to_users.php` exists
- [ ] `app/Http/Controllers/ClientController.php` contains 2 new methods
- [ ] `app/Models/User.php` has `password_changed_at` in fillable and casts
- [ ] `routes/web.php` has 2 new routes registered
- [ ] `password_changed_at` column exists in users table
- [ ] Laravel cache cleared
- [ ] Login test successful - redirects to password change form

---

## FILE PERMISSIONS

Ensure these permissions are correct:

```bash
# View files should be readable
chmod 644 /home/dextragr/public_html/will/resources/views/client/change-password.blade.php

# PHP files should be readable
chmod 644 /home/dextragr/public_html/will/app/Http/Middleware/CheckPasswordChanged.php
chmod 644 /home/dextragr/public_html/will/app/Http/Controllers/ClientController.php
chmod 644 /home/dextragr/public_html/will/app/Models/User.php
chmod 644 /home/dextragr/public_html/will/routes/web.php
```

---

## ERROR MESSAGES & SOLUTIONS

### Error: "View [client.change-password] not found"
- **Cause**: View file in wrong directory
- **Solution**: Move file to `resources/views/client/change-password.blade.php`
- **Verify**: Check file exists at correct path
- **Then**: Run `php artisan view:clear`

### Error: "Column 'password_changed_at' doesn't exist in where clause"
- **Cause**: Migration not run
- **Solution**: Run `php artisan migrate` OR execute direct SQL
- **Verify**: Check column exists: `DESCRIBE users;`

### Error: "Route [client.change-password] not defined"
- **Cause**: Routes not added to web.php
- **Solution**: Add routes to `routes/web.php` inside client group
- **Then**: Run `php artisan route:clear`

### Error: "Class CheckPasswordChanged not found"
- **Cause**: Middleware file missing or not registered
- **Solution**: Ensure middleware exists and `routes/web.php` uses it
- **Verify**: Check file exists at `app/Http/Middleware/CheckPasswordChanged.php`

---

## SUMMARY

**What Changed**:
- Added mandatory password change on first client login
- Client logs in with IC number, redirected to password change form
- After changing password, they can access the portal normally

**Files Modified**: 6
- 3 new files (Migration, Middleware, View)
- 3 updated files (Controller, Model, Routes)

**Database Changes**: 1
- Added `password_changed_at` column to users table

**Live Server Status**: FIXING
- View file is in wrong location ← **FIX THIS FIRST**
- Run cache clear after moving file
- Run migration if not already run
- Test login
