/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


package data;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.sql.*;
import java.lang.Float;



/**
 *
 * @author Administrator
 */
public class SubmitPayment extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException{
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String selectedCreditcardNumber = request.getParameter("creditcardNumber");
        String selectedExpirationDate = request.getParameter("expirationDate");
        String selectedLast3Digits = request.getParameter("last3Digits");
        String selectedDigitalSignature = request.getParameter("digitalSignature");
        String selectedCreditcardType = request.getParameter("creditcardType");
        String selectedShow_id = request.getParameter("Show_id");
        Float selectedShow_price = new Float(request.getParameter("Show_price")).floatValue();
        int selectedNumTickets = Integer.parseInt(request.getParameter("numTickets"));
        int selectedCapacity = Integer.parseInt(request.getParameter("Capacity"));
       

        if(selectedShow_price <= 0){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The show price can't be null")));
        }
        else if(selectedNumTickets <= 0){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The number of tickets can't be null")));
        }
        else if(selectedCapacity <= 0){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The capacity can't be null")));
        }
        else if(selectedCreditcardNumber == ""){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The credit card number can't be empty")));
        }
        else if(selectedExpirationDate == ""){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The expiration date can't be empty")));
        }
        else if(selectedLast3Digits == ""){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The last 3 digits are required")));
        }
        else if(selectedCreditcardType == ""){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The credit card type can't be empty")));
        }
        else if(selectedShow_id == ""){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The show id  can't be empty")));
        }
        else if(selectedDigitalSignature == ""){
           out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error: The digital signature can't be empty")));
        }
        else{
            Float TotalAmount = selectedShow_price * selectedNumTickets;
            String sqlStatement = "";
            String extraCondition = "";
            String result = "";

            try
            {
                ResourceBundle config = ResourceBundle.getBundle("config");
                // get a DB connection
                String dbURL = config.getString("dbURL");
                String username = config.getString("username");
                String password = config.getString("password");

                Connection connection = DriverManager.getConnection(dbURL, username, password);
                Statement statement = connection.createStatement();

                StringBuffer jsonSB = new StringBuffer();

                ResourceBundle dataSQLQueries = ResourceBundle.getBundle("data.SQLQueries");

                sqlStatement = dataSQLQueries.getString("Query.show.AvailableSeats");
                extraCondition = dataSQLQueries.getString("Condition.Show_id") + SQLUtil.addQuotes(selectedShow_id);
                ResultSet resultSet = statement.executeQuery(sqlStatement + extraCondition);


                if(resultSet.next())
                {
                    int availableSeats = Integer.parseInt(resultSet.getString(1));
                    if(selectedNumTickets > availableSeats){
                        out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error insufficient tickets for this show")));
                    }
                    else{
                        sqlStatement = dataSQLQueries.getString("Query.balance.owner");
                        extraCondition = dataSQLQueries.getString("Query.updateBalance.part2") + dataSQLQueries.getString("Condition.number") + SQLUtil.addQuotes(selectedCreditcardNumber) + dataSQLQueries.getString("Condition.expirationDate") + SQLUtil.addQuotes(selectedExpirationDate) + dataSQLQueries.getString("Condition.last3Digits") + SQLUtil.addQuotes(selectedLast3Digits) + dataSQLQueries.getString("Condition.digitalSignature") + SQLUtil.addQuotes(selectedDigitalSignature) +  dataSQLQueries.getString("Condition.type") + SQLUtil.addQuotes(selectedCreditcardType);



                        resultSet = statement.executeQuery(sqlStatement + extraCondition);

                        if(resultSet.next())
                        {
                            Float Balance = new Float(resultSet.getString(1)).floatValue();
                            String CCOwner = resultSet.getString(2);
                            String CCid = resultSet.getString(3);

                            if(Balance >= TotalAmount){// update cc record with balance = balance - TotalAmount
                               sqlStatement = dataSQLQueries.getString("Query.updateBalance.part1") + dataSQLQueries.getString("Update.DeductBalance") + TotalAmount + dataSQLQueries.getString("Query.updateBalance.part2")  ;
                               extraCondition = dataSQLQueries.getString("Condition.CreditCard_id") + CCid;

                               int i = statement.executeUpdate(sqlStatement + extraCondition);
                               if (i != 1){
                                   out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error updating credit card balance")));
                               }
                               else{
 
                                   String CurrentDate = DateUtil.currentDate_YYYYMMDD();
                                   String CurrentTime = TimeUtil.currentTime_HHMMSS();
                                   sqlStatement = dataSQLQueries.getString("Query.insertReservation.part1") + dataSQLQueries.getString("Insert.Values.start")+ SQLUtil.addSimpleQuotes(CurrentDate) + "," +  SQLUtil.addSimpleQuotes(CurrentTime) + "," + selectedNumTickets + "," + "'' ," + CCid + "," + selectedShow_id + dataSQLQueries.getString("Insert.Values.end");

                                   int j = statement.executeUpdate(sqlStatement);
                                   if (j != 1){
                                       out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error updating reservation table")));
                                   }
                                   else{
                                       jsonSB.append("\"status\" : \"success\", \n");
                                       jsonSB.append("\"totalAmount\" : \"" + TotalAmount + "\", \n");
                                       jsonSB.append("\"CCowner\" : \"" + CCOwner + "\" \n");
                                       result = XMLUtil.getFormat(jsonSB.toString());
                                       out.println(result);
                                   }
 
                               }
                            }

                            else{
                                out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error : insufficient fund")));
                            }

                        }


                        else{
                            out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error getting credit card information")));
                        }
                    }
                }
                else 
                {
                    out.println(XMLUtil.getFormat(XMLUtil.errorHandler("Error getting current Avalaible seats")));
                }
                resultSet.close();
                statement.close();
                connection.close();
                out.close();
            }
            catch(SQLException e)
            {
                out.println(XMLUtil.getFormat(XMLUtil.errorHandler(e.getMessage())));

            }






        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            //Logger.getLogger(GetFilmsList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException  {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            //Logger.getLogger(GetFilmsList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 }