package com.example;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import com.example.App;

public class ShopController {

    private static final String CART_FILE = "cart.txt";

    @FXML
    private Button cartBtn;

    @FXML
    private Button loginBtn;

    @FXML
    private Button cardBtn1, cardBtn2, cardBtn3, cardBtn4;
    @FXML
    private Button cardBtn5, cardBtn6, cardBtn7, cardBtn8;

    @FXML
    private Label mainTitle;

    @FXML
    private TextArea cardText1, cardText2, cardText3, cardText4;
    @FXML
    private TextArea cardText5, cardText6, cardText7, cardText8;

    @FXML
    public void initialize() {
        System.out.println("ShopController initialized.");
    }

    @FXML
    private void handleCartButton() throws IOException {
        App.setRoot("cart");
    }

    @FXML
    private void handleLoginButton() throws IOException {
        App.setRoot("login");
    }

    // Book Addition Handlers
    @FXML
    private void handleAddToCartButton1() {
        addToCart("Lord of the Rings");
    }

    @FXML
    private void handleAddToCartButton2() {
        addToCart("The Wheel of Time");
    }

    @FXML
    private void handleAddToCartButton3() {
        addToCart("The Chronicles of Narnia");
    }

    @FXML
    private void handleAddToCartButton4() {
        addToCart("The Earthsea Cycle");
    }

    @FXML
    private void handleAddToCartButton5() {
        addToCart("The First Law Trilogy");
    }

    @FXML
    private void handleAddToCartButton6() {
        addToCart("The Kingkiller Chronicle");
    }

    @FXML
    private void handleAddToCartButton7() {
        addToCart("The Mistborn Series");
    }

    @FXML
    private void handleAddToCartButton8() {
        addToCart("The Stormlight Archive");
    }

    /**
     * Adds the specified item to the cart by appending it to the cart file.
     *
     * @param bookTitle the title of the book to add to the cart
     */
    private void addToCart(String bookTitle) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(CART_FILE, true))) {
            writer.write(bookTitle);
            writer.newLine();
            System.out.println("Added to cart: " + bookTitle);
        } catch (IOException e) {
            System.err.println("Failed to add item to cart: " + e.getMessage());
        }
    }
}
