package DataAccess.Implementations;

import DataAccess.ConnectionFactory;
import DataAccess.Interfaces.PurchaseDaoInterface;
import Elements.Person;
import Elements.Purchase;

import java.math.BigDecimal;
import java.sql.*;

public class PurchaseDao extends BaseDao<Purchase> implements PurchaseDaoInterface{

    @Override
    public Purchase extractFromResultSet(ResultSet rs) throws SQLException{
        PersonDao personDao = new PersonDao();
        Purchase purchase = new Purchase();
        purchase.setId(rs.getInt("id"));
        purchase.setClient(personDao.findById(rs.getInt("client")));
        purchase.setTotal(rs.getBigDecimal("total"));
        return purchase;
    }

    @Override
    public int insertPurchase(Purchase purchase) throws SQLException {
        Connection connection = ConnectionFactory.getConnection();
        PreparedStatement statement = null;

        String query = "INSERT INTO purchase (client, total) VALUES (?,?)";
        statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        statement.setInt(1, purchase.getClient().getId());
        statement.setBigDecimal(2, purchase.getTotal());


        int rowsAffected = statement.executeUpdate();
        if(rowsAffected == 0){
            throw new SQLException("No rows affected");
        }

        try(ResultSet generatedKeys = statement.getGeneratedKeys()){
            if (generatedKeys.next()){
                return generatedKeys.getInt("id");
            } else {
                throw new SQLException("No id obtained");
            }
        }
    }

    @Override
    public int updatePurchase(Purchase purchase) {
        return 0;
    }

    public static void main(String[] args) {
        PurchaseDao purchaseDao = new PurchaseDao();
        PersonDao personDao = new PersonDao();

        Purchase purchase = new Purchase();
        Person client = personDao.findById(1);
        purchase.setClient(client);
        purchase.setTotal(BigDecimal.valueOf(29.96));
        try {
            int id = purchaseDao.insertPurchase(purchase);
            purchase.setId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

@@ -936,16 +936,28 @@
 t, total
+, date, time
 ) VALUES
@@ -961,16 +961,20 @@
 UES (?,?
+,?,?
 )%22;%0A    
@@ -1174,16 +1174,115 @@
 tal());%0A
+        statement.setDate(3, purchase.getDate());%0A        statement.setTime(4, purchase.getTime());
 %0A%0A      
@@ -2134,24 +2134,27 @@
 %0A           
+ //
  int id = pu
@@ -2196,24 +2196,27 @@
 %0A           
+ //
  purchase.se
@@ -2224,16 +2224,99 @@
 Id(id);%0A
+            purchase.save();%0A            System.out.println(%22Purchase populated%22);%0A
         

fix purchase dao to insert dates