#!/bin/bash

# Fix routing and static files

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "========================================="
echo "Fixing Routing and Static Files"
echo "========================================="
echo

# Fix static files in Next.js public directory
echo -e "${BLUE}[INFO]${NC} Setting up static files..."
cd /opt/airwavepbx

# Create public directory if it doesn't exist
mkdir -p public

# Copy logo to multiple locations to ensure it's found
if [ -f "logos/airwave-logo.png" ]; then
    cp logos/airwave-logo.png public/logo.png
    echo -e "${GREEN}[OK]${NC} Copied airwave-logo.png"
elif [ -f "logos/logo.png" ]; then
    cp logos/logo.png public/logo.png
    echo -e "${GREEN}[OK]${NC} Copied logo.png"
else
    # Create a simple PNG logo using ImageMagick if available
    if command -v convert &> /dev/null; then
        convert -size 200x50 xc:white -font Arial -pointsize 24 -fill "#3b82f6" \
                -gravity center -annotate +0+0 "AirwavePBX" public/logo.png
        echo -e "${GREEN}[OK]${NC} Created logo.png"
    else
        # Use the SVG we created earlier
        cp public/logo.svg public/logo.png 2>/dev/null || true
    fi
fi

# Create favicon
if [ -f "fap/favicon.ico" ]; then
    cp fap/favicon.ico public/favicon.ico
elif [ -f "public/logo.png" ]; then
    # Try to create favicon from logo if ImageMagick is available
    if command -v convert &> /dev/null; then
        convert public/logo.png -resize 32x32 public/favicon.ico
        echo -e "${GREEN}[OK]${NC} Created favicon.ico"
    fi
fi

# Fix the login page redirect issue
echo -e "${BLUE}[INFO]${NC} Checking login page..."
if [ ! -f "src/app/login/page.tsx" ]; then
    echo -e "${YELLOW}[WARNING]${NC} Login page missing, creating..."
    mkdir -p src/app/login
    cat > src/app/login/page.tsx << 'EOF'
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { apiClient } from '@/lib/api';
import toast from 'react-hot-toast';

export default function LoginPage() {
  const router = useRouter();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      await apiClient.login(username, password);
      toast.success('Login successful');
      router.push('/dashboard');
    } catch (error: any) {
      toast.error(error.response?.data?.error || 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <div className="max-w-md w-full space-y-8">
        <div>
          <img
            className="mx-auto h-12 w-auto"
            src="/logo.png"
            alt="AirwavePBX"
            onError={(e) => {
              e.currentTarget.style.display = 'none';
              const textLogo = document.getElementById('text-logo');
              if (textLogo) textLogo.style.display = 'block';
            }}
          />
          <h2 id="text-logo" className="mt-6 text-center text-3xl font-extrabold text-gray-900" style={{ display: 'none' }}>
            AirwavePBX
          </h2>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            Sign in to your account
          </h2>
        </div>
        <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
          <div className="rounded-md shadow-sm -space-y-px">
            <div>
              <label htmlFor="username" className="sr-only">
                Username
              </label>
              <input
                id="username"
                name="username"
                type="text"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
                placeholder="Username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
            </div>
            <div>
              <label htmlFor="password" className="sr-only">
                Password
              </label>
              <input
                id="password"
                name="password"
                type="password"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
                placeholder="Password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
          </div>

          <div>
            <button
              type="submit"
              disabled={loading}
              className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50"
            >
              {loading ? 'Signing in...' : 'Sign in'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
EOF
fi

# Fix settings page if missing
if [ ! -f "src/app/dashboard/settings/page.tsx" ]; then
    echo -e "${BLUE}[INFO]${NC} Creating settings page..."
    mkdir -p src/app/dashboard/settings
    cat > src/app/dashboard/settings/page.tsx << 'EOF'
'use client';

import Layout from '@/components/Layout';

export default function SettingsPage() {
  return (
    <Layout>
      <div>
        <h1 className="text-2xl font-bold text-gray-900 mb-6">Settings</h1>
        <div className="bg-white shadow rounded-lg p-6">
          <p className="text-gray-600">Settings page coming soon...</p>
        </div>
      </div>
    </Layout>
  );
}
EOF
fi

# Update Nginx to serve static files correctly
echo -e "${BLUE}[INFO]${NC} Updating Nginx configuration..."
source /etc/airwavepbx/airwavepbx.env

cat > /etc/nginx/sites-available/airwavepbx << NGINX_EOF
server {
    listen 80;
    server_name $DOMAIN;

    # Static files from public directory
    location ~ ^/(logo\.png|favicon\.ico|.*\.(jpg|jpeg|gif|png|ico|svg|css|js))$ {
        root /opt/airwavepbx/public;
        try_files \$uri =404;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # API proxy
    location /api {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_read_timeout 90;
    }

    # WebSocket proxy
    location /ws {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # Next.js app
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
NGINX_EOF

# Reload Nginx
nginx -t && systemctl reload nginx

# Rebuild the application to include new pages
echo -e "${BLUE}[INFO]${NC} Rebuilding application..."
cd /opt/airwavepbx
npm run build

if [ $? -eq 0 ]; then
    echo -e "${GREEN}[SUCCESS]${NC} Build completed successfully"
    
    # Restart frontend only
    pm2 restart airwavepbx-frontend
    
    # Wait for it to start
    sleep 5
    
    # Test access
    echo
    echo -e "${BLUE}[INFO]${NC} Testing access..."
    
    # Test static file
    echo -n "Logo file: "
    if curl -s -o /dev/null -w "%{http_code}" http://localhost/logo.png | grep -q "200\|404"; then
        echo -e "${GREEN}OK${NC}"
    else
        echo -e "${RED}FAILED${NC}"
    fi
    
    # Test API
    echo -n "API endpoint: "
    if curl -s http://localhost:3001/api | grep -q "ok"; then
        echo -e "${GREEN}OK${NC}"
    else
        echo -e "${RED}FAILED${NC}"
    fi
    
    # Test login page
    echo -n "Login page: "
    if curl -s -o /dev/null -w "%{http_code}" http://localhost/login | grep -q "200"; then
        echo -e "${GREEN}OK${NC}"
    else
        echo -e "${RED}FAILED${NC}"
    fi
    
    echo
    echo "========================================="
    echo "Routing Fix Complete"
    echo "========================================="
    echo
    echo "You should now be able to:"
    echo "1. Access http://$DOMAIN"
    echo "2. See the login page"
    echo "3. Login with admin/admin"
    echo
    echo "If you still have issues:"
    echo "- Clear browser cache"
    echo "- Try incognito/private mode"
    echo "- Check: pm2 logs"
    
else
    echo -e "${RED}[ERROR]${NC} Build failed"
    echo "Check the error messages above"
fi