#!/bin/bash
# ============================================================
# U Super Shop — Auto Deploy Script
# usupershop.com এ deploy করতে এই script চালান
# ============================================================

set -e
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'

DEPLOY_PATH="/var/www/usuper-shop"
PHP="php8.2"

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  U Super Shop — Deployment Script${NC}"
echo -e "${GREEN}========================================${NC}"

# 1. Upload files to server first, then run this script on the server
# OR use: rsync -avz --exclude=vendor --exclude=node_modules . user@server:/var/www/usuper-shop/

echo -e "\n${YELLOW}[1/8] Installing PHP dependencies...${NC}"
composer install --optimize-autoloader --no-dev

echo -e "\n${YELLOW}[2/8] Installing NPM dependencies & building assets...${NC}"
npm install
npm run build

echo -e "\n${YELLOW}[3/8] Setting up .env file...${NC}"
if [ ! -f .env ]; then
    cp .env.example .env
    $PHP artisan key:generate
    echo -e "${RED}  ⚠ .env file created. Update DB, SMS, and payment credentials!${NC}"
else
    echo -e "${GREEN}  ✓ .env already exists${NC}"
fi

echo -e "\n${YELLOW}[4/8] Setting up storage directories...${NC}"
mkdir -p storage/framework/{cache/data,sessions,views}
mkdir -p storage/logs
mkdir -p storage/app/public
mkdir -p bootstrap/cache
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true

echo -e "\n${YELLOW}[5/8] Creating storage symlink...${NC}"
$PHP artisan storage:link

echo -e "\n${YELLOW}[6/8] Running database migrations...${NC}"
$PHP artisan migrate --force

echo -e "\n${YELLOW}[7/8] Optimizing for production...${NC}"
$PHP artisan config:cache
$PHP artisan route:cache
$PHP artisan view:cache
$PHP artisan event:cache

echo -e "\n${YELLOW}[8/8] Setting file permissions...${NC}"
find . -type f -name "*.php" -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chown -R www-data:www-data . 2>/dev/null || true

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}  ✅ Deploy সম্পন্ন!${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "সাইট: https://www.usupershop.com"
echo -e "Admin: https://www.usupershop.com/admin"
