package natch_package;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.json.JSONObject;
import main_package.DataBaseConnection;

@ManagedBean(name = "natchPlanBean")
@ViewScoped
public class NatchPlanBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private NatchPlanDetail selectedPlan ;

    private NatchPlanDetail planDetail = new NatchPlanDetail();
    List<NatchPlanDetail> plansList=new ArrayList<>();

    public NatchPlanDetail getPlanDetail() {
        return planDetail;
    }

    public void setPlanDetail(NatchPlanDetail planDetail) {
        this.planDetail = planDetail;
    }

    
    public NatchPlanBean() {
    	  selectedPlan=  new NatchPlanDetail();
    	  plansList = getAllPlansFromDB();
    	  fetchApiDetailsDB();
	}
    
    
    
    public void savePlan() {
        
        
     	boolean isValid = validateFields(key_id, key_secret);

     	if (!isValid){
     		  FacesContext.getCurrentInstance().addMessage(null,
                      new FacesMessage(FacesMessage.SEVERITY_ERROR,
                             "Unable to retrieve API credentials from the database. Please contact support for assistance.",null));
     		  
     	}else {
     		boolean success = sendCreatePlanRequest();
            if (success) {
                FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                            "Plan Created Successfully.",null));
                planDetail = new NatchPlanDetail();
                plansList = getAllPlansFromDB();
            } else {
            	FacesContext.getCurrentInstance().addMessage(null,
            		    new FacesMessage(
            		        FacesMessage.SEVERITY_WARN,
            		        "Plan Created Successfully. "+
            		        "The plan was created, but we encountered an issue saving it to the database. Please contact support if this persists.",null
            		    )
            		);
            }
            
     	}
           
       
    }
    
    String key_id;
    String key_secret;

    private boolean sendCreatePlanRequest() {
        HttpURLConnection connection = null;
       
        try {
            String apiUrl = "https://api.cashfree.com/pg/plans";

            JSONObject jsonBody = new JSONObject();
            jsonBody.put("plan_id", planDetail.getPlanId());
            jsonBody.put("plan_name", planDetail.getPlanName());
            jsonBody.put("plan_type", planDetail.getPlanType());
            jsonBody.put("plan_currency", planDetail.getPlanCurrency());
            jsonBody.put("plan_recurring_amount", planDetail.getPlanRecurringAmount());
            jsonBody.put("plan_max_amount", planDetail.getPlanMaxAmount());
            jsonBody.put("plan_max_cycles", planDetail.getPlanMaxCycles());
            jsonBody.put("plan_intervals", planDetail.getPlanIntervals());
            jsonBody.put("plan_interval_type", planDetail.getPlanIntervalType());
            jsonBody.put("plan_note", planDetail.getPlanNote());

            URL url = new URL(apiUrl);
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("x-api-version", "2025-01-01");
            connection.setRequestProperty("x-client-id", key_id);
            connection.setRequestProperty("x-client-secret", key_secret);
            connection.setDoOutput(true);

            // Send JSON payload
            OutputStream os = connection.getOutputStream();
            os.write(jsonBody.toString().getBytes("UTF-8"));
            os.flush();
            os.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == 200) {
                String response = readStream(connection.getInputStream());
                System.out.println("Response Body: " + response);

                JSONObject json = new JSONObject(response);

                String planCurrency = json.getString("plan_currency");
                String planId = json.getString("plan_id");
                String planIntervalType = json.getString("plan_interval_type");
                int planIntervals = json.getInt("plan_intervals");
                int planMaxAmount = json.getInt("plan_max_amount");
                int planMaxCycles = json.getInt("plan_max_cycles");
                String planName = json.getString("plan_name");
                String planNote = json.getString("plan_note");
                int planRecurringAmount = json.getInt("plan_recurring_amount");
                String planStatus = json.getString("plan_status");
                String planType = json.getString("plan_type");

                // insert in DB
               int res=insertPlanIntoDB(planId, planName, planType, planCurrency, planRecurringAmount,
                        planMaxAmount, planMaxCycles, planIntervals, planIntervalType, planNote, planStatus);
               if (res == 1) {
            	    return true; // success
            	    
            	} else {
           	       return false; // failure
            	}
            } else {
                String errorResponse = readStream(connection.getErrorStream());
                JSONObject errorJson = new JSONObject(errorResponse);

                String message = errorJson.optString("message");
                String code = errorJson.optString("code");
                String type = errorJson.optString("type");
                String help = errorJson.optString("help", null);
                
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                "Plan Creation Failed. "+message,null));
                

                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false; 
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

 public void fetchApiDetailsDB() {
    	
    	try(Connection conn=DataBaseConnection.JAVAConnection()){
    		
    		String query = "SELECT * FROM api_keys WHERE provider_code = ? LIMIT 1";
    		try(PreparedStatement psmt=conn.prepareStatement(query)){
    		    psmt.setString(1, "cashfree-enatch");

    			ResultSet rs=psmt.executeQuery();
    			while(rs.next()) {
    				key_id=rs.getString("keyid");
    				key_secret=rs.getString("keySecret");
    				
    			}
    			
    			
	    		}catch (Exception e) {
	    			e.printStackTrace();
				}
	    	}catch (Exception e) {
				e.printStackTrace();
			}
	    }

		public  boolean validateFields( String key_id, String key_secret) {
			if (isNullOrEmpty(key_id)) return false;
			if (isNullOrEmpty(key_secret)) return false;
			
			return true;
		}
		
		private boolean isNullOrEmpty(String str) {
		  return (str == null || str.trim().isEmpty());
		}
		
    private int insertPlanIntoDB(String planId, String planName, String planType, String planCurrency,
            double planRecurringAmount, double planMaxAmount, int planMaxCycles,
            int planIntervals, String planIntervalType, String planNote, String planStatus) {

				Connection dbConn = null;
				PreparedStatement ps = null;
				int result = 0; // default: failure
				
				try {
				dbConn = DataBaseConnection.JAVAConnection();
				
				String sql = "INSERT INTO nach_plans (" +
				"plan_id, plan_name, plan_type, plan_currency, plan_recurring_amount, " +
				"plan_max_amount, plan_max_cycles, plan_intervals, plan_interval_type, plan_note, plan_status" +
				") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
				
				ps = dbConn.prepareStatement(sql);
				ps.setString(1, planId);
				ps.setString(2, planName);
				ps.setString(3, planType);
				ps.setString(4, planCurrency);
				ps.setDouble(5, planRecurringAmount);
				ps.setDouble(6, planMaxAmount);
				ps.setInt(7, planMaxCycles);
				ps.setInt(8, planIntervals);
				ps.setString(9, planIntervalType);
				ps.setString(10, planNote);
				ps.setString(11, planStatus);
				
				int rowsAffected = ps.executeUpdate();
				
				if (rowsAffected > 0) {
				result = 1; // success
				}
				
				} catch (SQLException e) {
				e.printStackTrace();
				} finally {
				try {
				if (ps != null) ps.close();
			if (dbConn != null) dbConn.close();
			} catch (SQLException e) {
			e.printStackTrace();
				}
			}
				
			return result;
	}

    
    public List<NatchPlanDetail> getAllPlansFromDB() {
        List<NatchPlanDetail> plans = new ArrayList<>();
        Connection dbConn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            dbConn = DataBaseConnection.JAVAConnection();

            String sql = "SELECT plan_id, plan_name, plan_type, plan_currency, " +
                         "plan_recurring_amount, plan_max_amount, plan_max_cycles, " +
                         "plan_intervals, plan_interval_type, plan_note, plan_status " +
                         "FROM nach_plans ORDER BY created_at DESC";

            ps = dbConn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                NatchPlanDetail plan = new NatchPlanDetail();
                plan.setPlanId(rs.getString("plan_id"));
                plan.setPlanName(rs.getString("plan_name"));
                plan.setPlanType(rs.getString("plan_type"));
                plan.setPlanCurrency(rs.getString("plan_currency"));
                plan.setPlanRecurringAmount(rs.getDouble("plan_recurring_amount"));
                plan.setPlanMaxAmount(rs.getDouble("plan_max_amount"));
                plan.setPlanMaxCycles(rs.getInt("plan_max_cycles"));
                plan.setPlanIntervals(rs.getInt("plan_intervals"));
                plan.setPlanIntervalType(rs.getString("plan_interval_type"));
                plan.setPlanNote(rs.getString("plan_note"));
                plan.setPlanStatus(rs.getString("plan_status"));
                plans.add(plan);
            }

            System.out.println("Loaded " + plans.size() + " plans from nach_plans table.");

        } catch (SQLException e) {
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Database Error",
                    "Unable to fetch plans from the database. Please contact support."));
        } finally {
            try {
                if (rs != null) rs.close();
                if (ps != null) ps.close();
                if (dbConn != null) dbConn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return plans;
    }
    
    public void fetchPlanByID(String uniquePlanID) {
    	fetchPlan(uniquePlanID);
    };
    
    public boolean fetchPlan(String planIdd) {
    	System.out.println("Fetchinf");
    	 HttpURLConnection connection = null;

         try {
             String apiUrl = "https://api.cashfree.com/pg/plans/"+planIdd;

            
             URL url = new URL(apiUrl);
             connection = (HttpURLConnection) url.openConnection();

             connection.setRequestMethod("GET");
             connection.setRequestProperty("Content-Type", "application/json");
             connection.setRequestProperty("x-api-version", "2025-01-01");
             connection.setRequestProperty("x-client-id", key_id);
             connection.setRequestProperty("x-client-secret", key_secret);
             
           
             int responseCode = connection.getResponseCode();
             
             System.out.println("Response Code"+responseCode);
             if (responseCode == 200) {
                 String response = readStream(connection.getInputStream());
                 System.out.println("Response Body: " + response);

                 JSONObject json = new JSONObject(response);

                 String planCurrency = json.getString("plan_currency");
                 String planId = json.getString("plan_id");
                 String planIntervalType = json.getString("plan_interval_type");
                 int planIntervals = json.getInt("plan_intervals");
                 Double planMaxAmount = json.getDouble("plan_max_amount");
                 int planMaxCycles = json.getInt("plan_max_cycles");
                 String planName = json.getString("plan_name");
                 String planNote = json.getString("plan_note");
                 Double planRecurringAmount = json.getDouble("plan_recurring_amount");
                 String planStatus = json.getString("plan_status");
                 String planType = json.getString("plan_type");
                 
                 
                 selectedPlan.setPlanCurrency(planCurrency);
                 selectedPlan.setPlanId(planId);
                 selectedPlan.setPlanIntervalType(planIntervalType);
                 selectedPlan.setPlanIntervals(planIntervals);
                 selectedPlan.setPlanMaxAmount(planMaxAmount);
                 selectedPlan.setPlanMaxCycles(planMaxCycles);
                 selectedPlan.setPlanName(planName);
                 selectedPlan.setPlanNote(planNote);
                 selectedPlan.setPlanRecurringAmount(planRecurringAmount);
                 selectedPlan.setPlanStatus(planStatus);
                 selectedPlan.setPlanType(planType);
                 
                 
                 
                 
                 
                 
                 
                 // insert in DB
               // int res=insertPlanIntoDB(planId, planName, planType, planCurrency, planRecurringAmount,
                //      planMaxAmount, planMaxCycles, planIntervals, planIntervalType, planNote, planStatus);

            //    if (res == 1) {
             	    return true; // success
            // 	} else {
            //	       return false; // failure
            // 	}
             } else {
                 String errorResponse = readStream(connection.getErrorStream());
                 JSONObject errorJson = new JSONObject(errorResponse);
                 
                 System.out.println(errorJson.toString());

                 String message = errorJson.optString("message");
                 String code = errorJson.optString("code");
                 String type = errorJson.optString("type");
                 String help = errorJson.optString("help", null);
                 
                 FacesContext.getCurrentInstance().addMessage(null,
                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                 "Plan Fetching Failed. "+message,null));
                 

                 return false;
             }

         } catch (Exception e) {
             e.printStackTrace();
             return false; 
         } finally {
             if (connection != null) {
                 connection.disconnect();
             }
         }
    }

    
    private String readStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

	public List<NatchPlanDetail> getPlansList() {
		return plansList;
	}

	public void setPlansList(List<NatchPlanDetail> plansList) {
		this.plansList = plansList;
	}

	public NatchPlanDetail getSelectedPlan() {
		return selectedPlan;
	}

	public void setSelectedPlan(NatchPlanDetail selectedPlan) {
		this.selectedPlan = selectedPlan;
	}
}
