# OIA Alert System - Complete Setup Guide

## Overview

The OIA Alert System is a full-featured Laravel web application for managing and tracking community alerts. The project includes authentication, alert management, notifications, and user profiles with a modern, responsive dashboard interface.

## System Requirements

### Server Requirements
- PHP 8.1 or higher
- Composer (latest version)
- Node.js (optional, for frontend builds)
- SQLite or MySQL

### PHP Extensions
- BCMath
- Ctype
- Fileinfo
- JSON
- Mbstring
- OpenSSL
- PDO
- Tokenizer
- XML

## Installation Steps

### Step 1: Clone or Navigate to Project

```bash
cd d:\Ai-asset\OIA-Alert-System
```

### Step 2: Install PHP Dependencies

```bash
composer install
```

This will install all Laravel framework dependencies and packages defined in `composer.json`.

### Step 3: Install Node Dependencies (Optional)

```bash
npm install
```

Only needed if you plan to compile frontend assets (CSS/JS).

### Step 4: Environment Setup

1. Copy the example environment file:
   ```bash
   cp .env.example .env
   ```

2. Generate the application encryption key:
   ```bash
   php artisan key:generate
   ```

   This creates a unique key for your installation and updates `.env`.

### Step 5: Database Configuration

#### Option A: SQLite (Recommended for Development)

SQLite is the default. Ensure the database file exists:

```bash
touch database/database.sqlite
```

Or Laravel will create it automatically on first migration.

Your `.env` should have:
```env
DB_CONNECTION=sqlite
DB_DATABASE=database/database.sqlite
```

#### Option B: MySQL

1. Create a database:
   ```sql
   CREATE DATABASE oia_alert CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
   ```

2. Update `.env`:
   ```env
   DB_CONNECTION=mysql
   DB_HOST=127.0.0.1
   DB_PORT=3306
   DB_DATABASE=oia_alert
   DB_USERNAME=root
   DB_PASSWORD=your_password
   ```

### Step 6: Run Database Migrations

```bash
php artisan migrate
```

This creates all necessary database tables:
- users
- alert_types
- alerts
- notifications
- password_reset_tokens
- sessions

### Step 7: Seed Initial Data

```bash
php artisan db:seed
```

This seeds the database with:
- 8 predefined alert types
- 1 test user account

### Step 8: Create Storage Symbolic Link

For file uploads to work properly:

```bash
php artisan storage:link
```

This creates a symbolic link from `storage/app/public` to `public/storage`.

### Step 9: Clear Cache (Important)

```bash
php artisan config:clear
php artisan cache:clear
php artisan view:clear
```

### Step 10: Start Development Server

```bash
php artisan serve
```

The application will be available at `http://localhost:8000`

## First Run

### Default Credentials

After seeding, login with:
- **Email**: test@example.com
- **Password**: password

### First Steps

1. Login to the dashboard
2. Explore the OIA Alerts
3. Submit a new alert
4. View your alerts
5. Update your profile

## Project Structure

### Key Directories

```
OIA-Alert-System/
├── app/                          # Application code
│   ├── Http/Controllers/         # Route handlers
│   ├── Models/                   # Database models
│   ├── Policies/                 # Authorization policies
│   └── Providers/                # Service providers
│
├── database/
│   ├── migrations/               # Database schema
│   └── seeders/                  # Initial data
│
├── resources/views/              # Blade templates
│   ├── layouts/                  # Layout components
│   ├── alerts/                   # Alert pages
│   ├── profile/                  # Profile pages
│   └── dashboard.blade.php
│
├── routes/                       # Route definitions
│   ├── web.php                   # Web routes
│   └── auth.php                  # Auth routes
│
├── public/                       # Public assets
│   └── storage/                  # Linked storage
│
├── storage/                      # Application storage
│   ├── app/public/              # File uploads
│   ├── logs/                     # Log files
│   └── framework/                # Framework cache
│
├── bootstrap/                    # Bootstrap scripts
├── config/                       # Configuration files
├── tests/                        # Test files
│
├── .env                          # Environment variables (create from .env.example)
├── .env.example                  # Example environment file
├── artisan                       # Laravel CLI
├── composer.json                 # PHP dependencies
├── package.json                  # Node dependencies
└── README.md                     # Documentation
```

## Core Features

### 1. Authentication
- User registration
- Email/password login
- Password reset (built-in)
- Session management

### 2. Dashboard
- Statistics cards
- Recent alerts listing
- Notification feed
- User greeting

### 3. Alert Management
- **Submit**: Create new alerts with images/evidence
- **Browse**: View all community alerts
- **Manage**: Edit/delete your alerts
- **Details**: Full alert information

### 4. User Profiles
- View profile information
- Edit name and email
- Change password
- View activity stats

### 5. Notifications
- Alert notifications
- Mark as read
- Delete notifications
- Unread counter

## Routes Overview

### Dashboard
- `GET /` - Welcome page
- `GET /dashboard` - Dashboard

### Alerts
- `GET /alerts` - My alerts list
- `GET /alerts/create` - Create alert form
- `POST /alerts` - Store alert
- `GET /alerts/{id}` - View alert
- `GET /alerts/{id}/edit` - Edit form
- `PUT /alerts/{id}` - Update alert
- `DELETE /alerts/{id}` - Delete alert
- `GET /alerts/oia/alerts` - All alerts

### Profile
- `GET /profile` - View profile
- `GET /profile/edit` - Edit form
- `PUT /profile` - Update profile
- `GET /profile/password` - Password form
- `PUT /profile/password` - Update password

### Authentication (Built-in)
- `GET /login` - Login form
- `POST /login` - Submit login
- `GET /register` - Registration form
- `POST /register` - Submit registration
- `POST /logout` - Logout

## Database Schema

### Users Table
```sql
- id (Primary Key)
- name
- email (Unique)
- phone (Nullable)
- password (Hashed)
- email_verified_at (Nullable)
- remember_token
- created_at / updated_at
```

### Alert Types Table
```sql
- id (Primary Key)
- name (Unique)
- description (Nullable)
- icon (Nullable)
- created_at / updated_at
```

### Alerts Table
```sql
- id (Primary Key)
- user_id (Foreign Key → users)
- alert_type_id (Foreign Key → alert_types)
- title
- description
- severity (low, medium, high, critical)
- status (pending, in_progress, resolved, rejected)
- location (Nullable)
- image_path (Nullable)
- evidence_path (Nullable)
- created_at / updated_at
```

### Notifications Table
```sql
- id (Primary Key)
- user_id (Foreign Key → users)
- alert_id (Foreign Key → alerts, Nullable)
- title
- message
- type (Notification type)
- read_at (Nullable)
- created_at / updated_at
```

## Configuration Files

### .env File

Important variables to set:

```env
APP_NAME="OIA Alert System"      # Application name
APP_ENV=local                    # Environment (local, production)
APP_DEBUG=true                   # Debug mode
APP_URL=http://localhost:8000    # Application URL

DB_CONNECTION=sqlite             # Database type
DB_DATABASE=database.sqlite      # SQLite file path

MAIL_DRIVER=log                  # Mail driver (for development)
MAIL_FROM_ADDRESS=admin@example.com
```

### config/app.php

Key application configuration. Usually doesn't need changes.

### config/database.php

Database connections. Update based on `.env`.

### config/auth.php

Authentication configuration. Uses default guards.

## Common Commands

### Artisan Commands

```bash
# Create new controller
php artisan make:controller ControllerName

# Create new model with migration
php artisan make:model ModelName --migration

# Run migrations
php artisan migrate

# Rollback migrations
php artisan migrate:rollback

# Reset database
php artisan migrate:reset

# Refresh database (reset + migrate + seed)
php artisan migrate:refresh --seed

# Seed database
php artisan db:seed

# Tinker REPL
php artisan tinker

# Clear caches
php artisan config:clear
php artisan cache:clear
php artisan view:clear

# Generate key
php artisan key:generate

# Serve application
php artisan serve

# Serve on specific port
php artisan serve --port=8001
```

## File Uploads

### Storage Location

Files are stored in `storage/app/public/alerts/`:
- Images: `alerts/images/{filename}`
- Evidence: `alerts/evidence/{filename}`

### Access Files

Files are served through:
```
http://localhost:8000/storage/alerts/images/{filename}
http://localhost:8000/storage/alerts/evidence/{filename}
```

### Size Limits

- Images: 5MB max
- Evidence: 10MB max

(Can be adjusted in validation rules in controllers)

## Security Features

### CSRF Protection
- All forms include CSRF tokens
- Enforced by middleware

### Password Security
- Passwords hashed with bcrypt
- Configurable hash rounds in `.env`

### Authorization
- Policies control who can modify resources
- Users can only modify their own data

### File Validation
- MIME type validation
- Size limits enforced
- Files stored outside public directory

### Database
- Prepared statements prevent SQL injection
- Foreign key constraints

## Troubleshooting

### Common Issues

#### 1. "Class not found" errors

**Cause**: Autoloader not updated

**Solution**:
```bash
composer dump-autoload
```

#### 2. Database connection fails

**Cause**: Incorrect credentials or database doesn't exist

**Solution**:
- Check `.env` settings
- Verify database exists
- Test with `php artisan tinker`

#### 3. File uploads not working

**Cause**: Storage link not created

**Solution**:
```bash
php artisan storage:link
```

#### 4. Views not updating

**Cause**: Views are cached

**Solution**:
```bash
php artisan view:clear
```

#### 5. 404 errors

**Cause**: Routes not found

**Solution**:
```bash
php artisan config:clear
php artisan cache:clear
```

#### 6. Permission denied errors

**Cause**: Storage directory not writable

**Solution**:
```bash
chmod -R 755 storage
chmod -R 755 bootstrap/cache
```

### Debug Mode

Enable debugging in `.env`:
```env
APP_DEBUG=true
```

Check logs in `storage/logs/` for detailed error messages.

## Performance Optimization

### Caching

```bash
# Cache configuration
php artisan config:cache

# Cache routes
php artisan route:cache

# Cache views (be careful!)
php artisan view:cache
```

### Database Optimization

- Indexes on foreign keys (done in migrations)
- Eager loading in controllers
- Pagination for large datasets

### Asset Compilation

For production:
```bash
npm run build
```

## Deployment

### Pre-deployment Checklist

1. Set `APP_DEBUG=false` in `.env`
2. Set `APP_ENV=production`
3. Generate production encryption key
4. Set proper database credentials
5. Set `APP_URL` to your domain
6. Configure mail settings
7. Set up proper file permissions
8. Enable HTTPS

### Deployment Steps

1. Clone repository to server
2. Install dependencies: `composer install --no-dev`
3. Copy `.env.example` to `.env` and configure
4. Generate key: `php artisan key:generate`
5. Run migrations: `php artisan migrate --force`
6. Seed data (if needed): `php artisan db:seed --force`
7. Create storage link: `php artisan storage:link`
8. Clear caches: `php artisan config:cache`

## Support & Resources

- [Laravel Documentation](https://laravel.com/docs)
- [Laravel API Reference](https://laravel.com/api)
- [Eloquent ORM Documentation](https://laravel.com/docs/eloquent)
- [Blade Template Documentation](https://laravel.com/docs/blade)

## Development Tips

1. **Use Tinker for testing**: `php artisan tinker`
2. **Log to database**: Check in `storage/logs/`
3. **Use Laravel Debugbar**: Install `barryvdh/laravel-debugbar`
4. **Follow PSR standards**: Keep code clean and consistent
5. **Write tests**: Use PHPUnit for testing

## Next Steps

1. Customize the design by modifying `resources/views/layouts/app.blade.php`
2. Add more alert types through the seeder
3. Implement email notifications
4. Add administrative features
5. Set up WebSockets for real-time updates
6. Deploy to a production server

Good luck with your OIA Alert System!
