package natch_package;

import java.io.BufferedReader;import java.net.HttpURLConnection;
import java.net.URL;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.servlet.http.HttpSession;

import org.primefaces.json.JSONObject;

import main_package.DataBaseConnection;

public class SubscriptionDAO {

	
	public ArrayList<SubscriptionOverview> fetchAllSubscriptions() {

	    ArrayList<SubscriptionOverview> list = new ArrayList<>();

	    String query =
	            "SELECT created_at, updated_at, " +
	            "subscription_id, subscription_session_id, cf_subscription_id, " +
	            "plan_max_amount, plan_recurring_amount, " +
	            "customer_name, customer_phone, payment_mode, " +
	            "subscription_status, " +
	            "user_id, loan_no " +
	            "FROM subscriptions_overview " +
	            "ORDER BY id DESC";

	    try (Connection con = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = con.prepareStatement(query);
	         ResultSet rs = ps.executeQuery()) {

	        while (rs.next()) {

	            SubscriptionOverview s = new SubscriptionOverview();

	            // Dates
	            s.setCreated_at(
	                    formatDate(rs.getString("created_at")));

	            s.setUpdated_at(
	                    formatDate(rs.getString("updated_at")));

	            // Subscription details
	            s.setSubscription_id(
	                    rs.getString("subscription_id"));

	            s.setSubscription_session_id(
	                    rs.getString("subscription_session_id"));

	            s.setCf_subscription_id(
	                    rs.getString("cf_subscription_id"));

	            // Plan details
	            s.setPlan_max_amount(
	                    rs.getDouble("plan_max_amount"));

	            s.setPlan_recurring_amount(
	                    rs.getDouble("plan_recurring_amount"));

	            // Customer details
	            s.setCustomer_name(
	                    rs.getString("customer_name"));

	            s.setCustomer_phone(
	                    rs.getString("customer_phone"));

	            // Payment / subscription status
	            s.setPayment_mode(
	                    rs.getString("payment_mode"));

	            s.setSubscription_status(
	                    rs.getString("subscription_status"));

	            // Application details
	            s.setAddedBy(
	                    rs.getString("user_id"));

	            s.setLoanNo(
	                    rs.getString("loan_no"));

	            list.add(s);
	        }

	    } catch (SQLException e) {
	        e.printStackTrace();
	    }

	    return list;
	}

    public String formatDate(String inputDate) {
     
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
        
        LocalDateTime dateTime = LocalDateTime.parse(inputDate, inputFormatter);
      
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss");
        
        
        return dateTime.format(outputFormatter);
    }
    
    
    public void fetchsubscriptionByID(String uniquesubscriptionID) {
    	SubscriptionPojo pojo=new SubscriptionPojo();
    	 pojo= fetchsubscription(uniquesubscriptionID);
    	if( pojo.isDataFetch()) {
    		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    		ss.setAttribute("SubScriptionData", pojo);
    		goToViewPage();
    	}else {
    		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(pojo.getMessage()));
    	}
    	
    	
    };
    
    public void goToViewPage() {
        try {
            FacesContext.getCurrentInstance()
                .getExternalContext()
                .redirect("viewSubscription.xhtml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String key_id,key_secret;
    
    

    public SubscriptionPojo fetchsubscription(String subscription_id) {
        SubscriptionPojo sb = new SubscriptionPojo();
        fetchApiDetailsDB();
        boolean isValid = validateFields(key_id, key_secret);

        if (!isValid) {
            sb.setDataFetch(false);
            sb.setMessage("Unable to retrieve API credentials from the database. Please contact support for assistance.");
            return sb;
        }

        HttpURLConnection connection = null;
        try {
            String apiUrl = "https://api.cashfree.com/pg/subscriptions/" + subscription_id;

            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();

            if (responseCode == 200) {
                String response = readStream(connection.getInputStream());
                System.out.println("Response: " + response);
                JSONObject json = new JSONObject(response);

                // --- Root Subscription Details ---
                sb.setCf_subscription_id(json.optString("cf_subscription_id"));
                sb.setSubscription_id(json.optString("subscription_id"));
                sb.setSubscription_status(json.optString("subscription_status"));
                sb.setSubscription_expiry_time(formatDateOnly(json.optString("subscription_expiry_time")));
                sb.setSubscription_first_charge_time(formatDateOnly(json.optString("subscription_first_charge_time")));
                sb.setSubscription_session_id(json.optString("subscription_session_id"));
                
                // Timestamps
                sb.setSubscription_created_at(formatDateOnly(json.optString("created_at")));
                sb.setSubscription_activated_at(formatDateOnly(json.optString("activated_at")));
                sb.setSubscription_updated_at(formatDateOnly(json.optString("updated_at")));

                // Schedule Dates
                String nextSchedule = formatDateOnly(json.optString("next_schedule_date"));
                sb.setNext_schedule_date(nextSchedule);
                sb.setScheduled_on(nextSchedule);

                // Subscription Meta / Authorization Link
                JSONObject meta = json.optJSONObject("subscription_meta");
                if (meta != null) {
                    String returnUrl = meta.optString("return_url");
                    sb.setAuthorization_link(returnUrl);
                }

                // --- Authorization Details ---
                JSONObject auth = json.optJSONObject("authorization_details");
                if (auth != null) {
                    sb.setAuthorization_reference(auth.optString("authorization_reference"));
                    sb.setUmrn(auth.optString("authorization_reference"));
                    sb.setAuthorization_status(auth.optString("authorization_status"));
                    
                    String authTime = auth.optString("authorization_time");
                    sb.setAuthorization_time(formatDateTime(authTime));
                    sb.setAuthorization_created_at(formatDateOnly(authTime));
                    sb.setAuthorization_updated_at(formatDateOnly(auth.optString("updated_at", authTime)));

                    String paymentId = auth.optString("payment_id");
                    sb.setAuth_reference_id(auth.optString("authorization_reference_id", paymentId));
                    sb.setPayment_group(auth.optString("payment_group"));

                    // Payment Method (Handles both eNACH / Bank & UPI)
                    JSONObject paymentMethod = auth.optJSONObject("payment_method");
                    if (paymentMethod != null) {
                        if (paymentMethod.has("enach")) {
                            JSONObject enach = paymentMethod.getJSONObject("enach");
                            sb.setChannel(enach.optString("channel"));
                            sb.setAuth_mode(enach.optString("auth_mode"));
                            sb.setAccount_type(enach.optString("account_type"));
                            sb.setAccount_number(enach.optString("account_number"));
                            sb.setAccount_ifsc(enach.optString("account_ifsc"));
                            sb.setAccount_holder_name(enach.optString("account_holder_name"));
                            sb.setAccount_bank_code(enach.optString("account_bank_code"));
                            sb.setBank_name(enach.optString("bank_name", "--"));
                        } else if (paymentMethod.has("upi")) {
                            JSONObject upi = paymentMethod.getJSONObject("upi");
                            sb.setChannel(upi.optString("channel"));
                            sb.setVpa(upi.optString("upi_id"));
                            sb.setAuth_flow("Upi Qr Mandate");
                        }
                    }
                }

                // --- Customer Details ---
                JSONObject customer = json.optJSONObject("customer_details");
                if (customer != null) {
                    sb.setCustomer_name(customer.optString("customer_name"));
                    sb.setCustomer_email(customer.optString("customer_email"));
                    sb.setCustomer_phone(customer.optString("customer_phone"));
                }

                // --- Plan Details ---
                JSONObject plan = json.optJSONObject("plan_details");
                if (plan != null) {
                    sb.setPlan_id(plan.optString("plan_id"));
                    sb.setPlan_name(plan.optString("plan_name"));
                    sb.setPlan_type(plan.optString("plan_type"));
                    sb.setPlan_max_cycles(plan.optInt("plan_max_cycles"));
                    sb.setPlan_recurring_amount(plan.optDouble("plan_recurring_amount"));
                    sb.setPlan_max_amount(plan.optDouble("plan_max_amount"));
                    sb.setPlan_interval_type(plan.optString("plan_interval_type"));
                    sb.setPlan_intervals(plan.optInt("plan_intervals"));
                    sb.setPlan_currency(plan.optString("plan_currency", "INR"));
                }

                sb.setDataFetch(true);

            } else {
                String errorResponse = readStream(connection.getErrorStream());
                JSONObject errorJson = new JSONObject(errorResponse);

                String message = errorJson.optString("message");
                sb.setDataFetch(false);
                sb.setMessage("Unable to fetch subscription information. Please contact support. Reason: " + message);
            }

        } catch (Exception e) {
            e.printStackTrace();
            sb.setDataFetch(false);
            sb.setMessage("Error processing request: " + e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return sb;
    }
    
    public SubscriptionPojo MANAGEPLAN(String action, String subscription_id, String plan_id, String next_scheduled_time) {
        fetchApiDetailsDB();
        boolean isValid = validateFields(key_id, key_secret);
        SubscriptionPojo sb = new SubscriptionPojo();


        if (!isValid) {
            sb.setDataFetch(false);
            sb.setMessage("Unable to retrieve API credentials from the database. Please contact support for assistance.");
            return sb;
        }

        HttpURLConnection connection = null;
        try {
            // Build URL with dynamic subscription_id
            String apiUrl = "https://api.cashfree.com/pg/subscriptions/" + subscription_id + "/manage";

            URL url = new URL(apiUrl);
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("x-api-version", "2026-01-01");
            connection.setRequestProperty("x-client-id", key_id);
            connection.setRequestProperty("x-client-secret", key_secret);
            connection.setDoOutput(true);

            // Build request body
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("subscription_id", subscription_id);
            jsonBody.put("action", action);

            // Add action_details dynamically based on action type
            if (action.equals("CHANGE_PLAN")) {
                if (plan_id != null && !plan_id.isEmpty()) {
                    JSONObject actionDetails = new JSONObject();
                    actionDetails.put("plan_id", plan_id);
                    jsonBody.put("action_details", actionDetails);
                } else {
                    sb.setDataFetch(false);
                    sb.setMessage("plan_id is required for CHANGE_PLAN action.");
                    return sb;
                }

            } else if (action.equals("ACTIVATE")) {
                if (next_scheduled_time != null && !next_scheduled_time.isEmpty()) {
                    JSONObject actionDetails = new JSONObject();
                    actionDetails.put("next_scheduled_time", next_scheduled_time);
                    jsonBody.put("action_details", actionDetails);
                } else {
                    sb.setDataFetch(false);
                    sb.setMessage("next_scheduled_time is required for ACTIVATE action.");
                    return sb;
                }

            }

            // Write body to connection
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // Read response
            int responseCode = connection.getResponseCode();
            InputStream is = (responseCode == 200)
                ? connection.getInputStream()
                : connection.getErrorStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line.trim());
            }

            // Parse response
            JSONObject jsonResponse = new JSONObject(response.toString());

            if (responseCode == 200) {
                sb.setDataFetch(true);
                sb.setMessage("Subscription " + action + " successful.");
                // Set any additional response fields as needed
                // e.g. sb.setSubscriptionStatus(jsonResponse.optString("subscription_status"));
            } else {
                sb.setDataFetch(false);
                sb.setMessage(jsonResponse.optString("message", "Something went wrong."));
            }

        } catch (Exception e) {
            e.printStackTrace();
            sb.setDataFetch(false);
            sb.setMessage("Exception occurred: " + e.getMessage());
        } finally {
            if (connection != null) connection.disconnect();
        }
		return sb;
    }

    // --- Helper Methods for Formatting Dates ---
    private String formatDateOnly(String isoDate) {
        if (isoDate == null || isoDate.trim().isEmpty() || "null".equalsIgnoreCase(isoDate)) {
            return "--";
        }
        try {
            ZonedDateTime zdt = ZonedDateTime.parse(isoDate);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH);
            return zdt.format(formatter);
        } catch (Exception e) {
            return isoDate; // Fallback to raw string if parsing fails
        }
    }

    private String formatDateTime(String isoDate) {
        if (isoDate == null || isoDate.trim().isEmpty() || "null".equalsIgnoreCase(isoDate)) {
            return "--";
        }
        try {
            ZonedDateTime zdt = ZonedDateTime.parse(isoDate);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a", Locale.ENGLISH);
            return zdt.format(formatter);
        } catch (Exception e) {
            return isoDate; // Fallback to raw string if parsing fails
        }
    }
    
    
    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 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();
    }

}

