#!/bin/bash

# Shared Hosting Deployment Script
# Usage: ./deploy.sh
# Run from the project root directory on the production server via SSH.

set -e

echo "========================================="
echo "  Deploying Alphabd Technology"
echo "  $(date)"
echo "========================================="

# Pull latest code from git
echo ""
echo "[1/10] Pulling latest code from git..."
git pull origin main

# Install PHP dependencies (no dev, optimized)
echo ""
echo "[2/10] Running composer install..."
if command -v composer &> /dev/null; then
    composer install --no-dev --optimize-autoloader --no-interaction
else
    echo "  composer not found, downloading composer.phar..."
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php composer-setup.php --quiet
    rm composer-setup.php
    php composer.phar install --no-dev --optimize-autoloader --no-interaction
fi

# Install and build frontend assets
echo ""
echo "[3/10] Running npm ci && npm run build..."
npm ci
npm run build

# Run database migrations
echo ""
echo "[4/10] Running database migrations..."
php artisan migrate --force

# Cache configuration
echo ""
echo "[5/10] Caching configuration..."
php artisan config:cache

# Cache routes
echo ""
echo "[6/10] Caching routes..."
php artisan route:cache

# Cache views
echo ""
echo "[7/10] Caching views..."
php artisan view:cache

# Create storage symlink
echo ""
echo "[8/10] Creating storage symlink..."
php artisan storage:link --force

# Set proper permissions
echo ""
echo "[9/10] Setting permissions..."
chmod -R 775 storage bootstrap/cache
chown -R $(whoami):$(whoami) storage bootstrap/cache

# Restart queue workers
echo ""
echo "[10/10] Restarting queue workers..."
php artisan queue:restart

echo ""
echo "========================================="
echo "  Deployment complete!"
echo "  $(date)"
echo "========================================="
