#!/bin/bash
# ============================================================
# DocuTrack - cPanel Auto Installer
# Run this from Terminal: bash install.sh
# ============================================================

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[OK]${NC} $1"; }
warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
error()   { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

echo ""
echo "=============================================="
echo "   DocuTrack Installer — hr.gsolutions.com.kw"
echo "=============================================="
echo ""

# ── Step 1: Check PHP ────────────────────────────────────────
info "Checking PHP version..."
PHP=$(which php81 || which php8.1 || which php)
if [ -z "$PHP" ]; then error "PHP not found. Please enable PHP 8.1+ in cPanel."; fi
PHP_VER=$($PHP -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
info "Using PHP $PHP_VER at $PHP"

# ── Step 2: Check Composer ──────────────────────────────────
info "Checking Composer..."
if ! command -v composer &>/dev/null; then
  info "Installing Composer locally..."
  $PHP -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
  $PHP composer-setup.php --quiet
  rm -f composer-setup.php
  COMPOSER="$PHP composer.phar"
  success "Composer installed"
else
  COMPOSER="composer"
  success "Composer found"
fi

# ── Step 3: Set up directories ──────────────────────────────
info "Setting up directories..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$SCRIPT_DIR/backend"
FRONTEND_DIR="$SCRIPT_DIR/public_html"

if [ ! -d "$BACKEND_DIR" ]; then error "backend/ folder not found. Did you extract the full zip?"; fi
cd "$BACKEND_DIR" || error "Cannot enter backend directory"

# ── Step 4: Install Laravel dependencies ────────────────────
info "Installing Laravel dependencies (this may take 2-3 minutes)..."
$COMPOSER install --no-dev --optimize-autoloader --no-interaction 2>&1 | grep -E "(Installing|Generating|Nothing)" | head -20
success "Dependencies installed"

# ── Step 5: Configure .env ──────────────────────────────────
if [ ! -f ".env" ]; then
  if [ -f ".env.example" ]; then
    cp .env.example .env
  else
    cat > .env << 'ENVEOF'
APP_NAME="DocuTrack"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://hr.gsolutions.com.kw

LOG_CHANNEL=stack
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=YOUR_DB_NAME
DB_USERNAME=YOUR_DB_USER
DB_PASSWORD=YOUR_DB_PASSWORD

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=public
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

SANCTUM_STATEFUL_DOMAINS=hr.gsolutions.com.kw
SESSION_DOMAIN=.gsolutions.com.kw
ENVEOF
  fi
  warn "Created .env file — YOU MUST edit it with your database credentials!"
  warn "Edit: nano $BACKEND_DIR/.env"
  echo ""
  read -p "Press ENTER after editing .env to continue, or Ctrl+C to stop now..."
fi

# ── Step 6: Generate app key ────────────────────────────────
info "Generating application key..."
$PHP artisan key:generate --force
success "App key generated"

# ── Step 7: Run migrations ──────────────────────────────────
info "Running database migrations..."
$PHP artisan migrate --force 2>&1
if [ $? -ne 0 ]; then
  error "Migration failed! Check your DB credentials in .env"
fi
success "Database tables created"

# ── Step 8: Storage link ────────────────────────────────────
info "Linking storage folder..."
$PHP artisan storage:link --force 2>&1
success "Storage linked"

# ── Step 9: Optimize ────────────────────────────────────────
info "Optimizing Laravel..."
$PHP artisan config:cache
$PHP artisan route:cache
$PHP artisan view:cache
success "Laravel optimized"

# ── Step 10: Create admin user ──────────────────────────────
echo ""
echo "=============================================="
echo "  Create Admin User"
echo "=============================================="
read -p "Admin name [Admin]: " ADMIN_NAME
ADMIN_NAME=${ADMIN_NAME:-Admin}
read -p "Admin email [admin@gsolutions.com.kw]: " ADMIN_EMAIL
ADMIN_EMAIL=${ADMIN_EMAIL:-admin@gsolutions.com.kw}
read -s -p "Admin password (min 8 chars): " ADMIN_PASS
echo ""

$PHP artisan tinker --execute="
\App\Models\User::create([
  'name' => '$ADMIN_NAME',
  'email' => '$ADMIN_EMAIL',
  'password' => bcrypt('$ADMIN_PASS'),
  'role' => 'admin',
  'is_active' => true,
]);
echo 'Admin created!';
" 2>/dev/null

success "Admin user created: $ADMIN_EMAIL"

# ── Step 11: Set permissions ─────────────────────────────────
info "Setting file permissions..."
chmod -R 775 storage bootstrap/cache
chmod -R 755 public
success "Permissions set"

# ── Step 12: Copy frontend to public_html ────────────────────
info "Deploying frontend to public_html..."
if [ -d "$SCRIPT_DIR/frontend" ]; then
  cp -r "$SCRIPT_DIR/frontend/." "$FRONTEND_DIR/"
  success "Frontend deployed to public_html"
else
  warn "frontend/ folder not found — upload it manually to public_html"
fi

# ── Step 13: Set up .htaccess for Laravel ────────────────────
info "Configuring .htaccess for API..."
cat > "$BACKEND_DIR/public/.htaccess" << 'HTEOF'
<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>
HTEOF
success ".htaccess configured"

# ── Step 14: CORS config ─────────────────────────────────────
info "Updating CORS configuration..."
cat > "$BACKEND_DIR/config/cors.php" << 'CORSEOF'
<?php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['https://hr.gsolutions.com.kw', 'http://hr.gsolutions.com.kw'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];
CORSEOF
success "CORS configured for hr.gsolutions.com.kw"

# ── Step 15: Cron setup hint ─────────────────────────────────
echo ""
echo "=============================================="
echo "  CRON JOB (Set in cPanel → Cron Jobs)"
echo "=============================================="
echo "  * * * * * $PHP $BACKEND_DIR/artisan schedule:run >> /dev/null 2>&1"
echo "=============================================="

# ── Done ──────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}=============================================="
echo "  ✅ Installation Complete!"
echo "=============================================="
echo -e "${NC}"
echo "  Frontend: https://hr.gsolutions.com.kw"
echo "  API:      https://hr.gsolutions.com.kw/api"
echo ""
echo "  Login with:"
echo "  Email:    $ADMIN_EMAIL"
echo "  Password: (what you entered above)"
echo ""
echo -e "${YELLOW}  IMPORTANT — Point your subdomain to:"
echo "  In cPanel → Subdomains:"
echo "    Subdomain: hr"
echo "    Domain:    gsolutions.com.kw"
echo "    Root:      /home/USERNAME/public_html/hr.gsolutions.com.kw"
echo -e "${NC}"
