#!/bin/bash

# MindEase Project Creator
# This script creates the full Laravel 10 project structure with all files.

set -e  # exit on error

echo "Creating MindEase project structure..."

# Create root directories
mkdir -p app/Console/Commands          # <-- FIX: added Commands subdirectory
mkdir -p app/Exceptions
mkdir -p app/Http/Controllers/Auth
mkdir -p app/Http/Middleware
mkdir -p app/Http/Requests/Auth
mkdir -p app/Models
mkdir -p app/Providers
mkdir -p app/Repositories
mkdir -p app/Services/AI
mkdir -p app/Traits
mkdir -p bootstrap/cache
mkdir -p config
mkdir -p database/factories
mkdir -p database/migrations
mkdir -p database/seeders
mkdir -p public/css
mkdir -p public/js
mkdir -p resources/css
mkdir -p resources/js
mkdir -p resources/views/layouts
mkdir -p resources/views/auth
mkdir -p resources/views/dashboard
mkdir -p resources/views/mood
mkdir -p resources/views/exercises
mkdir -p resources/views/ai
mkdir -p resources/views/profile/partials
mkdir -p resources/views/pages
mkdir -p resources/views/components
mkdir -p routes
mkdir -p storage/app/public
mkdir -p storage/framework/cache
mkdir -p storage/framework/sessions
mkdir -p storage/framework/views
mkdir -p storage/logs
mkdir -p tests/Feature
mkdir -p tests/Unit

echo "Creating root files..."

# Create .env.example
cat > .env.example << 'EOF'
APP_NAME="MindEase"
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mindease
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@mindease.com"
MAIL_FROM_NAME="${APP_NAME}"

# AI Provider (modular)
AI_PROVIDER=openai
OPENAI_API_KEY=
OPENAI_ORGANIZATION=
ANTHROPIC_API_KEY=
EOF

# Create .gitignore (standard Laravel)
cat > .gitignore << 'EOF'
/.idea
/.vscode
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.phpunit.cache
EOF

# Create artisan file
cat > artisan << 'EOF'
#!/usr/bin/env php
<?php

define('LARAVEL_START', microtime(true));

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

$status = $kernel->handle(
    $input = new Symfony\Component\Console\Input\ArgvInput,
    new Symfony\Component\Console\Output\ConsoleOutput
);

$kernel->terminate($input, $status);

exit($status);
EOF

chmod +x artisan

# Create composer.json
cat > composer.json << 'EOF'
{
    "name": "mindease/mindease",
    "type": "project",
    "description": "AI Mental Wellness Platform",
    "keywords": ["laravel", "ai", "wellness"],
    "license": "MIT",
    "require": {
        "php": "^8.2",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^10.10",
        "laravel/sanctum": "^3.3",
        "laravel/tinker": "^2.8"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9.1",
        "laravel/breeze": "^1.26",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.18",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^7.0",
        "phpunit/phpunit": "^10.1"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "files": [
            "app/helpers.php"
        ]
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "minimum-stability": "stable",
    "prefer-stable": true
}
EOF

# Create package.json
cat > package.json << 'EOF'
{
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "devDependencies": {
        "@tailwindcss/forms": "^0.5.2",
        "@tailwindcss/typography": "^0.5.9",
        "alpinejs": "^3.12.0",
        "autoprefixer": "^10.4.14",
        "axios": "^1.1.2",
        "laravel-vite-plugin": "^0.8.0",
        "postcss": "^8.4.21",
        "tailwindcss": "^3.2.4",
        "vite": "^4.0.0"
    }
}
EOF

# Create tailwind.config.js
cat > tailwind.config.js << 'EOF'
/** @type {import('tailwindcss').Config} */
module.exports = {
    darkMode: 'class',
    content: [
        "./resources/**/*.blade.php",
        "./resources/**/*.js",
        "./resources/**/*.vue",
    ],
    theme: {
        extend: {},
    },
    plugins: [
        require('@tailwindcss/forms'),
        require('@tailwindcss/typography'),
    ],
}
EOF

# Create vite.config.js
cat > vite.config.js << 'EOF'
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
    ],
});
EOF

# Create README.md
cat > README.md << 'EOF'
# MindEase - AI Mental Wellness Platform

Flexible version ready for personal testing and future commercial extensions.

## Setup

1. Clone or create project from this script.
2. Run `composer install`
3. Run `npm install && npm run build`
4. Copy `.env.example` to `.env` and configure database.
5. Run `php artisan key:generate`
6. Run `php artisan migrate --seed`
7. Run `php artisan serve`

## Features

- User authentication
- Mood tracking
- Exercises library
- Modular AI Agent (OpenAI/Anthropic)
- Dark mode & RTL support
- SEO & AdSense ready
- Repository pattern, service layer
- Future extensions: installer, theme panel, multi-language, freemium
EOF

# Create public/robots.txt
cat > public/robots.txt << 'EOF'
User-agent: *
Disallow:
Sitemap: {{ url('/sitemap.xml') }}
EOF

# Create public/.htaccess (default Laravel)
cat > public/.htaccess << 'EOF'
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
EOF

# Create public/index.php (default Laravel)
cat > public/index.php << 'EOF'
<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
    require $maintenance;
}

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$response = $kernel->handle(
    $request = Request::capture()
)->send();

$kernel->terminate($request, $response);
EOF

# Create bootstrap/app.php (default Laravel)
cat > bootstrap/app.php << 'EOF'
<?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
*/

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
*/

return $app;
EOF

# Create config/app.php (we'll use default Laravel, but we'll generate a minimal version)
cat > config/app.php << 'EOF'
<?php

use Illuminate\Support\Facades\Facade;

return [
    'name' => env('APP_NAME', 'Laravel'),
    'env' => env('APP_ENV', 'production'),
    'debug' => (bool) env('APP_DEBUG', false),
    'url' => env('APP_URL', 'http://localhost'),
    'asset_url' => env('ASSET_URL'),
    'timezone' => 'UTC',
    'locale' => 'en',
    'fallback_locale' => 'en',
    'faker_locale' => 'en_US',
    'key' => env('APP_KEY'),
    'cipher' => 'AES-256-CBC',
    'maintenance' => [
        'driver' => 'file',
    ],
    'providers' => [
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
    ],
    'aliases' => Facade::defaultAliases()->merge([
        // 'Example' => App\Facades\Example::class,
    ])->toArray(),
];
EOF

# Create config/auth.php (default Laravel)
cat > config/auth.php << 'EOF'
<?php

return [
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
    ],
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_reset_tokens',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],
    'password_timeout' => 10800,
];
EOF

# Create config/database.php (default Laravel)
cat > config/database.php << 'EOF'
<?php

use Illuminate\Support\Str;

return [
    'default' => env('DB_CONNECTION', 'mysql'),
    'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],
        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
    ],
    'migrations' => 'migrations',
    'redis' => [
        'client' => env('REDIS_CLIENT', 'phpredis'),
        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],
        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],
    ],
];
EOF

# Create config/mindease.php
cat > config/mindease.php << 'EOF'
<?php

return [
    'ai' => [
        'provider' => env('AI_PROVIDER', 'openai'),
        'rate_limit' => env('AI_RATE_LIMIT', 60),
    ],
    'adsense' => [
        'enabled' => env('ADSENSE_ENABLED', false),
        'publisher_id' => env('ADSENSE_PUBLISHER_ID', ''),
        'slots' => [
            'header' => env('ADSENSE_SLOT_HEADER', ''),
            'sidebar' => env('ADSENSE_SLOT_SIDEBAR', ''),
            'footer' => env('ADSENSE_SLOT_FOOTER', ''),
        ],
    ],
];
EOF

# Create config/services.php
cat > config/services.php << 'EOF'
<?php

return [
    'openai' => [
        'api_key' => env('OPENAI_API_KEY'),
        'organization' => env('OPENAI_ORGANIZATION'),
        'model' => env('OPENAI_MODEL', 'gpt-3.5-turbo'),
    ],
    'anthropic' => [
        'api_key' => env('ANTHROPIC_API_KEY'),
        'model' => env('ANTHROPIC_MODEL', 'claude-2'),
    ],
];
EOF

# Now create app files

# app/helpers.php
cat > app/helpers.php << 'EOF'
<?php

if (!function_exists('setting')) {
    function setting($key, $default = null)
    {
        return app(\App\Repositories\SettingRepository::class)->get($key, $default);
    }
}
EOF

# app/Console/Kernel.php
cat > app/Console/Kernel.php << 'EOF'
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule): void
    {
        // $schedule->command('ai:cleanup')->daily();
    }

    protected function commands(): void
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
EOF

# app/Exceptions/Handler.php
cat > app/Exceptions/Handler.php << 'EOF'
<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
}
EOF

# app/Http/Kernel.php
cat > app/Http/Kernel.php << 'EOF'
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\DarkMode::class,
            \App\Http\Middleware\RtlMiddleware::class,
        ],

        'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}
EOF

# app/Http/Middleware/DarkMode.php
cat > app/Http/Middleware/DarkMode.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class DarkMode
{
    public function handle(Request $request, Closure $next)
    {
        $darkMode = $request->cookie('dark_mode') === 'true' ||
            ($request->user() && $request->user()->dark_mode);

        view()->share('darkMode', $darkMode);

        return $next($request);
    }
}
EOF

# app/Http/Middleware/RtlMiddleware.php
cat > app/Http/Middleware/RtlMiddleware.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RtlMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $rtl = $request->cookie('rtl') === 'true' ||
            ($request->user() && $request->user()->locale === 'ar');

        view()->share('rtl', $rtl);

        return $next($request);
    }
}
EOF

# app/Http/Middleware/Authenticate.php (default)
cat > app/Http/Middleware/Authenticate.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }
}
EOF

# app/Http/Middleware/RedirectIfAuthenticated.php (default)
cat > app/Http/Middleware/RedirectIfAuthenticated.php << 'EOF'
<?php

namespace App\Http\Middleware;

use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfAuthenticated
{
    public function handle(Request $request, Closure $next, string ...$guards): Response
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                return redirect(RouteServiceProvider::HOME);
            }
        }

        return $next($request);
    }
}
EOF

# app/Http/Middleware/TrimStrings.php (default)
cat > app/Http/Middleware/TrimStrings.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;

class TrimStrings extends Middleware
{
    protected $except = [
        'current_password',
        'password',
        'password_confirmation',
    ];
}
EOF

# app/Http/Middleware/TrustProxies.php (default)
cat > app/Http/Middleware/TrustProxies.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;

class TrustProxies extends Middleware
{
    protected $proxies;
    protected $headers =
        Request::HEADER_X_FORWARDED_FOR |
        Request::HEADER_X_FORWARDED_HOST |
        Request::HEADER_X_FORWARDED_PORT |
        Request::HEADER_X_FORWARDED_PROTO |
        Request::HEADER_X_FORWARDED_AWS_ELB;
}
EOF

# app/Http/Middleware/VerifyCsrfToken.php (default)
cat > app/Http/Middleware/VerifyCsrfToken.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        //
    ];
}
EOF

# app/Http/Middleware/EncryptCookies.php (default)
cat > app/Http/Middleware/EncryptCookies.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    protected $except = [
        //
    ];
}
EOF

# app/Http/Middleware/PreventRequestsDuringMaintenance.php (default)
cat > app/Http/Middleware/PreventRequestsDuringMaintenance.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;

class PreventRequestsDuringMaintenance extends Middleware
{
    protected $except = [
        //
    ];
}
EOF

# app/Http/Middleware/TrustHosts.php (default)
cat > app/Http/Middleware/TrustHosts.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Http\Middleware\TrustHosts as Middleware;

class TrustHosts extends Middleware
{
    public function hosts(): array
    {
        return [
            $this->allSubdomainsOfApplicationUrl(),
        ];
    }
}
EOF

# app/Http/Middleware/ValidateSignature.php (default)
cat > app/Http/Middleware/ValidateSignature.php << 'EOF'
<?php

namespace App\Http\Middleware;

use Illuminate\Routing\Middleware\ValidateSignature as Middleware;

class ValidateSignature extends Middleware
{
    protected $except = [
        // 'unignore', 'these',
    ];
}
EOF

# app/Http/Controllers/PageController.php
cat > app/Http/Controllers/PageController.php << 'EOF'
<?php

namespace App\Http\Controllers;

use App\Services\MetaService;
use Illuminate\Http\Request;

class PageController extends Controller
{
    protected $metaService;

    public function __construct(MetaService $metaService)
    {
        $this->metaService = $metaService;
    }

    public function home()
    {
        $meta = $this->metaService
            ->setTitle('Home')
            ->setDescription('AI Mental Wellness Platform for your daily peace')
            ->render();

        return view('pages.home', compact('meta'));
    }

    public function about()
    {
        $meta = $this->metaService
            ->setTitle('About Us')
            ->setDescription('Learn about MindEase mission')
            ->render();

        return view('pages.about', compact('meta'));
    }

    public function contact()
    {
        $meta = $this->metaService
            ->setTitle('Contact')
            ->setDescription('Get in touch with MindEase team')
            ->render();

        return view('pages.contact', compact('meta'));
    }

    public function privacy()
    {
        $meta = $this->metaService
            ->setTitle('Privacy Policy')
            ->render();

        return view('pages.privacy', compact('meta'));
    }

    public function terms()
    {
        $meta = $this->metaService
            ->setTitle('Terms of Service')
            ->render();

        return view('pages.terms', compact('meta'));
    }

    public function disclaimer()
    {
        $meta = $this->metaService
            ->setTitle('Disclaimer')
            ->render();

        return view('pages.disclaimer', compact('meta'));
    }

    public function sitemap()
    {
        $urls = [
            route('home'),
            route('about'),
            route('contact'),
            route('privacy'),
            route('terms'),
            route('disclaimer'),
            route('login'),
            route('register'),
        ];

        return response()->view('pages.sitemap', compact('urls'))->header('Content-Type', 'application/xml');
    }
}
EOF

# app/Http/Controllers/DashboardController.php
cat > app/Http/Controllers/DashboardController.php << 'EOF'
<?php

namespace App\Http\Controllers;

use App\Services\MoodService;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    protected $moodService;

    public function __construct(MoodService $moodService)
    {
        $this->moodService = $moodService;
    }

    public function index()
    {
        $recentMoods = $this->moodService->getRecentMoods(7);
        $moodStats = $this->moodService->getMoodStats(30);
        $recentChats = auth()->user()->aiConversations()->latest()->take(5)->get();

        return view('dashboard.index', compact('recentMoods', 'moodStats', 'recentChats'));
    }
}
EOF

# app/Http/Controllers/MoodController.php
cat > app/Http/Controllers/MoodController.php << 'EOF'
<?php

namespace App\Http\Controllers;

use App\Http\Requests\MoodRequest;
use App\Services\MoodService;
use App\Repositories\MoodEntryRepository;

class MoodController extends Controller
{
    protected $moodService;
    protected $moodRepo;

    public function __construct(MoodService $moodService, MoodEntryRepository $moodRepo)
    {
        $this->moodService = $moodService;
        $this->moodRepo = $moodRepo;
    }

    public function index()
    {
        $moods = $this->moodRepo->getUserMoods(auth()->id());
        return view('mood.index', compact('moods'));
    }

    public function create()
    {
        return view('mood.create');
    }

    public function store(MoodRequest $request)
    {
        $this->moodService->createMood($request->validated());
        return redirect()->route('moods.index')->with('success', 'Mood entry saved.');
    }

    public function show($id)
    {
        $mood = $this->moodRepo->find($id);
        $this->authorize('view', $mood);
        return view('mood.show', compact('mood'));
    }
}
EOF

# app/Http/Controllers/ExerciseController.php
cat > app/Http/Controllers/ExerciseController.php << 'EOF'
<?php

namespace App\Http\Controllers;

use App\Services\ExerciseService;
use App\Repositories\ExerciseRepository;
use Illuminate\Http\Request;

class ExerciseController extends Controller
{
    protected $exerciseService;
    protected $exerciseRepo;

    public function __construct(ExerciseService $exerciseService, ExerciseRepository $exerciseRepo)
    {
        $this->exerciseService = $exerciseService;
        $this->exerciseRepo = $exerciseRepo;
    }

    public function index(Request $request)
    {
        $category = $request->get('category');
        $exercises = $category
            ? $this->exerciseRepo->findByField('category', $category)
            : $this->exerciseService->getAllExercises();

        return view('exercises.index', compact('exercises', 'category'));
    }

    public function show($slug)
    {
        $exercise = $this->exerciseService->getExerciseBySlug($slug);
        if ($exercise->is_premium && !auth()->user()->isPremium()) {
            return redirect()->route('subscription')->with('error', 'This is a premium exercise.');
        }
        return view('exercises.show', compact('exercise'));
    }
}
EOF

# app/Http/Controllers/AIChatController.php
cat > app/Http/Controllers/AIChatController.php << 'EOF'
<?php

namespace App\Http\Controllers;

use App\Services\AI\AgentService;
use App\Repositories\AIConversationRepository;
use Illuminate\Http\Request;

class AIChatController extends Controller
{
    protected $agentService;
    protected $conversationRepo;

    public function __construct(AgentService $agentService, AIConversationRepository $conversationRepo)
    {
        $this->agentService = $agentService;
        $this->conversationRepo = $conversationRepo;
    }

    public function index()
    {
        return view('ai.chat');
    }

    public function send(Request $request)
    {
        $request->validate(['message' => 'required|string']);

        $result = $this->agentService->processMessage(auth()->user(), $request->message);

        if ($request->wantsJson()) {
            return response()->json($result);
        }

        return redirect()->route('ai.history')->with('success', 'Response received.');
    }

    public function history()
    {
        $conversations = $this->conversationRepo->getUserConversations(auth()->id());
        return view('ai.history', compact('conversations'));
    }

    public function show($id)
    {
        $conversation = $this->conversationRepo->find($id);
        $this->authorize('view', $conversation);
        return view('ai.show', compact('conversation'));
    }
}
EOF

# app/Http/Controllers/ProfileController.php
cat > app/Http/Controllers/ProfileController.php << 'EOF'
<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class ProfileController extends Controller
{
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $request->user()->fill($request->validated());

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        $request->user()->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }

    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::to('/');
    }
}
EOF

# app/Http/Controllers/Auth/RegisteredUserController.php
cat > app/Http/Controllers/Auth/RegisteredUserController.php << 'EOF'
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    public function create(): View
    {
        return view('auth.register');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

        Auth::login($user);

        return redirect(RouteServiceProvider::HOME);
    }
}
EOF

# app/Http/Controllers/Auth/AuthenticatedSessionController.php
cat > app/Http/Controllers/Auth/AuthenticatedSessionController.php << 'EOF'
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    public function create(): View
    {
        return view('auth.login');
    }

    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

        return redirect()->intended(RouteServiceProvider::HOME);
    }

    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}
EOF

# app/Http/Controllers/Auth/PasswordController.php
cat > app/Http/Controllers/Auth/PasswordController.php << 'EOF'
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class PasswordController extends Controller
{
    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validateWithBag('updatePassword', [
            'current_password' => ['required', 'current_password'],
            'password' => ['required', Password::defaults(), 'confirmed'],
        ]);

        $request->user()->update([
            'password' => Hash::make($validated['password']),
        ]);

        return back()->with('status', 'password-updated');
    }
}
EOF

# app/Http/Requests/Auth/LoginRequest.php
cat > app/Http/Requests/Auth/LoginRequest.php << 'EOF'
<?php

namespace App\Http\Requests\Auth;

use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class LoginRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ];
    }

    public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();

        if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'email' => trans('auth.failed'),
            ]);
        }

        RateLimiter::clear($this->throttleKey());
    }

    public function ensureIsNotRateLimited(): void
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
            return;
        }

        event(new Lockout($this));

        $seconds = RateLimiter::availableIn($this->throttleKey());

        throw ValidationException::withMessages([
            'email' => trans('auth.throttle', [
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    }

    public function throttleKey(): string
    {
        return Str::transliterate(Str::lower($this->input('email')).'|'.$this->ip());
    }
}
EOF

# app/Http/Requests/MoodRequest.php
cat > app/Http/Requests/MoodRequest.php << 'EOF'
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MoodRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'mood_score' => 'required|integer|min:1|max:10',
            'notes' => 'nullable|string|max:1000',
            'entry_date' => 'nullable|date|before_or_equal:today',
        ];
    }
}
EOF

# app/Http/Requests/ProfileUpdateRequest.php
cat > app/Http/Requests/ProfileUpdateRequest.php << 'EOF'
<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
        ];
    }
}
EOF

# app/Models/User.php
cat > app/Models/User.php << 'EOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'locale', 'dark_mode',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'dark_mode' => 'boolean',
    ];

    public function moodEntries()
    {
        return $this->hasMany(MoodEntry::class);
    }

    public function aiConversations()
    {
        return $this->hasMany(AIConversation::class);
    }

    public function subscription()
    {
        return $this->hasOne(Subscription::class)->where('is_active', true);
    }

    public function isPremium()
    {
        return $this->subscription && $this->subscription->plan !== 'free';
    }
}
EOF

# app/Models/MoodEntry.php
cat > app/Models/MoodEntry.php << 'EOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MoodEntry extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'mood_score', 'notes', 'entry_date',
    ];

    protected $casts = [
        'entry_date' => 'date',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
EOF

# app/Models/Exercise.php
cat > app/Models/Exercise.php << 'EOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Exercise extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'slug', 'description', 'content', 'category', 'duration', 'image', 'is_premium',
    ];

    protected $casts = [
        'is_premium' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($exercise) {
            if (empty($exercise->slug)) {
                $exercise->slug = \Str::slug($exercise->title);
            }
        });
    }
}
EOF

# app/Models/AIConversation.php
cat > app/Models/AIConversation.php << 'EOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AIConversation extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'user_message', 'assistant_response', 'context', 'model_used', 'tokens_used',
    ];

    protected $casts = [
        'context' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
EOF

# app/Models/Subscription.php
cat > app/Models/Subscription.php << 'EOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Subscription extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'plan', 'starts_at', 'ends_at', 'is_active',
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
        'is_active' => 'boolean',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
EOF

# app/Models/Setting.php
cat > app/Models/Setting.php << 'EOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable = ['key', 'value', 'type'];

    public $timestamps = true;

    public function getValueAttribute($value)
    {
        switch ($this->type) {
            case 'integer':
                return (int) $value;
            case 'boolean':
                return (bool) $value;
            case 'json':
                return json_decode($value, true);
            default:
                return $value;
        }
    }

    public function setValueAttribute($value)
    {
        if ($this->type === 'json' && !is_string($value)) {
            $value = json_encode($value);
        }
        $this->attributes['value'] = $value;
    }
}
EOF

# app/Providers/AppServiceProvider.php
cat > app/Providers/AppServiceProvider.php << 'EOF'
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        //
    }
}
EOF

# app/Providers/AuthServiceProvider.php (default)
cat > app/Providers/AuthServiceProvider.php << 'EOF'
<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [];

    public function boot(): void
    {
        $this->registerPolicies();
    }
}
EOF

# app/Providers/EventServiceProvider.php (default)
cat > app/Providers/EventServiceProvider.php << 'EOF'
<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    public function boot(): void
    {
        //
    }

    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}
EOF

# app/Providers/RouteServiceProvider.php
cat > app/Providers/RouteServiceProvider.php << 'EOF'
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    public const HOME = '/dashboard';

    public function boot(): void
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }
}
EOF

# app/Repositories/BaseRepositoryInterface.php
cat > app/Repositories/BaseRepositoryInterface.php << 'EOF'
<?php

namespace App\Repositories;

interface BaseRepositoryInterface
{
    public function all();
    public function find($id);
    public function create(array $data);
    public function update($id, array $data);
    public function delete($id);
    public function findByField($field, $value);
}
EOF

# app/Repositories/BaseRepository.php
cat > app/Repositories/BaseRepository.php << 'EOF'
<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;

abstract class BaseRepository implements BaseRepositoryInterface
{
    protected $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    public function all()
    {
        return $this->model->all();
    }

    public function find($id)
    {
        return $this->model->findOrFail($id);
    }

    public function create(array $data)
    {
        return $this->model->create($data);
    }

    public function update($id, array $data)
    {
        $record = $this->find($id);
        $record->update($data);
        return $record;
    }

    public function delete($id)
    {
        return $this->find($id)->delete();
    }

    public function findByField($field, $value)
    {
        return $this->model->where($field, $value)->get();
    }
}
EOF

# app/Repositories/UserRepository.php
cat > app/Repositories/UserRepository.php << 'EOF'
<?php

namespace App\Repositories;

use App\Models\User;

class UserRepository extends BaseRepository
{
    public function __construct(User $model)
    {
        parent::__construct($model);
    }

    public function findByEmail($email)
    {
        return $this->model->where('email', $email)->first();
    }
}
EOF

# app/Repositories/MoodEntryRepository.php
cat > app/Repositories/MoodEntryRepository.php << 'EOF'
<?php

namespace App\Repositories;

use App\Models\MoodEntry;

class MoodEntryRepository extends BaseRepository
{
    public function __construct(MoodEntry $model)
    {
        parent::__construct($model);
    }

    public function getUserMoods($userId, $limit = null)
    {
        $query = $this->model->where('user_id', $userId)->orderBy('entry_date', 'desc');
        if ($limit) {
            $query->limit($limit);
        }
        return $query->get();
    }

    public function getMoodStats($userId, $days = 30)
    {
        return $this->model->where('user_id', $userId)
            ->where('entry_date', '>=', now()->subDays($days))
            ->selectRaw('AVG(mood_score) as average, DATE(entry_date) as date')
            ->groupBy('date')
            ->orderBy('date')
            ->get();
    }
}
EOF

# app/Repositories/ExerciseRepository.php
cat > app/Repositories/ExerciseRepository.php << 'EOF'
<?php

namespace App\Repositories;

use App\Models\Exercise;

class ExerciseRepository extends BaseRepository
{
    public function __construct(Exercise $model)
    {
        parent::__construct($model);
    }

    public function findBySlug($slug)
    {
        return $this->model->where('slug', $slug)->firstOrFail();
    }

    public function getPublished($premium = false)
    {
        return $this->model->where('is_premium', $premium)->get();
    }
}
EOF

# app/Repositories/AIConversationRepository.php
cat > app/Repositories/AIConversationRepository.php << 'EOF'
<?php

namespace App\Repositories;

use App\Models\AIConversation;

class AIConversationRepository extends BaseRepository
{
    public function __construct(AIConversation $model)
    {
        parent::__construct($model);
    }

    public function getUserConversations($userId)
    {
        return $this->model->where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->paginate(20);
    }
}
EOF

# app/Repositories/SubscriptionRepository.php
cat > app/Repositories/SubscriptionRepository.php << 'EOF'
<?php

namespace App\Repositories;

use App\Models\Subscription;

class SubscriptionRepository extends BaseRepository
{
    public function __construct(Subscription $model)
    {
        parent::__construct($model);
    }

    public function getActiveUserSubscription($userId)
    {
        return $this->model->where('user_id', $userId)
            ->where('is_active', true)
            ->first();
    }
}
EOF

# app/Repositories/SettingRepository.php
cat > app/Repositories/SettingRepository.php << 'EOF'
<?php

namespace App\Repositories;

use App\Models\Setting;

class SettingRepository extends BaseRepository
{
    public function __construct(Setting $model)
    {
        parent::__construct($model);
    }

    public function get($key, $default = null)
    {
        $setting = $this->model->where('key', $key)->first();
        return $setting ? $setting->value : $default;
    }

    public function set($key, $value, $type = 'string')
    {
        return $this->model->updateOrCreate(
            ['key' => $key],
            ['value' => $value, 'type' => $type]
        );
    }
}
EOF

# app/Services/MetaService.php
cat > app/Services/MetaService.php << 'EOF'
<?php

namespace App\Services;

class MetaService
{
    protected $title;
    protected $description;
    protected $image;
    protected $url;
    protected $type = 'website';
    protected $siteName;

    public function __construct()
    {
        $this->siteName = config('app.name');
        $this->url = request()->url();
    }

    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }

    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    public function setImage($image)
    {
        $this->image = $image;
        return $this;
    }

    public function setUrl($url)
    {
        $this->url = $url;
        return $this;
    }

    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    public function render()
    {
        $title = $this->title ? $this->title . ' - ' . $this->siteName : $this->siteName;
        $description = $this->description ?? setting('meta_description', 'AI Mental Wellness Platform');
        $image = $this->image ?? asset('images/og-default.jpg');

        $html = '';
        $html .= "<title>{$title}</title>\n";
        $html .= "<meta name=\"description\" content=\"{$description}\">\n";
        $html .= "<meta property=\"og:title\" content=\"{$title}\">\n";
        $html .= "<meta property=\"og:description\" content=\"{$description}\">\n";
        $html .= "<meta property=\"og:image\" content=\"{$image}\">\n";
        $html .= "<meta property=\"og:url\" content=\"{$this->url}\">\n";
        $html .= "<meta property=\"og:type\" content=\"{$this->type}\">\n";
        $html .= "<meta property=\"og:site_name\" content=\"{$this->siteName}\">\n";
        $html .= "<meta name=\"twitter:card\" content=\"summary_large_image\">\n";
        $html .= "<meta name=\"twitter:title\" content=\"{$title}\">\n";
        $html .= "<meta name=\"twitter:description\" content=\"{$description}\">\n";
        $html .= "<meta name=\"twitter:image\" content=\"{$image}\">\n";

        return $html;
    }
}
EOF

# app/Services/MoodService.php
cat > app/Services/MoodService.php << 'EOF'
<?php

namespace App\Services;

use App\Repositories\MoodEntryRepository;
use Illuminate\Support\Facades\Auth;

class MoodService
{
    protected $moodRepo;

    public function __construct(MoodEntryRepository $moodRepo)
    {
        $this->moodRepo = $moodRepo;
    }

    public function getRecentMoods($limit = 7)
    {
        return $this->moodRepo->getUserMoods(Auth::id(), $limit);
    }

    public function getMoodStats($days = 30)
    {
        return $this->moodRepo->getMoodStats(Auth::id(), $days);
    }

    public function createMood(array $data)
    {
        $data['user_id'] = Auth::id();
        $data['entry_date'] = $data['entry_date'] ?? now()->toDateString();
        return $this->moodRepo->create($data);
    }
}
EOF

# app/Services/ExerciseService.php
cat > app/Services/ExerciseService.php << 'EOF'
<?php

namespace App\Services;

use App\Repositories\ExerciseRepository;

class ExerciseService
{
    protected $exerciseRepo;

    public function __construct(ExerciseRepository $exerciseRepo)
    {
        $this->exerciseRepo = $exerciseRepo;
    }

    public function getAllExercises($premiumFilter = false)
    {
        return $this->exerciseRepo->getPublished($premiumFilter);
    }

    public function getExerciseBySlug($slug)
    {
        return $this->exerciseRepo->findBySlug($slug);
    }
}
EOF

# app/Services/AI/AgentService.php
cat > app/Services/AI/AgentService.php << 'EOF'
<?php

namespace App\Services\AI;

use App\Models\User;
use App\Repositories\AIConversationRepository;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;

class AgentService
{
    protected $promptBuilder;
    protected $contextManager;
    protected $memoryManager;
    protected $decisionEngine;
    protected $recommendationEngine;
    protected $conversationRepo;
    protected $provider;
    protected $apiKey;
    protected $model;

    public function __construct(
        PromptBuilder $promptBuilder,
        ContextManager $contextManager,
        MemoryManager $memoryManager,
        DecisionEngine $decisionEngine,
        RecommendationEngine $recommendationEngine,
        AIConversationRepository $conversationRepo
    ) {
        $this->promptBuilder = $promptBuilder;
        $this->contextManager = $contextManager;
        $this->memoryManager = $memoryManager;
        $this->decisionEngine = $decisionEngine;
        $this->recommendationEngine = $recommendationEngine;
        $this->conversationRepo = $conversationRepo;

        $this->provider = config('mindease.ai.provider', 'openai');
        $this->apiKey = config("services.{$this->provider}.api_key");
        $this->model = config("services.{$this->provider}.model", 'gpt-3.5-turbo');
    }

    public function processMessage(User $user, string $message): array
    {
        $context = $this->contextManager->buildContext($user);
        $memory = $this->memoryManager->getRecentMemory($user);
        $prompt = $this->promptBuilder->build($message, $context, $memory);
        $action = $this->decisionEngine->decide($prompt);
        $response = $this->callAIProvider($prompt);
        $recommendations = $this->recommendationEngine->generate($user, $message, $response);

        $conversation = $this->conversationRepo->create([
            'user_id' => $user->id,
            'user_message' => $message,
            'assistant_response' => $response,
            'context' => $context,
            'model_used' => $this->model,
            'tokens_used' => $this->estimateTokens($prompt . $response),
        ]);

        $this->memoryManager->store($user, $message, $response);

        return [
            'response' => $response,
            'conversation_id' => $conversation->id,
            'recommendations' => $recommendations,
        ];
    }

    protected function callAIProvider(string $prompt): string
    {
        if ($this->provider === 'openai') {
            $response = Http::withToken($this->apiKey)
                ->post('https://api.openai.com/v1/chat/completions', [
                    'model' => $this->model,
                    'messages' => [
                        ['role' => 'system', 'content' => 'You are a helpful mental wellness assistant.'],
                        ['role' => 'user', 'content' => $prompt],
                    ],
                    'temperature' => 0.7,
                ]);

            if ($response->failed()) {
                Log::error('OpenAI API error: ' . $response->body());
                return 'Sorry, I am having trouble responding right now.';
            }

            return $response->json('choices.0.message.content');
        }

        return 'AI response placeholder';
    }

    protected function estimateTokens(string $text): int
    {
        return (int) (strlen($text) / 4);
    }
}
EOF

# app/Services/AI/PromptBuilder.php
cat > app/Services/AI/PromptBuilder.php << 'EOF'
<?php

namespace App\Services\AI;

class PromptBuilder
{
    public function build(string $message, array $context, array $memory): string
    {
        $prompt = "Context:\n";
        foreach ($context as $key => $value) {
            $prompt .= "- $key: " . (is_array($value) ? json_encode($value) : $value) . "\n";
        }

        if (!empty($memory)) {
            $prompt .= "\nRecent conversation:\n";
            foreach ($memory as $mem) {
                $prompt .= "User: {$mem['user']}\nAssistant: {$mem['assistant']}\n";
            }
        }

        $prompt .= "\nUser: $message\nAssistant:";

        return $prompt;
    }
}
EOF

# app/Services/AI/ContextManager.php
cat > app/Services/AI/ContextManager.php << 'EOF'
<?php

namespace App\Services\AI;

use App\Models\User;
use App\Repositories\MoodEntryRepository;
use App\Repositories\ExerciseRepository;

class ContextManager
{
    protected $moodRepo;
    protected $exerciseRepo;

    public function __construct(MoodEntryRepository $moodRepo, ExerciseRepository $exerciseRepo)
    {
        $this->moodRepo = $moodRepo;
        $this->exerciseRepo = $exerciseRepo;
    }

    public function buildContext(User $user): array
    {
        $recentMoods = $this->moodRepo->getUserMoods($user->id, 5);
        $lastExercise = $user->aiConversations()->latest()->first();

        return [
            'user_name' => $user->name,
            'recent_moods' => $recentMoods->pluck('mood_score', 'entry_date')->toArray(),
            'last_ai_interaction' => $lastExercise ? $lastExercise->created_at->diffForHumans() : null,
            'is_premium' => $user->isPremium(),
            'current_time' => now()->toDateTimeString(),
        ];
    }
}
EOF

# app/Services/AI/MemoryManager.php
cat > app/Services/AI/MemoryManager.php << 'EOF'
<?php

namespace App\Services\AI;

use App\Models\User;
use App\Repositories\AIConversationRepository;

class MemoryManager
{
    protected $conversationRepo;

    public function __construct(AIConversationRepository $conversationRepo)
    {
        $this->conversationRepo = $conversationRepo;
    }

    public function getRecentMemory(User $user, int $limit = 5): array
    {
        $conversations = $this->conversationRepo->getUserConversations($user->id)
            ->take($limit)
            ->map(function ($conv) {
                return [
                    'user' => $conv->user_message,
                    'assistant' => $conv->assistant_response,
                    'time' => $conv->created_at->toDateTimeString(),
                ];
            })->toArray();

        return $conversations;
    }

    public function store(User $user, string $message, string $response): void
    {
        // already stored
    }
}
EOF

# app/Services/AI/DecisionEngine.php
cat > app/Services/AI/DecisionEngine.php << 'EOF'
<?php

namespace App\Services\AI;

class DecisionEngine
{
    public function decide(string $prompt): string
    {
        return 'api';
    }
}
EOF

# app/Services/AI/RecommendationEngine.php
cat > app/Services/AI/RecommendationEngine.php << 'EOF'
<?php

namespace App\Services\AI;

use App\Models\User;
use App\Repositories\ExerciseRepository;

class RecommendationEngine
{
    protected $exerciseRepo;

    public function __construct(ExerciseRepository $exerciseRepo)
    {
        $this->exerciseRepo = $exerciseRepo;
    }

    public function generate(User $user, string $message, string $response): array
    {
        $recommendations = [];
        $keywords = ['stress', 'anxiety', 'sleep', 'focus', 'gratitude'];

        foreach ($keywords as $keyword) {
            if (stripos($message, $keyword) !== false || stripos($response, $keyword) !== false) {
                $exercises = $this->exerciseRepo->findByField('category', $keyword);
                foreach ($exercises as $ex) {
                    $recommendations[] = [
                        'title' => $ex->title,
                        'slug' => $ex->slug,
                        'reason' => "Based on your mention of '{$keyword}'",
                    ];
                }
            }
        }

        return array_slice($recommendations, 0, 3);
    }
}
EOF

# app/Console/Commands/TestAI.php
cat > app/Console/Commands/TestAI.php << 'EOF'
<?php

namespace App\Console\Commands;

use App\Services\AI\AgentService;
use App\Models\User;
use Illuminate\Console\Command;

class TestAI extends Command
{
    protected $signature = 'ai:test {user?}';
    protected $description = 'Test AI agent with a user';

    public function handle(AgentService $agent)
    {
        $userId = $this->argument('user') ?? 1;
        $user = User::find($userId);
        if (!$user) {
            $this->error('User not found');
            return 1;
        }

        $message = $this->ask('Enter your message');
        $result = $agent->processMessage($user, $message);
        $this->info('Response: ' . $result['response']);
        $this->info('Recommendations: ' . json_encode($result['recommendations']));
        return 0;
    }
}
EOF

# routes/web.php
cat > routes/web.php << 'EOF'
<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\MoodController;
use App\Http\Controllers\ExerciseController;
use App\Http\Controllers\AIChatController;
use App\Http\Controllers\PageController;
use Illuminate\Support\Facades\Route;

Route::get('/', [PageController::class, 'home'])->name('home');
Route::get('/about', [PageController::class, 'about'])->name('about');
Route::get('/contact', [PageController::class, 'contact'])->name('contact');
Route::get('/privacy', [PageController::class, 'privacy'])->name('privacy');
Route::get('/terms', [PageController::class, 'terms'])->name('terms');
Route::get('/disclaimer', [PageController::class, 'disclaimer'])->name('disclaimer');
Route::get('/sitemap.xml', [PageController::class, 'sitemap'])->name('sitemap');

Route::post('/dark-mode/toggle', function (Illuminate\Http\Request $request) {
    $darkMode = $request->cookie('dark_mode') === 'true' ? 'false' : 'true';
    return redirect()->back()->withCookie(cookie('dark_mode', $darkMode, 60*24*365));
})->name('dark-mode.toggle');

Route::post('/rtl/toggle', function (Illuminate\Http\Request $request) {
    $rtl = $request->cookie('rtl') === 'true' ? 'false' : 'true';
    return redirect()->back()->withCookie(cookie('rtl', $rtl, 60*24*365));
})->name('rtl.toggle');

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::resource('moods', MoodController::class)->except(['edit', 'update']);
    Route::get('/exercises', [ExerciseController::class, 'index'])->name('exercises.index');
    Route::get('/exercises/{exercise}', [ExerciseController::class, 'show'])->name('exercises.show');
    Route::get('/ai/chat', [AIChatController::class, 'index'])->name('ai.chat');
    Route::post('/ai/chat', [AIChatController::class, 'send'])->name('ai.send');
    Route::get('/ai/history', [AIChatController::class, 'history'])->name('ai.history');
    Route::get('/ai/conversation/{conversation}', [AIChatController::class, 'show'])->name('ai.conversation');
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

require __DIR__.'/auth.php';
EOF

# routes/auth.php
cat > routes/auth.php << 'EOF'
<?php

use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\ConfirmablePasswordController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Auth\VerifyEmailController;
use Illuminate\Support\Facades\Route;

Route::middleware('guest')->group(function () {
    Route::get('register', [RegisteredUserController::class, 'create'])
                ->name('register');

    Route::post('register', [RegisteredUserController::class, 'store']);

    Route::get('login', [AuthenticatedSessionController::class, 'create'])
                ->name('login');

    Route::post('login', [AuthenticatedSessionController::class, 'store']);

    Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])
                ->name('password.request');

    Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])
                ->name('password.email');

    Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])
                ->name('password.reset');

    Route::post('reset-password', [NewPasswordController::class, 'store'])
                ->name('password.store');
});

Route::middleware('auth')->group(function () {
    Route::get('verify-email', EmailVerificationPromptController::class)
                ->name('verification.notice');

    Route::get('verify-email/{id}/{hash}', VerifyEmailController::class)
                ->middleware(['signed', 'throttle:6,1'])
                ->name('verification.verify');

    Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
                ->middleware('throttle:6,1')
                ->name('verification.send');

    Route::get('confirm-password', [ConfirmablePasswordController::class, 'show'])
                ->name('password.confirm');

    Route::post('confirm-password', [ConfirmablePasswordController::class, 'store']);

    Route::put('password', [PasswordController::class, 'update'])->name('password.update');

    Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])
                ->name('logout');
});
EOF

# routes/console.php (default)
cat > routes/console.php << 'EOF'
<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
EOF

# routes/api.php (default)
cat > routes/api.php << 'EOF'
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
EOF

# database/migrations/2014_10_12_000000_create_users_table.php
cat > database/migrations/2014_10_12_000000_create_users_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('locale')->default('en');
            $table->boolean('dark_mode')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};
EOF

# database/migrations/2014_10_12_100000_create_password_reset_tokens_table.php
cat > database/migrations/2014_10_12_100000_create_password_reset_tokens_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('password_reset_tokens', function (Blueprint $table) {
            $table->string('email')->primary();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('password_reset_tokens');
    }
};
EOF

# database/migrations/2019_08_19_000001_create_failed_jobs_table.php
cat > database/migrations/2019_08_19_000001_create_failed_jobs_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->id();
            $table->string('uuid')->unique();
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('failed_jobs');
    }
};
EOF

# database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php
cat > database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('personal_access_tokens', function (Blueprint $table) {
            $table->id();
            $table->morphs('tokenable');
            $table->string('name');
            $table->string('token', 64)->unique();
            $table->text('abilities')->nullable();
            $table->timestamp('last_used_at')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('personal_access_tokens');
    }
};
EOF

# database/migrations/2025_01_01_000001_create_mood_entries_table.php
cat > database/migrations/2025_01_01_000001_create_mood_entries_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('mood_entries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->tinyInteger('mood_score');
            $table->text('notes')->nullable();
            $table->date('entry_date')->index();
            $table->timestamps();

            $table->index(['user_id', 'entry_date']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('mood_entries');
    }
};
EOF

# database/migrations/2025_01_01_000002_create_exercises_table.php
cat > database/migrations/2025_01_01_000002_create_exercises_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('exercises', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('description');
            $table->text('content')->nullable();
            $table->string('category');
            $table->integer('duration')->nullable();
            $table->string('image')->nullable();
            $table->boolean('is_premium')->default(false);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('exercises');
    }
};
EOF

# database/migrations/2025_01_01_000003_create_ai_conversations_table.php
cat > database/migrations/2025_01_01_000003_create_ai_conversations_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('ai_conversations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->text('user_message');
            $table->text('assistant_response')->nullable();
            $table->json('context')->nullable();
            $table->string('model_used')->nullable();
            $table->integer('tokens_used')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('ai_conversations');
    }
};
EOF

# database/migrations/2025_01_01_000004_create_subscriptions_table.php
cat > database/migrations/2025_01_01_000004_create_subscriptions_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('plan');
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('subscriptions');
    }
};
EOF

# database/migrations/2025_01_01_000005_create_settings_table.php
cat > database/migrations/2025_01_01_000005_create_settings_table.php << 'EOF'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->text('value')->nullable();
            $table->string('type')->default('string');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('settings');
    }
};
EOF

# database/factories/UserFactory.php
cat > database/factories/UserFactory.php << 'EOF'
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    protected static ?string $password;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'remember_token' => Str::random(10),
        ];
    }

    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}
EOF

# database/factories/MoodEntryFactory.php
cat > database/factories/MoodEntryFactory.php << 'EOF'
<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class MoodEntryFactory extends Factory
{
    public function definition(): array
    {
        return [
            'user_id' => User::factory(),
            'mood_score' => $this->faker->numberBetween(1, 10),
            'notes' => $this->faker->sentence(),
            'entry_date' => $this->faker->dateTimeBetween('-1 month', 'now'),
        ];
    }
}
EOF

# database/factories/ExerciseFactory.php
cat > database/factories/ExerciseFactory.php << 'EOF'
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class ExerciseFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => $this->faker->sentence(3),
            'slug' => $this->faker->slug,
            'description' => $this->faker->paragraph,
            'content' => $this->faker->paragraphs(3, true),
            'category' => $this->faker->randomElement(['mindfulness', 'breathing', 'gratitude', 'focus']),
            'duration' => $this->faker->numberBetween(5, 30),
            'image' => null,
            'is_premium' => $this->faker->boolean(20),
        ];
    }
}
EOF

# database/factories/AIConversationFactory.php
cat > database/factories/AIConversationFactory.php << 'EOF'
<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class AIConversationFactory extends Factory
{
    public function definition(): array
    {
        return [
            'user_id' => User::factory(),
            'user_message' => $this->faker->sentence,
            'assistant_response' => $this->faker->paragraph,
            'context' => ['key' => 'value'],
            'model_used' => 'gpt-3.5-turbo',
            'tokens_used' => $this->faker->numberBetween(10, 200),
        ];
    }
}
EOF

# database/seeders/DatabaseSeeder.php
cat > database/seeders/DatabaseSeeder.php << 'EOF'
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            ExerciseSeeder::class,
            SettingsSeeder::class,
        ]);
    }
}
EOF

# database/seeders/ExerciseSeeder.php
cat > database/seeders/ExerciseSeeder.php << 'EOF'
<?php

namespace Database\Seeders;

use App\Models\Exercise;
use Illuminate\Database\Seeder;

class ExerciseSeeder extends Seeder
{
    public function run(): void
    {
        $exercises = [
            [
                'title' => 'Deep Breathing',
                'description' => 'A simple breathing exercise to calm your mind.',
                'content' => 'Sit comfortably. Inhale deeply through your nose for 4 seconds, hold for 4, exhale through mouth for 6. Repeat 5 times.',
                'category' => 'breathing',
                'duration' => 5,
                'is_premium' => false,
            ],
            [
                'title' => 'Gratitude Journal',
                'description' => 'Write down three things you are grateful for today.',
                'content' => 'Take a few minutes to reflect and write down three specific things you appreciate.',
                'category' => 'gratitude',
                'duration' => 10,
                'is_premium' => false,
            ],
            [
                'title' => 'Body Scan Meditation',
                'description' => 'A guided meditation to release tension.',
                'content' => 'Lie down and slowly bring attention to each part of your body from toes to head.',
                'category' => 'mindfulness',
                'duration' => 15,
                'is_premium' => true,
            ],
        ];

        foreach ($exercises as $ex) {
            Exercise::create($ex);
        }
    }
}
EOF

# database/seeders/SettingsSeeder.php
cat > database/seeders/SettingsSeeder.php << 'EOF'
<?php

namespace Database\Seeders;

use App\Models\Setting;
use Illuminate\Database\Seeder;

class SettingsSeeder extends Seeder
{
    public function run(): void
    {
        Setting::updateOrCreate(['key' => 'site_name'], ['value' => 'MindEase', 'type' => 'string']);
        Setting::updateOrCreate(['key' => 'meta_description'], ['value' => 'AI Mental Wellness Platform', 'type' => 'string']);
        Setting::updateOrCreate(['key' => 'adsense_enabled'], ['value' => false, 'type' => 'boolean']);
    }
}
EOF

# resources/css/app.css
cat > resources/css/app.css << 'EOF'
@tailwind base;
@tailwind components;
@tailwind utilities;
EOF

# resources/js/app.js
cat > resources/js/app.js << 'EOF'
import './bootstrap';
import Alpine from 'alpinejs';

window.Alpine = Alpine;
Alpine.start();
EOF

# resources/js/bootstrap.js
cat > resources/js/bootstrap.js << 'EOF'
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
EOF

# resources/js/dark-mode.js (optional)
cat > resources/js/dark-mode.js << 'EOF'
// Dark mode toggle could be enhanced here
EOF

# resources/views/layouts/app.blade.php
cat > resources/views/layouts/app.blade.php << 'EOF'
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" @if($rtl ?? false) dir="rtl" @endif class="{{ $darkMode ? 'dark' : '' }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    {!! $meta ?? '' !!}

    <link rel="icon" href="{{ asset('favicon.ico') }}">

    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />

    @vite(['resources/css/app.css', 'resources/js/app.js'])

    @include('components.structured-data')
</head>
<body class="font-sans antialiased bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
    <div class="min-h-screen">
        @include('layouts.navigation')

        @if (isset($header))
            <header class="bg-white dark:bg-gray-800 shadow">
                <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
                    {{ $header }}
                </div>
            </header>
        @endif

        <main>
            {{ $slot }}
        </main>
    </div>

    @include('components.ad-slot')
</body>
</html>
EOF

# resources/views/layouts/navigation.blade.php
cat > resources/views/layouts/navigation.blade.php << 'EOF'
<nav class="bg-white dark:bg-gray-800 border-b border-gray-100 dark:border-gray-700">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
            <div class="flex">
                <div class="shrink-0 flex items-center">
                    <a href="{{ route('home') }}">
                        <x-application-logo class="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200" />
                    </a>
                </div>

                <div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
                    <x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
                        {{ __('Dashboard') }}
                    </x-nav-link>
                    <x-nav-link :href="route('moods.index')" :active="request()->routeIs('moods.*')">
                        {{ __('Moods') }}
                    </x-nav-link>
                    <x-nav-link :href="route('exercises.index')" :active="request()->routeIs('exercises.*')">
                        {{ __('Exercises') }}
                    </x-nav-link>
                    <x-nav-link :href="route('ai.chat')" :active="request()->routeIs('ai.*')">
                        {{ __('AI Chat') }}
                    </x-nav-link>
                </div>
            </div>

            <div class="hidden sm:flex sm:items-center sm:ml-6 space-x-4">
                <form method="POST" action="{{ route('dark-mode.toggle') }}">
                    @csrf
                    <button type="submit" class="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300">
                        @if($darkMode)
                            <span class="sr-only">Switch to light mode</span>
                            🌙
                        @else
                            <span class="sr-only">Switch to dark mode</span>
                            ☀️
                        @endif
                    </button>
                </form>

                <form method="POST" action="{{ route('rtl.toggle') }}">
                    @csrf
                    <button type="submit" class="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300">
                        @if($rtl)
                            LTR
                        @else
                            RTL
                        @endif
                    </button>
                </form>

                <x-dropdown align="right" width="48">
                    <x-slot name="trigger">
                        <button class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:text-gray-700 dark:hover:text-gray-300 focus:outline-none transition ease-in-out duration-150">
                            <div>{{ Auth::user()->name }}</div>
                            <div class="ml-1">
                                <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                </svg>
                            </div>
                        </button>
                    </x-slot>

                    <x-slot name="content">
                        <x-dropdown-link :href="route('profile.edit')">
                            {{ __('Profile') }}
                        </x-dropdown-link>
                        <form method="POST" action="{{ route('logout') }}">
                            @csrf
                            <x-dropdown-link :href="route('logout')"
                                    onclick="event.preventDefault();
                                                this.closest('form').submit();">
                                {{ __('Log Out') }}
                            </x-dropdown-link>
                        </form>
                    </x-slot>
                </x-dropdown>
            </div>
        </div>
    </div>
</nav>
EOF

# resources/views/dashboard/index.blade.php
cat > resources/views/dashboard/index.blade.php << 'EOF'
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    <h3 class="text-lg font-medium">Welcome back, {{ auth()->user()->name }}!</h3>

                    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded">
                            <h4 class="font-medium">Recent Moods</h4>
                            @forelse($recentMoods as $mood)
                                <div class="flex justify-between mt-2">
                                    <span>{{ $mood->entry_date->format('M d') }}</span>
                                    <span class="font-bold">{{ $mood->mood_score }}/10</span>
                                </div>
                            @empty
                                <p class="text-gray-500">No moods logged yet. <a href="{{ route('moods.create') }}" class="text-blue-600">Add one</a></p>
                            @endforelse
                        </div>
                        <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded">
                            <h4 class="font-medium">Recent AI Chats</h4>
                            @forelse($recentChats as $chat)
                                <div class="mt-2">
                                    <a href="{{ route('ai.conversation', $chat) }}" class="text-blue-600 hover:underline">
                                        {{ Str::limit($chat->user_message, 50) }}
                                    </a>
                                    <span class="text-sm text-gray-500">{{ $chat->created_at->diffForHumans() }}</span>
                                </div>
                            @empty
                                <p class="text-gray-500">No chats yet. <a href="{{ route('ai.chat') }}" class="text-blue-600">Start a conversation</a></p>
                            @endforelse
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>
EOF

# resources/views/ai/chat.blade.php
cat > resources/views/ai/chat.blade.php << 'EOF'
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('AI Wellness Assistant') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6">
                    <div id="chat-messages" class="space-y-4 h-96 overflow-y-auto p-4 border rounded dark:border-gray-600">
                    </div>

                    <form id="chat-form" class="mt-4 flex space-x-2">
                        @csrf
                        <input type="text" id="message-input" class="flex-1 rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200" placeholder="Type your message..." required>
                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Send</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.getElementById('chat-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const input = document.getElementById('message-input');
            const message = input.value;
            if (!message) return;

            const messagesDiv = document.getElementById('chat-messages');
            messagesDiv.innerHTML += `<div class="text-right"><span class="inline-block bg-blue-100 dark:bg-blue-900 p-2 rounded">${message}</span></div>`;

            fetch('{{ route('ai.send') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({ message })
            })
            .then(res => res.json())
            .then(data => {
                messagesDiv.innerHTML += `<div class="text-left"><span class="inline-block bg-gray-100 dark:bg-gray-700 p-2 rounded">${data.response}</span></div>`;
                input.value = '';
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            })
            .catch(err => console.error(err));
        });
    </script>
    @endpush
</x-app-layout>
EOF

# resources/views/pages/home.blade.php (simple)
cat > resources/views/pages/home.blade.php << 'EOF'
<x-guest-layout>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    <h1 class="text-3xl font-bold">Welcome to MindEase</h1>
                    <p class="mt-4">Your AI-powered mental wellness companion.</p>
                    @auth
                        <a href="{{ route('dashboard') }}" class="mt-4 inline-block px-4 py-2 bg-blue-600 text-white rounded">Go to Dashboard</a>
                    @else
                        <a href="{{ route('login') }}" class="mt-4 inline-block px-4 py-2 bg-blue-600 text-white rounded">Login</a>
                        <a href="{{ route('register') }}" class="mt-4 ml-2 inline-block px-4 py-2 bg-gray-600 text-white rounded">Register</a>
                    @endauth
                </div>
            </div>
        </div>
    </div>
</x-guest-layout>
EOF

# resources/views/pages/sitemap.blade.php
cat > resources/views/pages/sitemap.blade.php << 'EOF'
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach($urls as $url)
        <url>
            <loc>{{ $url }}</loc>
            <lastmod>{{ now()->toDateString() }}</lastmod>
            <changefreq>monthly</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach
</urlset>
EOF

# resources/views/components/ad-slot.blade.php
cat > resources/views/components/ad-slot.blade.php << 'EOF'
@if(config('mindease.adsense.enabled') && config('mindease.adsense.publisher_id'))
    <div class="ad-container my-4">
        <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client={{ config('mindease.adsense.publisher_id') }}"
            crossorigin="anonymous"></script>
        <ins class="adsbygoogle"
            style="display:block"
            data-ad-client="{{ config('mindease.adsense.publisher_id') }}"
            data-ad-slot="{{ config('mindease.adsense.slots.footer') }}"
            data-ad-format="auto"
            data-full-width-responsive="true"></ins>
        <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
    </div>
@endif
EOF

# resources/views/components/structured-data.blade.php
cat > resources/views/components/structured-data.blade.php << 'EOF'
<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "WebSite",
    "name": "{{ config('app.name') }}",
    "url": "{{ url('/') }}",
    "description": "{{ setting('meta_description') }}",
    "potentialAction": {
        "@type": "SearchAction",
        "target": "{{ url('/search?q={search_term_string}') }}",
        "query-input": "required name=search_term_string"
    }
}
</script>
EOF

cat > resources/views/layouts/guest.blade.php << 'EOF'
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'MindEase') }}</title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />

    <!-- Scripts -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="font-sans text-gray-900 antialiased">
    <div class="min-h-screen flex flex-col sm:justify-center items-center pt-6 sm:pt-0 bg-gray-100 dark:bg-gray-900">
        <div>
            <a href="/">
                <x-application-logo class="w-20 h-20 fill-current text-gray-500" />
            </a>
        </div>

        <div class="w-full sm:max-w-md mt-6 px-6 py-4 bg-white dark:bg-gray-800 shadow-md overflow-hidden sm:rounded-lg">
            {{ $slot }}
        </div>
    </div>
</body>
</html>
EOF

mkdir -p resources/views/components
cat > resources/views/components/nav-link.blade.php << 'EOF'
@props(['active'])

@php
$classes = ($active ?? false)
            ? 'inline-flex items-center px-1 pt-1 border-b-2 border-indigo-400 dark:border-indigo-600 text-sm font-medium leading-5 text-gray-900 dark:text-gray-100 focus:outline-none focus:border-indigo-700 transition duration-150 ease-in-out'
            : 'inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-700 focus:outline-none focus:text-gray-700 dark:focus:text-gray-300 focus:border-gray-300 dark:focus:border-gray-700 transition duration-150 ease-in-out';
@endphp

<a {{ $attributes->merge(['class' => $classes]) }}>
    {{ $slot }}
</a>
EOF

cat > resources/views/components/dropdown.blade.php << 'EOF'
@props(['align' => 'right', 'width' => '48', 'contentClasses' => 'py-1 bg-white dark:bg-gray-700'])

@php
switch ($align) {
    case 'left':
        $alignmentClasses = 'origin-top-left left-0';
        break;
    case 'top':
        $alignmentClasses = 'origin-top';
        break;
    case 'right':
    default:
        $alignmentClasses = 'origin-top-right right-0';
        break;
}

switch ($width) {
    case '48':
        $width = 'w-48';
        break;
}
@endphp

<div class="relative" x-data="{ open: false }" @click.outside="open = false" @close.stop="open = false">
    <div @click="open = ! open">
        {{ $trigger }}
    </div>

    <div x-show="open"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 scale-95"
            x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-75"
            x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-95"
            class="absolute z-50 mt-2 {{ $width }} rounded-md shadow-lg {{ $alignmentClasses }}"
            style="display: none;"
            @click="open = false">
        <div class="rounded-md ring-1 ring-black ring-opacity-5 {{ $contentClasses }}">
            {{ $content }}
        </div>
    </div>
</div>
EOF

cat > resources/views/components/dropdown-link.blade.php << 'EOF'
<a {{ $attributes->merge(['class' => 'block w-full px-4 py-2 text-left text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-800 transition duration-150 ease-in-out']) }}>{{ $slot }}</a>
EOF

cat > resources/views/components/application-logo.blade.php << 'EOF'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" {{ $attributes }}>
    <path fill="#4F46E5" d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z"/>
    <circle fill="#4F46E5" cx="24" cy="24" r="8"/>
</svg>
EOF

echo "Project structure created successfully!"
echo "Next steps:"
echo "1. Run: composer install"
echo "2. Run: npm install && npm run build"
echo "3. Copy .env.example to .env and configure database"
echo "4. Run: php artisan key:generate"
echo "5. Run: php artisan migrate --seed"
echo "6. Run: php artisan serve"
