package jsonPackage;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import main_package.DataBaseConnection;
import main_package.DataBaseMethodsHemant;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ManagedBean(name = "myNidhiCollectionJson")
@ViewScoped

public class MyNidhiCollectionJson implements Serializable {

    private String json;

    public MyNidhiCollectionJson() 
    {   
    	
        JSONObject mainobj = new JSONObject();
        JSONArray arr = new JSONArray();
        JSONObject obj = new JSONObject();

        Connection conn = null;
        
        try
        {
            conn = DataBaseConnection.JAVAConnection();
            DataBaseMethodsHemant db = new DataBaseMethodsHemant();
            db.getTotalEmiAmountTargatedCollectionPending(obj);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            
            obj.put("status", "error");
            obj.put("message", e.getMessage());
        } 
        finally 
        {
            try 
            {
                if (conn != null) conn.close();
            } 
            catch (SQLException e) 
            {
                e.printStackTrace();
            }
        }

        arr.add(obj);
        mainobj.put("today", arr);

        json = mainobj.toJSONString();
    }
    
    
    
    // ✅ JSON render method (API response)
    public void renderJson() throws IOException {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        externalContext.setResponseContentType("application/json");
        externalContext.setResponseCharacterEncoding("UTF-8");

        externalContext.getResponseOutputWriter().write(json);

        facesContext.responseComplete();
    }

    // Getter
    public String getJson() {
        return json;
    }

    // Setter
    public void setJson(String json) {
        this.json = json;
    }
}