#!/usr/bin/env bash
#
# Project setup script — run this after cloning or pulling latest changes.
# Usage: ./setup.sh
#
# No Node/npm step: frontend styling is Bootstrap loaded via CDN, no JS build.

set -e

PHP_BIN="${PHP_BIN:-php8.5}"
COMPOSER_BIN="${COMPOSER_BIN:-/usr/bin/composer}"

if ! command -v "$PHP_BIN" >/dev/null 2>&1; then
    echo "Error: '$PHP_BIN' not found. Set PHP_BIN=/path/to/php8.5 ./setup.sh" >&2
    exit 1
fi

if [ ! -f "$COMPOSER_BIN" ]; then
    echo "Error: composer not found at '$COMPOSER_BIN'. Set COMPOSER_BIN=/path/to/composer ./setup.sh" >&2
    exit 1
fi

echo "==> Installing PHP dependencies"
"$PHP_BIN" "$COMPOSER_BIN" install

echo "==> Setting up environment file"
if [ ! -f .env ]; then
    cp .env.example .env
    "$PHP_BIN" artisan key:generate
else
    echo ".env already exists, skipping"
fi

echo "==> Setting up SQLite database"
mkdir -p database
touch database/database.sqlite
"$PHP_BIN" artisan migrate

echo "==> Fixing storage & cache permissions"
chmod -R 777 storage bootstrap/cache
chmod 777 database
chmod 666 database/database.sqlite

echo "==> Clearing cached bootstrap files"
"$PHP_BIN" artisan optimize:clear

echo "==> Done. Update APP_URL in .env if needed, then visit the app in your browser."
