# Comprehensive Remediation Plan for Elhamd-Laravel

## Execution Task List (Live)

- [x] Phase 0 - Baseline and Safety Gates
  - [x] Capture baseline outputs (`php artisan route:list`, `php artisan test`, `vendor/bin/pint --test`)
  - [x] Apply temporary and permanent risk controls in routes and uploads
  - [x] Mark phase complete
- [x] Phase 1 - Critical Security Remediation
  - [x] Sanctum guard and API auth hardening
  - [x] Least-privilege admin authorization with module abilities
  - [x] Payment integrity validation + transactional locking
  - [x] Upload hardening (no SVG + strict MIME/size + secure disk)
  - [x] Social links hardening and safe rendering
  - [x] Hardcoded secret scan and env extraction
  - [x] Mark phase complete
- [x] Phase 2 - Route and Controller Contract Alignment
  - [x] Fix undefined route action bindings
  - [x] Constrain `Route::resource` to implemented methods
  - [x] Canonicalize route names used by controllers/views/tests
  - [x] Mark phase complete
- [x] Phase 3 - Domain Logic Corrections
  - [x] Employee-centric HR relation/column corrections
  - [x] Warranty customer derivation via contract linkage
  - [x] Support comments relation/column alignment
  - [x] Branch manager relation + `User::isEmployee()` role alignment
  - [x] Mark phase complete
- [x] Phase 4 - Performance and Scalability
  - [x] Eager loading for critical public/customer pages
  - [x] Remove DB queries from Blade templates
  - [x] Cache site settings + invalidation on updates
  - [x] Queue slow operations (notifications/PDF/sitemap)
  - [x] Search optimization guardrails
  - [x] Mark phase complete
- [x] Phase 5 - Code Quality and Reliability
  - [x] Convert unsafe write flows to FormRequests + `validated()`
  - [x] Fix `LogsActivity` changed-fields logic
  - [x] Add/confirm CI gates (tests + pint + static analysis-ready workflow)
  - [x] Harden seeders against weak default credentials
  - [x] Mark phase complete

## Phase Completion Log

1. Phase 0 completed on February 17, 2026.
2. Phase 1 completed on February 17, 2026.
3. Phase 2 completed on February 17, 2026.
4. Phase 3 completed on February 17, 2026.
5. Phase 4 completed on February 17, 2026.
6. Phase 5 completed on February 17, 2026.

## Summary
This plan addresses every finding from the audit in strict order: security first, then route/domain correctness, then performance, then quality hardening. It is split into six phases with explicit file targets, implementation decisions, and acceptance criteria so implementation is decision-complete.

## Phase 0: Baseline and Safety Gates
1. Capture a baseline with `php artisan route:list`, `php artisan test`, and `vendor/bin/pint --test`; store outputs for before/after comparison.
2. Add temporary risk controls: restrict payment write routes to finance-capable roles in `routes/web.php` and disable SVG acceptance path in `app/Http/Controllers/Admin/SystemController.php` until hardening lands.
3. Phase completion criteria: baseline documented and temporary controls active.

## Phase 1: Critical Security Remediation
1. Fix API auth in `config/auth.php`, `routes/api.php`, `app/Models/User.php`, and `bootstrap/app.php`; define and enable a working Sanctum guard and ensure protected API routes stay behind `auth:sanctum`. Acceptance: unauthenticated requests return 401; valid tokens pass.
2. Replace broad admin access with least privilege in `routes/web.php`, `app/Http/Middleware/AdminMiddleware.php`, `app/Enums/UserRole.php`, and `app/Providers/AppServiceProvider.php`; enforce module-level abilities (`users.manage`, `finance.manage`, `content.manage`, `support.manage`, `hr.manage`) via `can:` middleware per route group. Acceptance: unauthorized roles get 403 per module.
3. Enforce payment integrity in `app/Http/Controllers/Admin/FinanceController.php`, `app/Services/FinanceService.php`, and new FormRequests `app/Http/Requests/Admin/Finance/StorePaymentRequest.php` and `app/Http/Requests/Admin/Finance/UpdatePaymentRequest.php`; validate invoice-customer ownership, positive amount, and amount <= outstanding; write in transaction with `lockForUpdate()`. Acceptance: cross-customer payment, overpayment, and race-condition duplicates are blocked.
4. Harden uploads in `app/Http/Controllers/Admin/SystemController.php` and `config/filesystems.php`; disallow SVG, enforce MIME+extension+size checks, store sensitive files on non-public disk, and serve sensitive assets via signed URLs. Acceptance: SVG and MIME-mismatch payloads are rejected.
5. Harden social links in `app/Http/Controllers/Admin/CMSController.php` and `resources/views/components/public-footer.blade.php`; enforce whitelist keys and `https://` URLs, normalize links, and render with `rel="noopener noreferrer nofollow"`. Acceptance: malformed URLs are rejected; safe URLs render correctly.
6. Remove hardcoded secrets by scanning tracked files, moving values to env, updating `.env.example`, and rotating exposed keys. Acceptance: no credentials remain in code.

## Phase 2: Route and Controller Contract Alignment
1. Resolve undefined route actions in `routes/web.php` by aligning method names with implemented controller methods for accounting/admin routes. Acceptance: no invalid action references.
2. Restrict resource routes in `routes/web.php` and `routes/api.php` with `->only([...])` to implemented actions, adding missing actions only where required by business flow. Acceptance: no generated routes target missing methods.
3. Canonicalize route names used across `resources/views/**`, `app/Http/Controllers/**`, and tests, including known mismatches around finance invoices, FAQs, company-info, and support show routes. Acceptance: no runtime “Route [x] not defined”.

## Phase 3: Domain Logic Corrections
1. Standardize HR on employee-centric schema in `app/Models/**`, `app/Http/Controllers/Admin/HR/**`, and migrations; fix relation keys (`employee_id` vs `user_id`) and column assumptions. Acceptance: HR flows run without relation/column errors.
2. Fix warranty logic in `app/Http/Controllers/Customer/WarrantyController.php`, `app/Models/Warranty.php`, and related claim models/migrations; derive customer through contract linkage and persist claims with valid FKs. Acceptance: warranty claim create/read works against real data.
3. Fix support logic in `app/Http/Controllers/Customer/SupportController.php` and support models; align relations and columns to `author_id` and `content`. Acceptance: ticket comments persist and render with correct author.
4. Add missing branch manager relation in `app/Models/Branch.php` and align `isEmployee()` role logic in `app/Models/User.php` with `app/Enums/UserRole.php`. Acceptance: branch and role-based redirects behave consistently.

## Phase 4: Performance and Scalability
1. Remove N+1 issues by eager loading in public/customer controllers serving home, vehicle, test-drive, and support pages. Acceptance: query counts are bounded and reduced.
2. Remove DB calls from Blade templates, especially `resources/views/components/public-footer.blade.php` and `resources/views/admin/finance/invoices/create.blade.php`; move data fetching to controllers/composers/services. Acceptance: no direct model queries in Blade.
3. Cache site settings in `app/Providers/AppServiceProvider.php` and invalidate on settings updates from admin system/CMS actions. Acceptance: repeated renders avoid repeated settings query.
4. Queue slow operations by moving notifications, PDF generation, and sitemap generation to jobs with `ShouldQueue`. Acceptance: web response latency drops for those flows.
5. Optimize search endpoints with indexes and throttling for high-cost wildcard queries. Acceptance: improved response time under concurrent load.

## Phase 5: Code Quality and Reliability
1. Replace unsafe payload handling by adopting FormRequests and `validated()` in write controllers; remove `$request->all()` paths and tighten model mass assignment settings. Acceptance: all write endpoints use explicit validated data.
2. Fix activity logging bug in `app/Traits/LogsActivity.php` by using changed keys from dirty attributes correctly. Acceptance: audit logs reflect correct old/new field diffs.
3. Enforce PSR-12 and static checks with Pint + test + static analysis CI gates. Acceptance: CI blocks noncompliant merges.
4. Harden seeders in `database/seeders/**` by removing predictable credentials and limiting demo credentials to local/dev contexts. Acceptance: no weak production-seeded passwords.

## Public API, Interface, and Type Changes
1. Protected API endpoints now strictly require valid Sanctum tokens.
2. Finance payment endpoints return 422 for ownership/overpayment violations with consistent error payloads.
3. Route-name contracts become canonical; internal references update to canonical names; compatibility aliases only where external consumers require them.
4. New typed FormRequest contracts are introduced for finance writes and CMS/social link writes.
5. Authorization shifts from generic admin role checks to explicit ability checks.

## Test Cases and Scenarios
1. Authorization matrix tests for each admin module (authorized role passes, others 403).
2. API auth tests for token-required routes (401 without token, success with token).
3. Payment tests for cross-customer mismatch, overpayment, exact remaining payment, and concurrent payment race.
4. Upload tests for SVG/MIME rejection and valid file acceptance.
5. Social link validation/render tests for malformed vs safe URLs.
6. Route integrity tests for all named routes referenced by views/controllers.
7. HR integration tests for corrected relations/columns.
8. Warranty/support integration tests for corrected keys and relations.
9. Query-count regression tests on public critical pages.
10. CI gate tests: PHPUnit, Pint, static analysis all green.

## Rollout Sequence
1. Deploy migrations/backfills for domain consistency.
2. Deploy auth/authorization hardening and verify role matrix.
3. Deploy route/controller contract fixes.
4. Deploy performance improvements and queue workers.
5. Rotate credentials/tokens and invalidate compromised values.
6. Monitor for 24 hours: 401/403 spikes, payment errors, queue failures, route-not-found events.

## Assumptions and Defaults
1. Employee-centric schema is the canonical HR source moving forward.
2. SVG uploads remain disabled by default for security.
3. URL paths remain stable; route-name changes are internal unless compatibility is explicitly required.
4. Security correctness takes precedence over legacy permissive behavior.
5. CI enforcement (tests, format, static analysis) is mandatory for future merges.
