//
//  CashierSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 17/04/2024.
//

import SwiftUI
import LeStorage

struct CashierSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    var tournaments: [Tournament]
    
    init(tournaments: [Tournament]) {
        self.tournaments = tournaments
    }

    init(tournament: Tournament) {
        self.tournaments = [tournament]
    }
    
    var body: some View {
        List {
            Section {
                RowButtonView("Tout le monde a réglé", role: .destructive) {
                    let players = tournaments.flatMap({ $0.selectedPlayers() })
                    players.forEach { player in
                        if player.hasPaid() == false {
                            player.paymentType = .gift
                        }
                    }
                    do {
                        try dataStore.playerRegistrations.addOrUpdate(contentOfs: players)
                    } catch {
                        Logger.error(error)
                    }
                }
            } footer: {
                Text("Passe tous les joueurs qui n'ont pas réglé en offert")
            }
            
            Section {
                RowButtonView("Personne n'a réglé", role: .destructive) {
                    let players = tournaments.flatMap({ $0.selectedPlayers() })
                    players.forEach { player in
                        player.paymentType = nil
                    }
                    do {
                        try dataStore.playerRegistrations.addOrUpdate(contentOfs: players)
                    } catch {
                        Logger.error(error)
                    }
                }
            } footer: {
                Text("Remet à zéro le type d'encaissement de tous les joueurs")
            }

        }
    }
}

//#Preview {
//    CashierSettingsView(tournaments: [])
//}
