<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_login();

$user = User::current();

// Saldırı işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['attack'])) {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        flash_set('error', __('err_csrf'));
        redirect(APP_URL . '/fight.php');
    }

    $targetId = (int)($_POST['target_id'] ?? 0);
    $target = User::findById($targetId);

    if (!$target) {
        flash_set('error', __('err_item_not_found'));
    } elseif ($targetId === (int)$user['id']) {
        flash_set('error', __('err_self_attack'));
    } elseif ((int)$user['hp_now'] < GAME_HP_MIN) {
        flash_set('error', __('err_your_hp_low'));
    } elseif ((int)$target['hp_now'] < GAME_HP_MIN) {
        flash_set('error', __('err_target_low_hp'));
    } else {
        // Savaş motoru — basit ama dengeli
        $attStats = User::effectiveStats($user);
        $defStats = User::effectiveStats($target);

        // Saldırı gücü = pow + agi/2 + rastgele
        $attPower = $attStats['pow'] + intval($attStats['agi'] / 2) + random_int(0, 10);
        $defPower = $defStats['def'] + intval($defStats['agi'] / 2) + random_int(0, 10);

        $damageDealt = max(1, $attPower - intval($defPower / 2));
        $damageTaken = max(1, $defPower - intval($attPower / 2));

        // HP kapasitelerini güncelle
        $newAttHp = max(0, (int)$user['hp_now'] - $damageTaken);
        $newDefHp = max(0, (int)$target['hp_now'] - $damageDealt);

        $winnerId = null;
        $result = 'draw';
        $goldChange = 0;
        $expChange = 0;
        $msg = __('fight_draw');

        if ($damageDealt > $damageTaken) {
            $winnerId = (int)$user['id'];
            $result = 'win';
            // Hedeften altın çal (max %10)
            $goldChange = min(intval($target['gold'] * 0.1), 1000) * GAME_GOLD_RATE;
            $expChange = max(5, intval($target['level'] * 10)) * GAME_EXP_RATE;
            $msg = __('fight_won');
        } elseif ($damageTaken > $damageDealt) {
            $winnerId = (int)$target['id'];
            $result = 'loss';
            $goldChange = 0;
            $expChange = 1;
            $msg = __('fight_lost');
        }

        try {
            DB::beginTransaction();

            // Saldıran güncelle
            $userUpdates = [
                'hp_now' => $newAttHp,
                'stat_battle' => (int)$user['stat_battle'] + 1,
            ];
            if ($result === 'win') {
                $userUpdates['stat_win'] = (int)$user['stat_win'] + 1;
                $userUpdates['gold'] = (int)$user['gold'] + $goldChange;
                $userUpdates['exp'] = (int)$user['exp'] + $expChange;
            } elseif ($result === 'loss') {
                $userUpdates['stat_loss'] = (int)$user['stat_loss'] + 1;
                $userUpdates['exp'] = (int)$user['exp'] + $expChange;
            } else {
                $userUpdates['stat_draw'] = (int)$user['stat_draw'] + 1;
            }
            $sql = "UPDATE users SET " . implode(', ', array_map(fn($k) => "$k = :$k", array_keys($userUpdates))) . " WHERE id = :id";
            $userUpdates['id'] = (int)$user['id'];
            DB::execute($sql, array_combine(array_map(fn($k) => ":$k", array_keys($userUpdates)), array_values($userUpdates)));

            // Hedefi güncelle
            $targetUpdates = [
                'hp_now' => $newDefHp,
                'stat_battle' => (int)$target['stat_battle'] + 1,
            ];
            if ($result === 'win') {
                $targetUpdates['stat_loss'] = (int)$target['stat_loss'] + 1;
                $targetUpdates['gold'] = max(0, (int)$target['gold'] - $goldChange);
            } elseif ($result === 'loss') {
                $targetUpdates['stat_win'] = (int)$target['stat_win'] + 1;
            } else {
                $targetUpdates['stat_draw'] = (int)$target['stat_draw'] + 1;
            }
            $sqlT = "UPDATE users SET " . implode(', ', array_map(fn($k) => "$k = :$k", array_keys($targetUpdates))) . " WHERE id = :id";
            $targetUpdates['id'] = (int)$target['id'];
            DB::execute($sqlT, array_combine(array_map(fn($k) => ":$k", array_keys($targetUpdates)), array_values($targetUpdates)));

            // Savaş raporu kaydet
            $report = json_encode([
                'attacker' => $user['name'],
                'defender' => $target['name'],
                'damage_dealt' => $damageDealt,
                'damage_taken' => $damageTaken,
                'result' => $result,
                'gold' => $goldChange,
                'exp' => $expChange,
            ], JSON_UNESCAPED_UNICODE);

            DB::execute(
                "INSERT INTO user_fights (attacker_id, defender_id, winner_id, gold_changed, exp_changed, damage_dealt, damage_taken, report, created_at)
                 VALUES (:a, :d, :w, :g, :e, :dd, :dt, :r, :t)",
                [
                    ':a' => $user['id'], ':d' => $target['id'],
                    ':w' => $winnerId, ':g' => $goldChange, ':e' => $expChange,
                    ':dd' => $damageDealt, ':dt' => $damageTaken,
                    ':r' => $report, ':t' => time(),
                ]
            );

            DB::commit();

            $detail = $msg;
            if ($goldChange > 0) $detail .= ' ' . __('gold_gained', ['amount' => format_number($goldChange)]);
            if ($expChange > 0)  $detail .= ' ' . __('exp_gained', ['amount' => $expChange]);

            flash_set($result === 'win' ? 'success' : ($result === 'loss' ? 'error' : 'warning'), $detail);
        } catch (Throwable $e) {
            DB::rollback();
            flash_set('error', APP_DEBUG ? $e->getMessage() : __('error'));
        }
    }
    redirect(APP_URL . '/fight.php');
}

// Hedef listesi - benzer seviyedeki online oyuncular
$targets = DB::fetchAll(
    "SELECT id, name, race, exp, hp_now, gold, last_active
     FROM users
     WHERE id != :u AND is_banned = 0 AND hp_now >= :hp
     ORDER BY last_active DESC
     LIMIT 30",
    [':u' => $user['id'], ':hp' => GAME_HP_MIN]
);

$page_title = __('menu_fight');
require __DIR__ . '/includes/header.php';
?>

<h1>⚔ <?= e(__('menu_fight')) ?></h1>

<p class="text-muted mb-1">
    ❤ <?= __('health') ?>: <?= (int)$user['hp_now'] ?>/<?= (int)$user['hp_max'] ?>
    <?php if ((int)$user['hp_now'] < GAME_HP_MIN): ?>
        — <span class="text-danger"><?= __('err_your_hp_low') ?></span>
    <?php endif; ?>
</p>

<?php if (empty($targets)): ?>
    <p class="text-muted text-center" style="padding:2rem;">—</p>
<?php else: ?>
<table class="tbl">
    <thead>
        <tr>
            <th><?= __('character') ?></th>
            <th><?= __('level') ?></th>
            <th><?= __('health') ?></th>
            <th><?= __('attack') ?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($targets as $t):
            $tlvl = User::calculateLevel((int)$t['exp']);
        ?>
        <tr>
            <td>
                <img src="<?= APP_URL ?>/assets/img/race<?= (int)$t['race'] ?>small.gif"
                     alt="" style="vertical-align:middle; margin-right:0.4rem;">
                <strong><?= e($t['name']) ?></strong>
            </td>
            <td><?= $tlvl ?></td>
            <td><?= (int)$t['hp_now'] ?></td>
            <td>
                <form method="post" style="display:inline;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="target_id" value="<?= (int)$t['id'] ?>">
                    <button type="submit" name="attack" value="1" class="btn btn-sm">
                        ⚔ <?= __('attack') ?>
                    </button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<?php endif; ?>

<?php require __DIR__ . '/includes/footer.php'; ?>
