# 🗄️ Database Setup & Installation Guide

<p align="center">
  <img src="https://img.shields.io/badge/MySQL-Database-orange?style=for-the-badge&logo=mysql" alt="MySQL">
  <img src="https://img.shields.io/badge/Laravel-Migrations-red?style=for-the-badge&logo=laravel" alt="Laravel">
</p>

---

## 📑 Table of Contents

1. [System Requirements](#-system-requirements)
2. [Installing Prerequisites](#-installing-prerequisites)
3. [Database Setup](#-database-setup)
4. [Project Configuration](#-project-configuration)
5. [Running the Project](#-running-the-project)
6. [Database Seeding](#-database-seeding)
7. [Troubleshooting](#-troubleshooting)
8. [Production Tips](#-production-tips)

---

## 🔧 System Requirements

### Required Software

| Software | Required Version | Purpose |
|----------|------------------|---------|
| **PHP** | 8.2 or higher | Backend Runtime |
| **Composer** | 2.x | PHP Package Manager |
| **Node.js** | 18.x or higher | JavaScript Runtime |
| **NPM** | 9.x or higher | JavaScript Package Manager |
| **MySQL** | 5.7+ or 8.x | Database |
| **Git** | 2.x | Version Control |

### Required PHP Extensions

Check installed extensions:

```bash
php -m
```

Required extensions:
- ✅ `php-mbstring`
- ✅ `php-xml`
- ✅ `php-pdo`
- ✅ `php-mysql`
- ✅ `php-curl`
- ✅ `php-zip`
- ✅ `php-gd`
- ✅ `php-bcmath`
- ✅ `php-json`
- ✅ `php-tokenizer`
- ✅ `php-fileinfo`

---

## 📦 Installing Prerequisites

### Windows

#### 1. Install PHP
```powershell
# Use XAMPP, WAMP, or Laravel Herd
# Download from: https://www.apachefriends.org/download.html
```

#### 2. Install Composer
```powershell
# Download from: https://getcomposer.org/download/
# Or using PowerShell:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
```

#### 3. Install Node.js
```powershell
# Download from: https://nodejs.org/en/download/
```

#### 4. Install MySQL
```powershell
# Use XAMPP or install MySQL separately
# Download from: https://dev.mysql.com/downloads/installer/
```

### Linux (Ubuntu/Debian)

```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install PHP 8.2 and extensions
sudo apt install -y php8.2 php8.2-cli php8.2-fpm php8.2-mysql \
php8.2-mbstring php8.2-xml php8.2-curl php8.2-zip \
php8.2-gd php8.2-bcmath

# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

# Install Node.js & NPM
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

# Install MySQL
sudo apt install -y mysql-server
sudo mysql_secure_installation
```

### macOS

```bash
# Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install PHP 8.2
brew install php@8.2

# Install Composer
brew install composer

# Install Node.js
brew install node

# Install MySQL
brew install mysql
brew services start mysql
```

---

## 🗃️ Database Setup

### Step 1: Create Database

#### Using MySQL Command Line

```bash
# Login to MySQL
mysql -u root -p

# Create database
CREATE DATABASE school_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Create new user (optional - recommended for production)
CREATE USER 'school_user'@'localhost' IDENTIFIED BY 'your_secure_password';

# Grant privileges
GRANT ALL PRIVILEGES ON school_db.* TO 'school_user'@'localhost';
FLUSH PRIVILEGES;

# Exit
EXIT;
```

#### Using phpMyAdmin

1. Open phpMyAdmin in browser: `http://localhost/phpmyadmin`
2. Click "New" or "New Database"
3. Enter database name: `school_db`
4. Choose Collation: `utf8mb4_unicode_ci`
5. Click "Create"

#### Verify Database Creation

```bash
mysql -u root -p -e "SHOW DATABASES;"
```

You should see `school_db` in the list.

---

## ⚙️ Project Configuration

### Step 1: Clone the Project

```bash
# Clone repository
git clone <repository-url> school_system
cd school_system
```

### Step 2: Install Dependencies

```bash
# Install PHP packages
composer install

# Install JavaScript packages
npm install
```

**Note**: If you encounter errors with `composer install`:
```bash
# Remove vendor folder and lock file
rm -rf vendor composer.lock
composer install
```

### Step 3: Setup Environment File (.env)

```bash
# Copy environment file
cp .env.example .env

# Or on Windows PowerShell:
copy .env.example .env
```

### Step 4: Update .env Configuration

Open `.env` file and update the following:

```env
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Application Settings
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
APP_NAME="School Management System"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Database Settings
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=school_db
DB_USERNAME=root
DB_PASSWORD=

# Note: If you created a new user:
# DB_USERNAME=school_user
# DB_PASSWORD=your_secure_password

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Session Settings
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SESSION_DRIVER=file
SESSION_LIFETIME=120

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Cache Settings
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CACHE_STORE=database
QUEUE_CONNECTION=database

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Email Settings
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MAIL_MAILER=log
MAIL_FROM_ADDRESS="noreply@schoolsystem.com"
MAIL_FROM_NAME="${APP_NAME}"
```

### Step 5: Generate Application Key

```bash
php artisan key:generate
```

### Step 6: Run Migrations

```bash
# Run all migrations
php artisan migrate

# If you want to rebuild database from scratch:
php artisan migrate:fresh
```

**Migration Order** (automatically executed in correct order):

1. `create_users_table` - Users table
2. `create_cache_table` - Cache table
3. `create_jobs_table` - Jobs table
4. `create_permission_tables` - Permission tables (Spatie)
5. `create_grades_table` - Grades
6. `create_students_table` - Students
7. `create_attendances_table` - Attendance
8. `create_subjects_table` - Subjects
9. `create_marks_table` - Marks
10. `create_teachers_table` - Teachers
11. `add_teacher_id_to_subjects_table` - Link subjects to teachers
12. `create_schedules_table` - Schedules
13. `add_role_to_users_table` - Add role to users
14. `add_user_id_to_students_table` - Link students to users
15. `add_user_id_to_teachers_table` - Link teachers to users
16. `create_notes_table` - Notes
17. `create_parent_models_table` - Parents
18. `add_parent_id_to_students_table` - Link students to parents
19. `create_fees_table` - Fees
20. `create_payments_table` - Payments
21. `create_assignments_table` - Assignments
22. `create_settings_table` - Settings
23. `create_books_table` - Books
24. `create_borrowings_table` - Borrowings
25. `create_events_table` - Events
26. `create_exams_table` - Exams
27. `add_exam_id_to_marks_table` - Link marks to exams

### Step 7: Set Directory Permissions

#### Linux/macOS

```bash
# Grant write permissions to storage directories
chmod -R 775 storage
chmod -R 775 bootstrap/cache

# Change owner (optional)
sudo chown -R www-data:www-data storage
sudo chown -R www-data:www-data bootstrap/cache
```

#### Windows

```powershell
# Usually no permission changes needed on Windows
# But ensure directories are not write-protected
```

---

## 🚀 Running the Project

### Method 1: Basic Setup

```bash
# 1. Start Laravel server
php artisan serve

# Application will run on: http://127.0.0.1:8000
```

In another Terminal window:

```bash
# 2. Build assets (CSS/JS)
npm run build

# Or for development with Hot Reload:
npm run dev
```

### Method 2: Advanced Setup (Recommended for Development)

Use the custom Composer command that runs everything together:

```bash
composer dev
```

This command runs:
- ✅ **Server**: `php artisan serve` (port 8000)
- ✅ **Queue Worker**: Queue processing
- ✅ **Logs**: Real-time log viewing
- ✅ **Vite**: Hot reload for CSS/JS

### Method 3: Using Laravel Sail (Docker)

```bash
# Install Sail
composer require laravel/sail --dev

# Publish Sail
php artisan sail:install

# Start Docker Containers
./vendor/bin/sail up -d

# Run migrations in Docker
./vendor/bin/sail artisan migrate
```

---

## 🌱 Database Seeding

### Run Seeders

```bash
# Run all seeders
php artisan db:seed

# Or run specific seeder
php artisan db:seed --class=UserSeeder
```

### Create Admin User Manually

```bash
php artisan tinker
```

Then in Tinker:

```php
// Create admin user
$admin = \App\Models\User::create([
    'name' => 'Admin',
    'email' => 'admin@school.com',
    'password' => bcrypt('password123'),
    'email_verified_at' => now(),
]);

// Assign admin role (if using Spatie Permission)
$admin->assignRole('admin');

// Exit
exit
```

### Reset Database Completely

```bash
# Drop all tables, recreate, and seed
php artisan migrate:fresh --seed
```

⚠️ **Warning**: This command will delete all existing data!

---

## 🔍 Verify Installation

### 1. Check Database Connection

```bash
php artisan migrate:status
```

You should see a list of all migrations with status "Ran".

### 2. Verify Application Works

Open browser and navigate to:
```
http://localhost:8000
```

### 3. Verify Vite Assets Load

Ensure styles and JavaScript are loading correctly.

### 4. Check Permissions

```bash
php artisan permission:cache-reset
php artisan optimize:clear
```

---

## 🐛 Troubleshooting

### Issue 1: "SQLSTATE[HY000] [2002] Connection refused"

**Cause**: Cannot connect to database.

**Solution**:
```bash
# Check if MySQL is running
# Windows (XAMPP):
# Open XAMPP Control Panel and start MySQL

# Linux:
sudo systemctl status mysql
sudo systemctl start mysql

# macOS:
brew services list
brew services start mysql

# Verify connection details in .env
```

### Issue 2: "Class 'XXX' not found"

**Cause**: Dependencies not installed or autoload not updated.

**Solution**:
```bash
composer install
composer dump-autoload
php artisan optimize:clear
```

### Issue 3: "The stream or file could not be opened"

**Cause**: Permission issues with storage directory.

**Solution**:
```bash
# Linux/macOS:
chmod -R 775 storage bootstrap/cache

# Windows:
# Right-click on storage and bootstrap/cache folders
# Properties > Security > Edit > Add Full Control
```

### Issue 4: "Vite manifest not found"

**Cause**: Assets not built.

**Solution**:
```bash
npm install
npm run build
```

### Issue 5: "419 Page Expired" when submitting forms

**Cause**: CSRF token issue.

**Solution**:
```bash
php artisan optimize:clear
php artisan config:clear

# Ensure @csrf directive is in forms
```

### Issue 6: Migration Errors

**Solution**:
```bash
# Rollback last batch of migrations
php artisan migrate:rollback

# Or rebuild database from scratch
php artisan migrate:fresh
```

### Clear Cache

```bash
# Clear all caches
php artisan optimize:clear

# Or individually:
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear
```

---

## 📊 Database Information

### Table Relationships

```
users (Users)
  ├─> students (one-to-one) - Students
  ├─> teachers (one-to-one) - Teachers
  └─> parent_models (one-to-one) - Parents

students (Students)
  ├─> grades (many-to-one) - Grades
  ├─> parent_models (many-to-one) - Parent
  ├─> attendances (one-to-many) - Attendance
  ├─> marks (one-to-many) - Marks
  ├─> payments (one-to-many) - Payments
  ├─> borrowings (one-to-many) - Borrowings
  └─> notes (one-to-many) - Notes

teachers (Teachers)
  ├─> subjects (one-to-many) - Subjects
  └─> assignments (one-to-many) - Assignments

grades (Grades)
  ├─> students (one-to-many)
  ├─> subjects (one-to-many)
  └─> fees (one-to-many)

subjects (Subjects)
  ├─> marks (one-to-many)
  ├─> schedules (one-to-many)
  └─> assignments (one-to-many)

exams (Exams)
  ├─> marks (one-to-many)
  └─> subjects (many-to-one)
```

### Database Tips

#### 1. Backup Database

```bash
# Create backup
mysqldump -u root -p school_db > backup_$(date +%Y%m%d).sql

# Restore from backup
mysql -u root -p school_db < backup_20260114.sql
```

#### 2. Reset Database

```bash
# Drop all tables and re-run migrations
php artisan migrate:fresh

# With seeders
php artisan migrate:fresh --seed
```

#### 3. Create New Seeder

```bash
php artisan make:seeder StudentSeeder
```

#### 4. Create New Migration

```bash
php artisan make:migration create_table_name_table
```

---

## 🌐 Production Tips

When deploying to production server:

### 1. Update .env Settings

```env
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

# Use strong passwords
DB_PASSWORD=strong_secure_password
```

### 2. Optimize Performance

```bash
# Optimize Composer
composer install --optimize-autoloader --no-dev

# Cache configurations
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Build assets for production
npm run build
```

### 3. Security Settings

```bash
# Enable HTTPS only
SESSION_SECURE_COOKIE=true

# Disable debug mode
APP_DEBUG=false

# Use secure file permissions
chmod -R 755 storage
chmod -R 755 bootstrap/cache
```

### 4. Queue Workers

```bash
# Use Supervisor to run Queue Workers
sudo apt install supervisor

# Setup Supervisor config
sudo nano /etc/supervisor/conf.d/laravel-worker.conf
```

> [!IMPORTANT]
> **Background Jobs**: Make sure to run `php artisan queue:work` (or have a queue worker running) to process the background jobs. If the `.env` is set to `QUEUE_CONNECTION=sync`, the job will still run during the request, but it is now architecturally ready for background processing.


---

## 📞 Help and Support

If you encounter any issues:

1. **Check logs**:
   ```bash
   tail -f storage/logs/laravel.log
   ```

2. **Review documentation**: [README.md](README.md)

3. **Open an Issue** in the repository

4. **Contact the development team**

---

## ✅ Final Checklist

Before starting development, ensure:

- [ ] PHP 8.2+ installed
- [ ] Composer installed
- [ ] Node.js & NPM installed
- [ ] MySQL installed and running
- [ ] Database `school_db` created
- [ ] `composer install` executed
- [ ] `npm install` executed
- [ ] `.env.example` copied to `.env`
- [ ] Database credentials updated in `.env`
- [ ] `php artisan key:generate` executed
- [ ] `php artisan migrate` executed
- [ ] `npm run build` or `npm run dev` executed
- [ ] Server running `php artisan serve`
- [ ] Browser opened at `http://localhost:8000`

---

<p align="center">
  <strong>🎉 Congratulations! Your project is ready to run</strong>
</p>

<p align="center">
  For more information, see <a href="README.md">README.md</a>
</p>
