#!/bin/sh
# ============================================================
#  修復：補上缺少的昨日檔案（DormRentIncome model 等）
#  前置：deploy_statement.sh 已解壓 extract_stmt
#  之後會繼續完成 statement 部署的 migration + 驗證
#  請以 root 執行（寶塔面板「終端機」內貼上）
# ============================================================
set -e

PROJ=/www/wwwroot/faithfulness
BASE=/home/wing/wkr_tmp

echo "=== [1/2] 補上缺少的昨日檔案 ==="
if [ -f $BASE/extract_stmt/app/Models/DormRentIncome.php ]; then
  cp -a $BASE/extract_stmt/app/Models/DormRentIncome.php $PROJ/app/Models/
  echo "DormRentIncome: 從 extract_stmt 補上 OK"
fi
chown -R www:www $PROJ/app
echo "完成"

echo "=== [2/2] migration + 清快取 + 驗證（statement 部署的後半段）==="
cd $PROJ
sudo -u www /usr/bin/php artisan migrate --force
sudo -u www /usr/bin/php artisan optimize:clear 2>&1 | tail -1

sudo -u www /usr/bin/php artisan migrate:status 2>/dev/null | tail -2
sudo -u www /usr/bin/php artisan tinker --execute="echo 'accounting_transactions table: '.(Illuminate\Support\Facades\Schema::hasTable('accounting_transactions')?'OK':'MISSING').PHP_EOL;" 2>/dev/null | tail -1
echo "-- statement routes: $(sudo -u www /usr/bin/php artisan route:list 2>/dev/null | grep -c accounting.statement) (9 = OK)"
echo "-- sidebar 收租管理: $(grep -c '收租管理' resources/views/layouts/admin.blade.php) (>=1 = OK)"
echo "-- sidebar 會計收支表: $(grep -c '會計收支表' resources/views/layouts/admin.blade.php) (>=1 = OK)"
echo "=== 全部完成，Ctrl+F5 重新整理頁面 ==="
