#!/bin/bash
set -euo pipefail

echo "=========================================="
echo "KHWWC cPanel/LiteSpeed Deployment Script"
echo "=========================================="
echo ""

APP_DIR="/home/kirinyag/public_html/app1.kirinyagahealthcareworkerswelfare.co.ke/khwwc"
PUBLIC_DIR="$APP_DIR/public"

cd "$APP_DIR"

echo "[1/9] Checking PHP CLI..."
PHP_CLI_VERSION=$(php -r "echo PHP_VERSION;" 2>/dev/null || echo "unknown")
PHP_CLI_MAJOR=$(echo "$PHP_CLI_VERSION" | cut -d. -f1)
PHP_CLI_MINOR=$(echo "$PHP_CLI_VERSION" | cut -d. -f2)
echo "Detected PHP CLI: $PHP_CLI_VERSION"

if [[ "$PHP_CLI_MAJOR" -ne 8 ]] || [[ "$PHP_CLI_MINOR" -lt 4 ]]; then
    echo "ERROR: PHP 8.4+ required. Detected: $PHP_CLI_VERSION"
    exit 1
fi
echo "PHP CLI: PASS"
echo ""

echo "[2/9] Checking for composer..."
if command -v composer &> /dev/null; then
    COMPOSER_CMD="composer"
elif [ -f "/usr/local/bin/composer" ]; then
    COMPOSER_CMD="/usr/local/bin/composer"
elif [ -f "$HOME/composer.phar" ]; then
    COMPOSER_CMD="php $HOME/composer.phar"
else
    echo "WARNING: Composer not found."
    COMPOSER_CMD=""
fi
echo "Composer: ${COMPOSER_CMD:-not available}"
echo ""

echo "[3/9] Installing composer dependencies..."
if [ -n "$COMPOSER_CMD" ]; then
    if [ ! -d "vendor" ]; then
        echo "vendor/ not found. Running composer install..."
        $COMPOSER_CMD install --no-dev --no-interaction --prefer-dist --optimize-autoloader || {
            echo "ERROR: composer install failed"
            exit 1
        }
    else
        echo "vendor/ already exists. Skipping composer install."
    fi
else
    echo "SKIP: Composer not available."
    echo "MANUAL ACTION REQUIRED:"
    echo "  1. Install Composer, OR"
    echo "  2. Upload a pre-built vendor/ directory"
fi
echo ""

echo "[4/9] Setting up .env..."
if [ ! -f ".env" ]; then
    if [ -f ".env.production.example" ]; then
        cp .env.production.example .env
        echo "Created .env from .env.production.example"
    elif [ -f ".env.example" ]; then
        cp .env.example .env
        echo "Created .env from .env.example"
    else
        echo "WARNING: No .env template found. Creating minimal .env..."
        cat > .env << 'ENVEOF'
APP_NAME="KHWWC Welfare System"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://app1.kirinyagahealthcareworkerswelfare.co.ke

LOG_CHANNEL=stack
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=kirinyag_health
DB_USERNAME=kirinyag_Deno
DB_PASSWORD=Neibas2022

SESSION_DRIVER=database
CACHE_STORE=database
QUEUE_CONNECTION=database

JWT_SECRET=
COOP_ENVIRONMENT=production
COOP_ENABLE_REAL_CALLS=true
ENVEOF
    fi
else
    echo ".env already exists. Skipping."
fi
echo ""

echo "[5/9] Generating APP_KEY..."
php artisan key:generate --force || echo "WARNING: key:generate failed"
echo ""

echo "[6/9] Setting permissions..."
chmod -R 775 storage bootstrap/cache || true
echo "Permissions set."
echo ""

echo "[7/9] Creating storage symlink..."
php artisan storage:link || true
echo ""

echo "[8/9] Running migrations..."
php artisan migrate --force --no-interaction || echo "WARNING: migrations failed"
echo ""

echo "[9/9] Optimizing and clearing caches..."
php artisan config:clear || true
php artisan route:clear || true
php artisan view:clear || true
php artisan cache:clear || true
php artisan config:cache || true
php artisan route:cache || true
php artisan view:cache || true
echo ""

echo "=========================================="
echo "Checking for .htaccess in public/..."
if [ -f "public/.htaccess" ]; then
    echo "public/.htaccess: EXISTS"
else
    echo "WARNING: public/.htaccess missing!"
    echo "Creating basic Laravel .htaccess..."
    cat > public/.htaccess << 'HTEOF'
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
HTEOF
fi
echo ""

echo "=========================================="
echo "Testing application..."
HEALTH=$(curl -s -o /dev/null -w "%{http_code}" https://app1.kirinyagahealthcareworkerswelfare.co.ke/api/health 2>/dev/null || echo "000")
echo "Health endpoint HTTP status: $HEALTH"

if [ "$HEALTH" = "200" ]; then
    echo "SUCCESS: Application is responding!"
else
    echo "WARNING: Health check returned $HEALTH"
    echo ""
    echo "Troubleshooting 500 errors:"
    echo "1. Check error logs: tail -f ~/logs/error_log"
    echo "2. Verify PHP error log in cPanel"
    echo "3. Ensure storage/ is writable: chmod -R 775 storage/"
    echo "4. Check .env has valid DB credentials"
    echo "5. Verify PHP 8.4 is active in cPanel"
fi
echo ""

echo "=========================================="
echo "Deployment script completed."
echo "=========================================="
