<?php
$pageTitle = 'Manage Fines';
include_once 'includes/header.php';

// --- Auth Check ---
$allowed_roles = ['admin', 'super_admin', 'finance_manager'];
$current_role = $_SESSION['user_role'] ?? $_SESSION['admin_user_role'] ?? '';
if (!in_array($current_role, $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Instantiate models
$fineModel = new Fine();
$settingModel = new Setting();
$playerModel = new Player();
$clubModel = new Club();

// Get currency
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

// Pagination and Search
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$search = trim($_GET['q'] ?? '');
$limit = 20;
$offset = ($page - 1) * $limit;

$total_fines = $fineModel->getTotalFinesCount($search);
$total_pages = ceil($total_fines / $limit);
$all_fines = $fineModel->getAllFinesWithDetails($limit, $offset, $search);

$all_players = $playerModel->getAllPlayersWithClub();
$all_clubs = $clubModel->getAll();

include_once 'includes/sidebar.php';
?>

<h1>Manage Fines</h1>

<?php if (isset($_SESSION['flash_message'])): ?>
    <div class="message success"><?php echo $_SESSION['flash_message']; unset($_SESSION['flash_message']); ?></div>
<?php endif; ?>
<?php if (isset($_SESSION['flash_error'])): ?>
    <div class="message error"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></div>
<?php endif; ?>

<div class="dashboard-section">
    <h2>Issue New Fine</h2>
    <div class="form-container">
        <form action="manual_finance_process.php" method="POST">
            <input type="hidden" name="action" value="issue_fine">
            <div class="form-row" style="display: flex; gap: 20px;">
                <div class="form-group" style="flex: 1;">
                    <label for="entity_type">Fine For:</label>
                    <select name="entity_type" id="entity_type" onchange="toggleEntitySelect(this.value)" required>
                        <option value="">-- Select Type --</option>
                        <option value="player">Player</option>
                        <option value="club">Club</option>
                    </select>
                </div>
                <div class="form-group" style="flex: 2;" id="player-select-group">
                    <label for="player_id">Select Player</label>
                    <select name="entity_id_player" id="player_id" class="entity-select">
                        <option value="">-- Select Player --</option>
                        <?php foreach ($all_players as $player): ?>
                            <option value="<?php echo $player->id; ?>"><?php echo htmlspecialchars($player->last_name . ', ' . $player->first_name . ' (' . ($player->club_name ?? 'No Club') . ')'); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" style="flex: 2; display: none;" id="club-select-group">
                    <label for="club_id">Select Club</label>
                    <select name="entity_id_club" id="club_id" class="entity-select">
                        <option value="">-- Select Club --</option>
                        <?php foreach ($all_clubs as $club): ?>
                            <option value="<?php echo $club->id; ?>"><?php echo htmlspecialchars($club->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-group"><label for="reason">Reason</label><input type="text" name="reason" id="reason" required placeholder="e.g., Unsportsmanlike conduct"></div>
            <div class="form-group"><label for="amount">Amount (<?php echo $currency_symbol; ?>)</label><input type="number" name="amount" id="amount" step="0.01" min="0.01" required></div>
            <button type="submit" class="btn">Issue Fine</button>
        </form>
    </div>
</div>

<div class="dashboard-section">
    <div class="table-wrapper">
        <table class="styled-table">
            <thead>
                <tr>
                    <th>Entity</th>
                    <th>Type</th>
                    <th>Reason</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Date Issued</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_fines as $fine): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($fine->entity_name); ?></td>
                        <td><?php echo ucfirst($fine->entity_type); ?></td>
                        <td><?php echo htmlspecialchars($fine->reason); ?></td>
                        <td><?php echo $currency_symbol; ?><?php echo number_format($fine->amount, 2); ?></td>
                        <td>
                            <span class="status-badge status-<?php echo strtolower($fine->status); ?>">
                                <?php echo ucfirst($fine->status); ?>
                            </span>
                        </td>
                        <td><?php echo date('d M Y', strtotime($fine->issued_date)); ?></td>
                        <td>
                            <?php if ($fine->status === 'unpaid'): ?>
                                <form action="manual_finance_process.php" method="POST" onsubmit="return confirm('Mark this fine as paid?');">
                                    <input type="hidden" name="action" value="mark_fine_paid">
                                    <input type="hidden" name="fine_id" value="<?php echo $fine->id; ?>">
                                    <button type="submit" class="btn-sm btn-success">Mark Paid</button>
                                </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
        <div class="pagination-controls">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&q=<?php echo urlencode($search); ?>" class="btn-sm">Previous</a>
            <?php endif; ?>
            <span class="page-info">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&q=<?php echo urlencode($search); ?>" class="btn-sm">Next</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.status-badge { padding: 4px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
.status-paid { background-color: #d4edda; color: #155724; }
.status-unpaid { background-color: #f8d7da; color: #721c24; }
.pagination-controls { display: flex; justify-content: center; gap: 10px; margin-top: 20px; align-items: center; }
</style>

<script>
function toggleEntitySelect(type) {
    const playerGroup = document.getElementById('player-select-group');
    const clubGroup = document.getElementById('club-select-group');
    const playerSelect = document.getElementById('player_id');
    const clubSelect = document.getElementById('club_id');

    if (type === 'player') {
        playerGroup.style.display = 'block';
        clubGroup.style.display = 'none';
        playerSelect.name = 'entity_id';
        clubSelect.name = 'entity_id_disabled';
    } else if (type === 'club') {
        playerGroup.style.display = 'none';
        clubGroup.style.display = 'block';
        playerSelect.name = 'entity_id_disabled';
        clubSelect.name = 'entity_id';
    }
}
</script>

<?php include_once 'includes/footer.php'; ?>