package com.nisum.dao;

import com.nisum.model.Product;
import com.nisum.util.DBConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDAO
{
    public List<Product> findAllActive() throws SQLException {
        List<Product> list = new ArrayList<>();
        String sql = "SELECT * FROM Product WHERE Status='Active'";
        try (Connection c = DBConnection.get();
             PreparedStatement ps = c.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                Product p = new Product();
                p.setId(rs.getInt("ProductID"));
                p.setName(rs.getString("ProductName"));
                p.setStatus(rs.getString("Status"));
                p.setCategoryId(rs.getInt("categoryId"));
                p.setImageurl(rs.getString("imageurl"));
                list.add(p);
            }
        }
        return list;
    }

    public Product getProductDetailsById(int productId) throws SQLException {
        Product product = null;
        String sql = "SELECT p.ProductID, p.ProductName, p.Status, p.CategoryId, p.imageurl, " +
                "pc.Price AS MRP, pc.DiscountPrice AS SP, pc.Discount " +
                "FROM Product p " +
                "JOIN ProductCategory pc ON p.ProductID = pc.ProductID " +
                "WHERE p.ProductID = ?";

        try (Connection c = DBConnection.get();
             PreparedStatement ps = c.prepareStatement(sql)) {

            ps.setInt(1, productId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    product = new Product();
                    product.setId(rs.getInt("ProductID"));
                    product.setName(rs.getString("ProductName"));
                    product.setStatus(rs.getString("Status"));
                    product.setCategoryId(rs.getInt("CategoryId"));
                    product.setImageurl(rs.getString("imageurl"));
                    product.setMrp(rs.getDouble("MRP"));
                    product.setSellingPrice(rs.getDouble("SP"));
                    product.setDiscountPercent(rs.getInt("Discount"));
                }
            }
        }
        return product;
    }


}
