#!/usr/bin/env bash
set -euo pipefail

ROOT="${1:-docs}"
mkdir -p "$ROOT"

cat > "$ROOT/PROJECT.md" <<'EOF'
# Registration Starter Project

## Overview

This project is a PHP/MySQL registration and access-control starter built with PDO, prepared statements, hashed passwords, groups, and application access rules.

It is designed to be a clean base for production-ready user registration, login, authorization, and admin-driven access management.

## Goals

- Provide a secure and minimal authentication foundation.
- Support user-to-group and group-to-application relationships.
- Keep database access isolated behind PDO prepared statements.
- Make the codebase easy to extend for admin tools, reporting, and future API work.
- Keep the project simple enough to deploy on shared or dedicated hosting.

## AI Goals

- Use AI to accelerate boilerplate generation without losing code quality.
- Use AI to draft documentation, migration notes, and admin workflows.
- Use AI to suggest refactors, test cases, and edge-case handling.
- Use AI to help produce repeatable deployment scripts and setup guides.
- Avoid AI-generated code landing in production without review.

## Security Goals

- Store passwords only with `password_hash()` and verify with `password_verify()`.
- Use prepared statements for every database write and read that includes user input.
- Add CSRF protection to all POST, PUT, PATCH, and DELETE actions.
- Regenerate the session ID after login and after privilege changes.
- Enforce unique constraints on username and email.
- Keep authorization checks server-side only.
- Log security-relevant events such as failed logins and access denials.
- Add rate limiting for login and registration endpoints.
- Use HTTPS in every environment that handles credentials.
- Consider Argon2id or a strong password policy aligned with modern guidance.

## Improvements

### Near term

- Add CSRF tokens to forms.
- Add flash messages for success and error states.
- Add validation helpers shared by all form handlers.
- Add pagination for admin user lists.
- Add better error pages for 403 and 404 responses.
- Add audit logging for group membership and application assignment changes.

### Medium term

- Add password reset flow.
- Add email verification.
- Add user profile editing.
- Add admin UI for assigning groups and applications.
- Add soft-delete or deactivation workflows for users.
- Add role-based permission helpers instead of hard-coded group checks.

### Longer term

- Add JSON API endpoints.
- Add frontend separation if needed.
- Add automated test coverage for authentication and authorization checks.
- Add container-based local development.
- Add deployment automation for staging and production.
- Add observability: structured logs, metrics, and security events.

## Future Tasks

1. Implement CSRF token generation and verification.
2. Add a reusable form validation layer.
3. Build admin screens for CRUD on groups and applications.
4. Add user-group assignment controls.
5. Add password reset and email verification.
6. Add rate limiting for auth endpoints.
7. Add integration tests for registration, login, and authorization checks.
8. Add seed scripts for default groups and applications.
9. Add documentation for deployment and backup procedures.
10. Add a migration strategy for future schema changes.

## Operational Notes

- The database schema uses junction tables for many-to-many relationships.
- Authorization should always be checked on the server side before rendering or processing sensitive actions.
- Password hashes should be stored in a `VARCHAR(255)` column to allow for future algorithm changes.
- Prepared statements should stay enabled with native prepares where possible.
- Login should use a single lookup and `password_verify()` against the stored hash.

## Definition of Done

A feature is complete when it has:

- Server-side validation.
- Secure database access.
- Authorization checks.
- Basic error handling.
- Documentation updates.
- A path for tests or manual verification.
EOF

cat > "$ROOT/SECURITY.md" <<'EOF'
# Security Notes

## Password Handling

- Store passwords only with `password_hash()`.
- Verify passwords only with `password_verify()`.
- Never store plain-text passwords.
- Never try to reverse password hashes.
- Use a `VARCHAR(255)` column for password hashes.

## Database Safety

- Use PDO prepared statements for every query that includes user input.
- Disable emulated prepares when possible.
- Validate input before it reaches the database.
- Use unique keys for username and email.
- Use foreign keys for group and application relationships.

## Session Safety

- Call `session_regenerate_id(true)` after login.
- Destroy sessions fully on logout.
- Set secure cookie flags in production.
- Use HTTPS everywhere credentials are transmitted.

## Authorization Safety

- Check permissions on the server side only.
- Never trust hidden fields or client-side UI for access control.
- Use centralized helper functions for group and application checks.
- Treat admin routes as restricted by default.

## CSRF Protection

- Add CSRF tokens to every state-changing form.
- Validate tokens before processing POST requests.
- Reject missing or invalid tokens.
- Apply the same protection to admin workflows.

## Abuse Prevention

- Add login throttling or rate limiting.
- Log repeated failed login attempts.
- Consider temporary lockouts for abusive behavior.
- Add email or notification alerts for suspicious admin activity.

## Audit Logging

- Log user registration events.
- Log failed and successful logins.
- Log role and group assignment changes.
- Log application access denials.
- Keep logs structured and timestamped.

## Recommended Additions

- Password reset tokens with expiration.
- Email verification before full access.
- Strong password policy or passphrase guidance.
- Optional MFA for admin accounts.
- Security headers at the web server level.
EOF

cat > "$ROOT/ROADMAP.md" <<'EOF'
# Roadmap

## Phase 1

- Build the core registration and login flow.
- Add groups and applications tables.
- Add join tables for access control.
- Add the first admin pages.

## Phase 2

- Add CSRF protection.
- Add flash messages.
- Add form validation helpers.
- Add admin assignment screens.
- Add pagination and filtering.

## Phase 3

- Add password reset.
- Add email verification.
- Add audit logs.
- Add rate limiting.
- Add better error pages.

## Phase 4

- Add test coverage.
- Add deployment automation.
- Add backups and restore notes.
- Add documentation for maintenance.
- Add API endpoints if needed.

## Phase 5

- Add observability.
- Add structured security logging.
- Add optional MFA.
- Add permission abstractions.
- Add containerized local development.
EOF

cat > "$ROOT/ADMIN_WORKFLOWS.md" <<'EOF'
# Admin Workflows

## Create a Group

1. Open the groups admin page.
2. Enter a group name and slug.
3. Save the record.
4. Confirm the group appears in the list.

## Create an Application

1. Open the applications admin page.
2. Enter the application name and slug.
3. Save the record.
4. Confirm the application appears in the list.

## Assign a User to a Group

1. Open the user detail view.
2. Select one or more groups.
3. Save the assignment.
4. Verify the new access level works.

## Assign a Group to an Application

1. Open the group detail view.
2. Select the applications that group may access.
3. Save the mapping.
4. Verify access checks return the expected result.

## Review Access

1. Check whether the user is active.
2. Check the groups attached to the user.
3. Check the applications attached to those groups.
4. Deny access when no match exists.
EOF

cat > "$ROOT/DEPLOYMENT.md" <<'EOF'
# Deployment Notes

## Requirements

- PHP with PDO MySQL support.
- MySQL or MariaDB.
- Web server with a document root pointing to `public/`.

## Setup

1. Import `sql/schema.sql`.
2. Update `app/config.php`.
3. Set the web server document root to `public/`.
4. Create the default groups and applications.
5. Test registration, login, and access control.

## Production Checklist

- Force HTTPS.
- Set secure session cookie flags.
- Turn off display errors.
- Log errors to file.
- Confirm file permissions are restricted.
- Back up the database before changes.

## Maintenance

- Review logs regularly.
- Rotate credentials when needed.
- Revisit password policy periodically.
- Update dependencies and platform packages.
- Re-test admin workflows after schema changes.
EOF

cat > "$ROOT/README.md" <<'EOF'
# Documentation Set

This folder contains the core project documentation for goals, security, roadmap, admin workflows, and deployment.

Recommended reading order:

1. PROJECT.md
2. SECURITY.md
3. ROADMAP.md
4. ADMIN_WORKFLOWS.md
5. DEPLOYMENT.md
EOF

echo "Created docs in $ROOT"

