> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Braian551/viax/llms.txt
> Use this file to discover all available pages before exploring further.

# Local Development Setup

> Complete guide to setting up Viax for local development using Laragon on Windows

# Local Development Setup

Set up a complete local development environment for Viax using Laragon, which provides Apache, MySQL, and PHP in a single package.

<Info>
  This guide focuses on Windows with Laragon. For macOS/Linux, use MAMP, XAMPP, or manual Apache/MySQL setup.
</Info>

## Why Local Development?

<CardGroup cols={2}>
  <Card title="Faster Development" icon="gauge-high">
    No network latency, instant response times for API calls
  </Card>

  <Card title="Offline Work" icon="wifi-slash">
    Develop without internet connection
  </Card>

  <Card title="Safe Testing" icon="shield-check">
    Test destructive operations without affecting production data
  </Card>

  <Card title="Full Control" icon="sliders">
    Complete access to database, logs, and server configuration
  </Card>
</CardGroup>

***

## Step 1: Install Laragon

### Download Laragon

<Steps>
  <Step title="Visit Laragon Website">
    Go to [laragon.org](https://laragon.org/download/)
  </Step>

  <Step title="Download Full Version">
    Download **Laragon Full** (includes Apache, MySQL, PHP, Redis, Memcached)

    File size: \~150 MB
  </Step>

  <Step title="Run Installer">
    * Double-click the installer
    * Choose installation directory (default: `C:\laragon`)
    * Complete installation wizard
  </Step>
</Steps>

### Start Laragon

<Steps>
  <Step title="Launch Laragon">
    Open Laragon from Start Menu or desktop shortcut
  </Step>

  <Step title="Start Services">
    Click **"Start All"** button (bottom-left)

    Services that will start:

    * Apache (port 80)
    * MySQL (port 3306)
  </Step>

  <Step title="Verify Services">
    Check that icons turn green:

    * 🟢 Apache
    * 🟢 MySQL
  </Step>

  <Step title="Test Apache">
    Open browser and visit: `http://localhost`

    You should see Laragon welcome page
  </Step>
</Steps>

***

## Step 2: Set Up Backend

### Copy Backend Files

<Tabs>
  <Tab title="Using PowerShell">
    ```powershell theme={null}
    # Navigate to Viax project
    cd C:\path\to\viax

    # Copy backend to Laragon www directory
    Copy-Item -Path .\backend -Destination C:\laragon\www\viax\backend -Recurse

    # Verify
    Test-Path C:\laragon\www\viax\backend\health.php
    ```
  </Tab>

  <Tab title="Manual Copy">
    1. Open File Explorer
    2. Navigate to your Viax project folder
    3. Copy the `backend` folder
    4. Navigate to `C:\laragon\www`
    5. Create folder `viax`
    6. Paste `backend` inside `viax`

    **Final structure:**

    ```
    C:\laragon\www\viax\backend\
    ├── auth/
    ├── conductor/
    ├── user/
    ├── admin/
    ├── config/
    └── health.php
    ```
  </Tab>
</Tabs>

### Verify Backend URL

Open browser and test:

```
http://localhost/viax/backend/health.php
```

**Expected response:**

```json theme={null}
{"status":"ok","timestamp":"2024-11-01 10:30:00"}
```

***

## Step 3: Set Up Database

### Create Database

<Tabs>
  <Tab title="HeidiSQL (Recommended)">
    HeidiSQL is included with Laragon.

    <Steps>
      <Step title="Open HeidiSQL">
        Laragon > Database button > Opens HeidiSQL automatically
      </Step>

      <Step title="Connect to MySQL">
        Connection should be automatic:

        * Host: localhost
        * User: root
        * Password: (empty by default)
      </Step>

      <Step title="Create Database">
        1. Right-click on connection
        2. "Create new" > "Database"
        3. Name: `viax`
        4. Collation: `utf8mb4_unicode_ci`
        5. Click OK
      </Step>
    </Steps>
  </Tab>

  <Tab title="phpMyAdmin">
    <Steps>
      <Step title="Access phpMyAdmin">
        Laragon > Menu > MySQL > phpMyAdmin

        Or visit: `http://localhost/phpmyadmin`
      </Step>

      <Step title="Create Database">
        1. Click "New" in left sidebar
        2. Database name: `viax`
        3. Collation: `utf8mb4_unicode_ci`
        4. Click "Create"
      </Step>
    </Steps>
  </Tab>

  <Tab title="Command Line">
    ```bash theme={null}
    # Open Laragon terminal
    # Laragon > Terminal button

    mysql -u root -p
    # Press Enter (no password by default)

    CREATE DATABASE viax CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    SHOW DATABASES;
    EXIT;
    ```
  </Tab>
</Tabs>

### Import Database Schema

<Steps>
  <Step title="Locate SQL File">
    Find the database file in your Viax project:

    * `basededatos.sql` or
    * `basededatosfinal.sql`
  </Step>

  <Step title="Import in HeidiSQL">
    1. Select `viax` database in left panel
    2. File > Load SQL file
    3. Select your `.sql` file
    4. Click "Execute" (F9)
    5. Wait for import to complete
  </Step>

  <Step title="Verify Tables">
    Expand `viax` database in HeidiSQL. You should see:

    * usuarios
    * conductores
    * solicitudes\_servicio
    * viajes
    * documentos\_conductor
    * configuracion\_precios
    * administradores
    * audit\_logs
    * empresas
  </Step>
</Steps>

**Alternative: Import via Command Line**

```bash theme={null}
mysql -u root viax < C:\path\to\basededatos.sql
```

### Configure Database Connection

**File:** `C:\laragon\www\viax\backend\config\database.php`

```php theme={null}
<?php
class Database {
    private $host = 'localhost';
    private $db_name = 'viax';
    private $username = 'root';
    private $password = 'root';  // Laragon default (or empty '')
    private $conn;
    
    public function getConnection() {
        $this->conn = null;
        
        try {
            $dsn = "mysql:host={$this->host};dbname={$this->db_name};charset=utf8mb4";
            $this->conn = new PDO($dsn, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch(PDOException $exception) {
            error_log("Connection error: " . $exception->getMessage());
            throw new Exception("Database connection failed");
        }
        
        return $this->conn;
    }
}
?>
```

<Note>
  Laragon's default MySQL password is `root`. Some installations use empty password `''`.
</Note>

***

## Step 4: Install PHP Dependencies

### Install Composer (if not included)

Laragon usually includes Composer. Verify:

```bash theme={null}
# Open Laragon terminal
composer --version
```

**If not installed:**

1. Laragon > Menu > Tools > Quick add > Composer
2. Or download from [getcomposer.org](https://getcomposer.org/)

### Install Backend Dependencies

```bash theme={null}
# Open Laragon terminal
cd C:\laragon\www\viax\backend

# Install dependencies
composer install

# Verify installation
ls vendor/
```

**Installed packages:**

* PHPMailer (email sending)
* JWT library (future authentication)
* Other PHP dependencies

***

## Step 5: Configure Flutter for Local Backend

### For Android Emulator

Android emulator maps `localhost` to `10.0.2.2`:

```bash theme={null}
flutter run --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend
```

### For Physical Android Device

<Steps>
  <Step title="Find Your Local IP">
    ```bash theme={null}
    ipconfig
    # Look for "IPv4 Address" (e.g., 192.168.1.100)
    ```
  </Step>

  <Step title="Connect Device to Same WiFi">
    Ensure your phone is on the same network as your computer
  </Step>

  <Step title="Run App">
    ```bash theme={null}
    flutter run --dart-define=API_BASE_URL=http://192.168.1.100/viax/backend
    ```
  </Step>
</Steps>

### For iOS Simulator

iOS Simulator can use `localhost`:

```bash theme={null}
flutter run --dart-define=API_BASE_URL=http://localhost/viax/backend
```

### Permanent Configuration (Development)

Edit `.vscode/launch.json`:

```json theme={null}
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Viax Local (Emulator)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://10.0.2.2/viax/backend"
      ]
    },
    {
      "name": "Viax Local (Device - Update IP)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://192.168.1.100/viax/backend"
      ]
    }
  ]
}
```

***

## Step 6: Test the Setup

### Test Backend Endpoints

<Tabs>
  <Tab title="Health Check">
    ```bash theme={null}
    curl http://localhost/viax/backend/health.php
    ```

    **Expected:**

    ```json theme={null}
    {"status":"ok"}
    ```
  </Tab>

  <Tab title="System Verification">
    ```bash theme={null}
    curl http://localhost/viax/backend/verify_system_json.php
    ```

    **Expected:**

    ```json theme={null}
    {
      "success": true,
      "database": "connected",
      "tables": [...],
      "php_version": "8.3.x"
    }
    ```
  </Tab>

  <Tab title="Test Login Endpoint">
    ```bash theme={null}
    curl -X POST http://localhost/viax/backend/auth/login.php \
      -H "Content-Type: application/json" \
      -d '{"email":"test@example.com","password":"test123"}'
    ```
  </Tab>
</Tabs>

### Test from Flutter App

<Steps>
  <Step title="Run the App">
    ```bash theme={null}
    flutter run --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend
    ```
  </Step>

  <Step title="Test Registration">
    1. Open the app
    2. Tap "Crear cuenta" (Create account)
    3. Fill in registration form
    4. Submit
  </Step>

  <Step title="Verify in Database">
    Open HeidiSQL and check `usuarios` table:

    ```sql theme={null}
    SELECT * FROM usuarios ORDER BY id DESC LIMIT 1;
    ```

    You should see the new user you just created.
  </Step>
</Steps>

***

## Development Workflow

### Daily Workflow

<Steps>
  <Step title="Start Services">
    1. Open Laragon
    2. Click "Start All"
    3. Wait for services to turn green
  </Step>

  <Step title="Start Development">
    ```bash theme={null}
    cd C:\path\to\viax
    flutter run --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend
    ```
  </Step>

  <Step title="Monitor Logs">
    * Flutter logs: In terminal where app is running
    * Backend logs: `C:\laragon\www\viax\backend\logs\`
    * Apache logs: `C:\laragon\bin\apache\apache-X.X.X\logs\`
    * MySQL logs: Laragon > Menu > MySQL > Log file
  </Step>

  <Step title="Hot Reload">
    * Press `r` in Flutter terminal for hot reload
    * Press `R` for hot restart
    * Press `q` to quit
  </Step>
</Steps>

### Database Development

**View Live Data:**

```sql theme={null}
-- Recent users
SELECT * FROM usuarios ORDER BY fecha_registro DESC LIMIT 10;

-- Active trips
SELECT * FROM solicitudes_servicio WHERE estado = 'pendiente';

-- Online drivers
SELECT * FROM conductores WHERE disponibilidad = 1;
```

**Reset Test Data:**

```sql theme={null}
-- Clear all trips
DELETE FROM viajes;
DELETE FROM solicitudes_servicio;

-- Clear test users (keep admin)
DELETE FROM usuarios WHERE id > 1;

-- Reset auto-increment
ALTER TABLE usuarios AUTO_INCREMENT = 2;
```

### Backend Development

**Enable Error Display:**

Add to top of PHP files during development:

```php theme={null}
<?php
// DEVELOPMENT ONLY - Remove in production
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/php_errors.log');

// Your code...
?>
```

**Logging:**

```php theme={null}
// Log to file
error_log("Debug info: " . json_encode($data));

// Log to custom file
file_put_contents(
    __DIR__ . '/logs/debug.log',
    date('Y-m-d H:i:s') . " - " . json_encode($data) . "\n",
    FILE_APPEND
);
```

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Laragon won't start">
    **Port conflicts:**

    1. Check if port 80 is in use:
       ```bash theme={null}
       netstat -ano | findstr :80
       ```

    2. Stop conflicting service:
       * Skype (uses port 80)
       * IIS (Windows web server)
       * Other web servers

    3. Or change Apache port:
       * Laragon > Menu > Apache > httpd.conf
       * Change `Listen 80` to `Listen 8080`
       * Restart Laragon
       * Use `http://localhost:8080/viax/backend`
  </Accordion>

  <Accordion title="Database connection failed">
    **Solutions:**

    1. Verify MySQL is running (green icon in Laragon)

    2. Check credentials:
       ```php theme={null}
       $username = 'root';
       $password = 'root';  // or '' (empty)
       ```

    3. Test connection manually:
       ```bash theme={null}
       mysql -u root -p
       # Enter password: root
       SHOW DATABASES;
       ```

    4. Check database exists:
       ```sql theme={null}
       SHOW DATABASES LIKE 'viax';
       ```
  </Accordion>

  <Accordion title="404 Not Found on backend URLs">
    **Check:**

    1. Files are in correct location:
       * Should be: `C:\laragon\www\viax\backend\`
       * Not: `C:\laragon\www\backend\`
    2. Verify URL path:
       * Correct: `http://localhost/viax/backend/health.php`
       * Wrong: `http://localhost/backend/health.php`
    3. Check file permissions (should auto-set by Laragon)
  </Accordion>

  <Accordion title="Composer not found">
    **Install Composer:**

    1. Laragon > Menu > Tools > Quick add > Composer
    2. Restart Laragon
    3. Verify: `composer --version`

    Or download from [getcomposer.org](https://getcomposer.org/)
  </Accordion>

  <Accordion title="Flutter can't connect from emulator">
    **Android Emulator:**

    * Must use `10.0.2.2` not `localhost`
    * Verify with:
      ```bash theme={null}
      # In emulator via adb shell
      curl http://10.0.2.2/viax/backend/health.php
      ```

    **Physical Device:**

    * Must be on same WiFi network
    * Use computer's IP (not localhost)
    * Disable Windows Firewall temporarily to test
  </Accordion>

  <Accordion title="Email sending not working">
    **PHPMailer Configuration:**

    For local development, configure SMTP in backend:

    ```php theme={null}
    // backend/auth/email_service.php
    $mail->SMTPDebug = 2; // Enable debug output
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your-email@gmail.com';
    $mail->Password = 'your-app-specific-password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    ```

    Or use Mailtrap.io for testing emails.
  </Accordion>
</AccordionGroup>

***

## Advanced Configuration

### Enable PHP Extensions

<Steps>
  <Step title="Edit php.ini">
    Laragon > Menu > PHP > php.ini
  </Step>

  <Step title="Uncomment Extensions">
    Remove `;` from extensions you need:

    ```ini theme={null}
    extension=gd
    extension=mysqli
    extension=pdo_mysql
    extension=openssl
    extension=mbstring
    ```
  </Step>

  <Step title="Restart Apache">
    Laragon > Stop All > Start All
  </Step>
</Steps>

### Virtual Hosts (Optional)

Create a pretty URL like `viax.local`:

<Steps>
  <Step title="Create Virtual Host">
    Laragon > Menu > Apache > sites-enabled > Add

    Content:

    ```apache theme={null}
    <VirtualHost *:80>
        DocumentRoot "C:/laragon/www/viax/backend"
        ServerName viax.local
        <Directory "C:/laragon/www/viax/backend">
            AllowOverride All
            Require all granted
        </Directory>
    </VirtualHost>
    ```
  </Step>

  <Step title="Update Hosts File">
    Edit `C:\Windows\System32\drivers\etc\hosts` (as Administrator):

    Add:

    ```
    127.0.0.1 viax.local
    ```
  </Step>

  <Step title="Restart Apache">
    Laragon > Stop All > Start All
  </Step>

  <Step title="Test">
    Visit: `http://viax.local/health.php`

    Use in Flutter:

    ```bash theme={null}
    --dart-define=API_BASE_URL=http://viax.local
    ```
  </Step>
</Steps>

***

## Performance Tips

<CardGroup cols={2}>
  <Card title="Increase PHP Memory" icon="memory">
    In `php.ini`:

    ```ini theme={null}
    memory_limit = 256M
    upload_max_filesize = 20M
    post_max_size = 20M
    ```
  </Card>

  <Card title="Enable OpCache" icon="bolt">
    In `php.ini`:

    ```ini theme={null}
    opcache.enable=1
    opcache.memory_consumption=128
    ```
  </Card>

  <Card title="MySQL Optimization" icon="database">
    In HeidiSQL, run:

    ```sql theme={null}
    SET GLOBAL innodb_buffer_pool_size=256M;
    ```
  </Card>

  <Card title="Disable Xdebug" icon="bug-slash">
    Comment out in `php.ini`:

    ```ini theme={null}
    ;zend_extension=xdebug
    ```
  </Card>
</CardGroup>

***

## Useful Laragon Commands

```bash theme={null}
# Quick access
Laragon > Terminal    # Opens terminal in www folder
Laragon > Root        # Opens C:\laragon in explorer
Laragon > www         # Opens C:\laragon\www in explorer

# Database
Laragon > Database    # Opens HeidiSQL
Laragon > Menu > MySQL > phpMyAdmin

# Logs
Laragon > Menu > Apache > Error log
Laragon > Menu > MySQL > Error log

# Configuration
Laragon > Menu > Apache > httpd.conf
Laragon > Menu > PHP > php.ini
Laragon > Menu > MySQL > my.ini
```

<Check>
  **Local Development Ready!** You now have a complete local environment for Viax development with hot reload, database access, and full debugging capabilities.
</Check>
