#!/bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
echo -e "${CYAN}${BOLD}✔ Heybank start setup...${NC}\n"
if [ ! -d "vendor" ]; then
    echo -e "${RED}✖ Vendor chưa có, vui lòng chạy 'composer install' trước!${NC}\n"
    exit 1
fi
if [ -z "$(grep '^DB_DATABASE=' .env | cut -d '=' -f2)" ] || \
   [ -z "$(grep '^DB_USERNAME=' .env | cut -d '=' -f2)" ] || \
   [ -z "$(grep '^DB_PASSWORD=' .env | cut -d '=' -f2)" ]; then
    echo -e "${RED}✖ Vui lòng cấu hình thông tin database trong file .env trước khi chạy setup!${NC}"
    echo -e "${YELLOW}  → Các dòng cần điền:${NC}"
    echo "    DB_DATABASE=ten_bang"
    echo "    DB_USERNAME=ten_user"
    echo "    DB_PASSWORD=mat_khau"
    echo
    exit 1
fi
php_version=$(php -r "echo PHP_VERSION;")
required_version="8.2.0"
if [ "$(printf '%s\n' "$required_version" "$php_version" | sort -V | head -n1)" != "$required_version" ]; then
    echo -e "${RED}✖ PHP phiên bản hiện tại: $php_version${NC}"
    echo -e "${RED}✖ Yêu cầu tối thiểu: PHP 8.2 trở lên!${NC}"
    echo -e "${YELLOW}  → Trên AAPanel: App Store → PHP → Install PHP 8.2 hoặc 8.3${NC}"
    exit 1
fi
echo -e "${GREEN}✔ PHP version $php_version hợp lệ (>= 8.2)${NC}\n"
if ! php -m | grep -q '^mbstring$'; then
    echo -e "${RED}✖ PHP extension 'mbstring' chưa được cài đặt!${NC}"
    echo -e "${YELLOW}  → Trên AAPanel: App Store → PHP → Setting → Install Extensions → mbstring${NC}"
    exit 1
fi
echo -e "${YELLOW}⚙ Kiểm tra storage & bootstrap/cache...${NC}"
mkdir -p storage/framework/{sessions,views,cache} bootstrap/cache
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true
echo -e "${GREEN}✔ Storage & bootstrap/cache OK${NC}\n"
commands=(
  "key:generate"
  "migrate --force"
  "config:cache"
  "route:cache"
  "view:cache"
  "optimize"
)
for cmd in "${commands[@]}"; do
    echo -e "${YELLOW}➡ php artisan $cmd${NC}"
    if php artisan $cmd; then
        echo -e "${GREEN}✔ $cmd thành công${NC}\n"
    else
        echo -e "${RED}✖ $cmd thất bại!${NC}\n"
        exit 1
    fi
done
echo -e "${CYAN}${BOLD}✔ Setup hoàn tất!${NC}\n"