#!/bin/bash
set -euo pipefail

# KHWWC Production Deployment Script
# Usage: bash deploy.sh [--skip-migrations] [--skip-build]
#
# This script is designed for cPanel/LiteSpeed shared hosting deployment.
# It assumes the package has been extracted to the public_html directory.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PUBLIC_DIR="${PUBLIC_DIR:-/home/kirinyag/public_html/app1.kirinyagahealthcareworkerswelfare.co.ke/khwwc/public}"
APP_DIR="$(dirname "$PUBLIC_DIR")"

echo "=========================================="
echo "KHWWC Production Deployment"
echo "=========================================="
echo "Public directory: $PUBLIC_DIR"
echo "App directory:    $APP_DIR"
echo ""

# Verify PHP version (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 "Checking PHP CLI..."
echo "Detected PHP CLI: $PHP_CLI_VERSION"
echo "Required PHP:     8.4"

if [[ "$PHP_CLI_MAJOR" -ne 8 ]] || [[ "$PHP_CLI_MINOR" -lt 4 ]]; then
    echo "PHP VERSION CHECK: FAIL"
    echo ""
    echo "Detected: $PHP_CLI_VERSION"
    echo "Required: 8.4"
    echo ""
    echo "Deployment aborted safely."
    exit 1
fi

echo "PHP CLI CHECK: PASS"
echo ""

# Try to verify web PHP version via a temporary diagnostic script
WEB_PHP_VERSION="unknown"
if command -v curl &> /dev/null; then
    TMP_PHP_INFO="/tmp/khwwc_php_info_$(date +%s).txt"
    cat > "$TMP_PHP_INFO" << 'PHPINFO'
<?php
header('Content-Type: text/plain');
echo 'PHP_VERSION=' . PHP_VERSION . PHP_EOL;
echo 'PHP_SAPI=' . PHP_SAPI . PHP_EOL;
echo 'PHP_INI=/etc/php/8.4/litespeed/php.ini' . PHP_EOL;
PHPINFO
    WEB_PHP_VERSION=$(curl -s -m 5 "http://127.0.0.1/phpinfo.php" 2>/dev/null | grep "^PHP_VERSION=" | cut -d= -f2 | tr -d '\r\n' || echo "unknown")
    rm -f "$TMP_PHP_INFO" 2>/dev/null || true
fi

echo "Web PHP version: $WEB_PHP_VERSION"
if [[ "$WEB_PHP_VERSION" != "unknown" ]]; then
    WEB_MAJOR=$(echo "$WEB_PHP_VERSION" | cut -d. -f1)
    WEB_MINOR=$(echo "$WEB_PHP_VERSION" | cut -d. -f2)
    if [[ "$WEB_MAJOR" -eq 8 ]] && [[ "$WEB_MINOR" -ge 4 ]]; then
        echo "Web PHP CHECK: PASS"
    else
        echo "WARNING: Web PHP version ($WEB_PHP_VERSION) may not be 8.4"
        echo "Ensure cPanel/LiteSpeed is configured to use PHP 8.4 for this domain."
    fi
else
    echo "WARNING: Could not detect web PHP version automatically."
    echo "Please verify in cPanel that PHP 8.4 is active for this domain."
fi
echo ""

# Verify Composer is available
if ! command -v composer &> /dev/null; then
    echo "WARNING: Composer not found. If vendor/ is included in the package, this is OK."
    echo "If vendor/ is NOT included, please install Composer or run composer install manually."
fi

# Verify we are in the right directory
if [ ! -f "$APP_DIR/artisan" ]; then
    echo "ERROR: artisan not found at $APP_DIR/artisan"
    echo "Please ensure the package was extracted to the correct location."
    exit 1
fi

cd "$APP_DIR"

# Check for .env file
if [ ! -f .env ]; then
    echo "WARNING: .env file not found."
    echo "Please create .env from .env.production.example and configure it before proceeding."
    echo ""
    echo "Required variables:"
    echo "  - APP_KEY (run: php artisan key:generate)"
    echo "  - DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD"
    echo "  - JWT_SECRET"
    echo "  - COOP_CONSUMER_KEY, COOP_CONSUMER_SECRET"
    echo "  - COOP_ACCOUNT_NUMBER"
    echo ""
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Verify storage directories exist and are writable
echo "Verifying storage directories..."
for dir in storage/logs storage/framework storage/app; do
    if [ ! -d "$dir" ]; then
        mkdir -p "$dir"
    fi
done

# Create storage link if it doesn't exist
if [ ! -L public/storage ]; then
    echo "Creating storage symlink..."
    php artisan storage:link || true
fi

# Clear caches
echo "Clearing caches..."
php artisan config:clear || true
php artisan route:clear || true
php artisan view:clear || true
php artisan cache:clear || true

# Run migrations (unless skipped)
if [[ "${1:-}" != "--skip-migrations" ]]; then
    echo "Running migrations..."
    php artisan migrate --force --no-interaction
else
    echo "Skipping migrations (--skip-migrations)"
fi

# Optimize for production
echo "Optimizing application..."
php artisan config:cache || true
php artisan route:cache || true
php artisan view:cache || true

# Verify health endpoint
echo "Verifying health endpoint..."
HEALTH_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1/api/health 2>/dev/null || echo "000")
if [ "$HEALTH_RESPONSE" = "200" ]; then
    echo "Health check: PASSED (HTTP $HEALTH_RESPONSE)"
else
    echo "WARNING: Health check returned HTTP $HEALTH_RESPONSE"
    echo "Please verify the application is working correctly."
fi

echo ""
echo "=========================================="
echo "Deployment completed successfully!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Verify the application at https://app1.kirinyagahealthcareworkerswelfare.co.ke"
echo "2. Log in as Super Admin and test Bank Diagnostics"
echo "3. Review storage/logs/ for any errors"
echo ""
