#!/bin/bash

# ========================================
# TastyIgniter Server Deployment Script
# FOR: restaurant.minra.top
# ========================================

echo "🍽️  TastyIgniter Deployment Script"
echo "===================================="
echo ""

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if we're in the right directory
if [ ! -f "artisan" ]; then
    echo -e "${RED}ERROR: artisan file not found!${NC}"
    echo "Please run this script from the TastyIgniter root directory."
    exit 1
fi

echo -e "${YELLOW}Step 1: Checking .env file...${NC}"
if [ ! -f ".env" ]; then
    echo -e "${RED}ERROR: .env file not found!${NC}"
    echo "Please copy .env.production.template to .env and configure it first:"
    echo "  cp .env.production.template .env"
    echo "  nano .env"
    exit 1
fi

# Check if APP_KEY is set
if grep -q "APP_KEY=$" .env || grep -q "APP_KEY=\"\"" .env; then
    echo -e "${YELLOW}Generating application key...${NC}"
    php artisan key:generate --force
    echo -e "${GREEN}✓ Application key generated${NC}"
else
    echo -e "${GREEN}✓ Application key already set${NC}"
fi

echo ""
echo -e "${YELLOW}Step 2: Setting file permissions...${NC}"
chmod -R 755 storage bootstrap/cache public
chmod -R 775 storage bootstrap/cache
echo -e "${GREEN}✓ Permissions set${NC}"

echo ""
echo -e "${YELLOW}Step 3: Creating storage link...${NC}"
php artisan storage:link 2>/dev/null || echo "  (Link already exists)"
echo -e "${GREEN}✓ Storage link created${NC}"

echo ""
echo -e "${YELLOW}Step 4: Clearing caches...${NC}"
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear
echo -e "${GREEN}✓ All caches cleared${NC}"

echo ""
echo -e "${YELLOW}Step 5: Testing database connection...${NC}"
php artisan tinker --execute="DB::connection()->getPdo(); echo 'Database connected!';" 2>&1 | grep -q "Database connected"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Database connection successful${NC}"
else
    echo -e "${RED}✗ Database connection failed!${NC}"
    echo "Please check your .env database settings:"
    echo "  - DB_HOST"
    echo "  - DB_DATABASE"
    echo "  - DB_USERNAME"
    echo "  - DB_PASSWORD"
    echo "  - DB_PREFIX (should be EMPTY!)"
    exit 1
fi

echo ""
echo -e "${YELLOW}Step 6: Checking database tables...${NC}"
TABLE_COUNT=$(php artisan tinker --execute="echo count(DB::select('SHOW TABLES'));" 2>/dev/null | tail -n 1)

if [ "$TABLE_COUNT" -lt 10 ]; then
    echo -e "${YELLOW}Only $TABLE_COUNT tables found. Running TastyIgniter installation...${NC}"
    echo ""
    echo "This will:"
    echo "  1. Drop existing tables (if any)"
    echo "  2. Create all TastyIgniter tables (~84 tables)"
    echo "  3. Set up extensions"
    echo ""
    read -p "Continue? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        php artisan igniter:down --force
        php artisan igniter:install --no-interaction
        
        # Verify installation
        NEW_TABLE_COUNT=$(php artisan tinker --execute="echo count(DB::select('SHOW TABLES'));" 2>/dev/null | tail -n 1)
        echo -e "${GREEN}✓ Installation complete! Created $NEW_TABLE_COUNT tables${NC}"
    else
        echo "Installation skipped."
    fi
else
    echo -e "${GREEN}✓ Database already initialized ($TABLE_COUNT tables found)${NC}"
fi

echo ""
echo -e "${YELLOW}Step 7: Creating admin user...${NC}"
if [ -f "create_admin.php" ]; then
    php create_admin.php
    echo -e "${GREEN}✓ Admin user created/verified${NC}"
else
    echo -e "${YELLOW}⚠ create_admin.php not found. Create admin manually:${NC}"
    echo "  php artisan tinker"
    echo "  DB::table('ti_admin_users')->insert([...]);"
fi

echo ""
echo -e "${YELLOW}Step 8: Optimizing for production...${NC}"
php artisan config:cache
php artisan route:cache
php artisan view:cache
echo -e "${GREEN}✓ Application optimized${NC}"

echo ""
echo "===================================="
echo -e "${GREEN}🎉 Deployment Complete!${NC}"
echo "===================================="
echo ""
echo "Next steps:"
echo "1. Visit: https://restaurant.minra.top/admin/login"
echo "2. Login with:"
echo "   Username: admin"
echo "   Password: admin123"
echo "3. Change your admin password immediately!"
echo "4. Remove create_admin.php: rm create_admin.php"
echo ""
echo -e "${YELLOW}Important security notes:${NC}"
echo "- Change the default admin password"
echo "- Verify APP_DEBUG=false in .env"
echo "- Set up regular database backups"
echo ""
