<?php
/**
 * 時間大富翁 - 房地產每日結算引擎
 */
class EstateEngine {
    
    public static function processDailySettlement($mysql_db) {
        $today = date('Y-m-d');

        try {
            // 自動為全域設定表擴充時間戳記欄位 (防呆)
            try { $mysql_db->exec("ALTER TABLE estate_global_settings ADD COLUMN last_update_date DATE"); } catch(Exception $e) {}

            $mysql_db->beginTransaction();

            // 鎖定全域設定表，確認今天是否已經結算過
            $stmt_check = $mysql_db->query("SELECT * FROM estate_global_settings WHERE id = 1 FOR UPDATE");
            $global_settings = $stmt_check->fetch();

            if (!$global_settings || (isset($global_settings['last_update_date']) && $global_settings['last_update_date'] === $today)) {
                $mysql_db->commit();
                return; // 今天已經結算過了，引擎自動休眠
            }

            $tax_rate = (float)$global_settings['daily_land_tax_rate'];

            // 撈取所有縣市與產業加權
            $cities_raw = $mysql_db->query("SELECT * FROM estate_cities")->fetchAll();
            $cities = [];
            foreach ($cities_raw as $c) $cities[$c['id']] = $c;

            // 撈取所有建物型錄資料
            $buildings_raw = $mysql_db->query("SELECT * FROM estate_buildings")->fetchAll();
            $buildings = [];
            foreach ($buildings_raw as $b) $buildings[$b['id']] = $b;

            // 撈取全體玩家
            $stmt_players = $mysql_db->query("SELECT id, display_name, sqlite_file FROM users WHERE role = 'player'");
            $players = $stmt_players->fetchAll();

            // 輪流鑽進每個玩家的專屬資料庫進行結算
            foreach ($players as $p) {
                // file_exists 還是需要 __DIR__，因為它不經過 config.php
                if (!empty($p['sqlite_file']) && file_exists(__DIR__ . '/' . $p['sqlite_file'])) {
                    
                    // ★ 核心修復：拿掉多餘的路徑，只傳入檔名讓 config.php 處理
                    $p_db = getPlayerSQLiteConnection($p['sqlite_file']);

                    $p_db->beginTransaction();
                    try {
                        $properties = $p_db->query("SELECT * FROM estate_properties")->fetchAll();

                        foreach ($properties as $prop) {
                            // 免稅保護期：今天剛買的土地，明天才開始算帳
                            if ($prop['purchase_date'] === $today) continue;

                            $pid = $prop['id'];
                            $cid = $prop['city_id'];
                            $city = $cities[$cid] ?? null;
                            if (!$city) continue;

                            if ($prop['building_id'] == 0) {
                                // -----------------------------
                                // 空地模式：徵收未開發空地稅
                                // -----------------------------
                                $tax = (int)round($prop['land_purchase_price'] * $tax_rate);
                                if ($tax > 0) {
                                    $p_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $tax");
                                    $p_db->prepare("UPDATE estate_properties SET last_revenue=0, last_cost=?, last_profit=? WHERE id=?")
                                         ->execute([$tax, -$tax, $pid]);

                                    $desc = "📜 房產稅務：【{$prop['city_name']} - 空地】繳納未開發空地稅 {$tax} 分鐘。";
                                    $p_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('estate_tax', ?, ?)")
                                         ->execute([-$tax, $desc]);
                                }
                            } else {
                                // -----------------------------
                                // 營運模式：計算亂數營收與產業加權
                                // -----------------------------
                                $bid = $prop['building_id'];
                                $b = $buildings[$bid] ?? null;

                                if ($b) {
                                    $ind = $b['industry_type'];
                                    $mult = 1.0;
                                    if ($ind === 'food') $mult = (float)$city['food_mult'];
                                    elseif ($ind === 'clothing') $mult = (float)$city['clothing_mult'];
                                    elseif ($ind === 'education') $mult = (float)$city['education_mult'];
                                    elseif ($ind === 'entertainment') $mult = (float)$city['entertainment_mult'];
                                    elseif ($ind === 'housing') $mult = (float)$city['housing_mult'];
                                    elseif ($ind === 'transport') $mult = (float)$city['transport_mult'];

                                    // 亂數抽取營收並乘上在地產業加權
                                    $min_rev = (int)$b['daily_revenue_min'];
                                    $max_rev = (int)$b['daily_revenue_max'];
                                    $raw_revenue = mt_rand($min_rev, $max_rev);
                                    $final_revenue = (int)round($raw_revenue * $mult);

                                    $fixed_cost = (int)$b['daily_fixed_cost'];
                                    $profit = $final_revenue - $fixed_cost;

                                    // 結算匯入錢包
                                    $p_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $profit");
                                    
                                    // 更新個人地產面板的財報數據
                                    $p_db->prepare("UPDATE estate_properties SET last_revenue=?, last_cost=?, last_profit=?, total_profit=total_profit+? WHERE id=?")
                                         ->execute([$final_revenue, $fixed_cost, $profit, $profit, $pid]);

                                    // 寫入存摺明細
                                    $sign = $profit >= 0 ? '+' : '';
                                    $prop_name = !empty($prop['custom_name']) ? $prop['custom_name'] : $b['building_name'];
                                    $desc = "🏢 房產營運：【{$prop['city_name']} - {$prop_name}】營收 {$final_revenue} 扣除成本 {$fixed_cost}，淨利 {$sign}{$profit} 分鐘。";
                                    $p_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('estate_profit', ?, ?)")
                                         ->execute([$profit, $desc]);
                                }
                            }
                        }
                        $p_db->commit();
                    } catch (Exception $e) {
                        $p_db->rollBack();
                        error_log("Estate Update Error for Player {$p['id']}: " . $e->getMessage());
                    }
                }
            }

            // 標記今天已經結算完畢
            $mysql_db->exec("UPDATE estate_global_settings SET last_update_date = '{$today}' WHERE id = 1");
            $mysql_db->commit();

        } catch (Exception $e) {
            if ($mysql_db->inTransaction()) $mysql_db->rollBack();
            error_log("Global Estate Engine Error: " . $e->getMessage());
        }
    }
}
?>