import { successResponse, errorResponse } from '../utils/response.js';
import { getProjectConnection } from '../utils/dbManager.js';
import Treelogy from '../models/treelogy.js';
import Login from '../models/login.js';
import Mapping from '../models/mapping.js';
import UserMaster from '../models/userMaster.js';
import sequelize from '../config/config.js';
import { Op } from 'sequelize';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';

/**
 * Mobile API Controller for Android Apps
 * Handles all mobile app API endpoints for tree survey data collection
 * 
 * IMPORTANT: PostgreSQL uses $1, $2, $3 for parameters, not ? like MySQL
 * Sequelize query() returns [results, metadata] array
 */

// Helper function to get project database connection
const getProjectDbConnection = async (treelogy_id) => {
  const project = await Treelogy.findByPk(treelogy_id);
  if (!project) {
    throw new Error('Project not found');
  }
  return await getProjectConnection(project.dbname);
};

// Authentication APIs
const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    
    if (!email || !password) {
      return res.json({
        tag: 'login',
        success: 0,
        error: 1,
        error_msg: 'Email and password are required'
      });
    }

    // Mobile login: Use member_id (now unique across entire system)
    // member_id is now globally unique, so no duplicate login issues
    const user = await Login.findOne({
      where: {
        member_id: email, // Use member_id (unique)
        status: 'Y'
      },
      include: [
        { 
          model: Mapping, 
          as: 'Mappings',
          required: false 
        },
        {
          model: UserMaster,
          as: 'UserMaster',
          required: false
        }
      ]
    });

    if (!user) {
      return res.json({
        tag: 'login',
        success: 2,
        error: 1,
        error_msg: 'no such user!'
      });
    }
    
    // Check password
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.json({
        tag: 'login',
        success: 3,
        error: 1,
        error_msg: 'incorrect password!'
      });
    }

    // Determine project: check mapping first, then user's direct treelogy_id
    let projectId = null;
    
    // First, check if user has a mapping (for surveyors/QC users)
    if (user.Mappings && user.Mappings.length > 0) {
      projectId = user.Mappings[0].treelogy_id; // Get first mapped project
    } else if (user.treelogy_id) {
      // Fallback to user's direct treelogy_id
      projectId = user.treelogy_id;
    }

    if (!projectId) {
      return res.json({
        tag: 'login',
        success: 0,
        error: 1,
        error_msg: 'No project assigned to this user. Please contact administrator.'
      });
    }

    // Get project details
    const project = await Treelogy.findByPk(projectId);
    if (!project) {
      return res.json({
        tag: 'login',
        success: 0,
        error: 1,
        error_msg: 'Project not found'
      });
    }

    const projectConnection = await getProjectConnection(project.dbname);
    
    // Get today's tree details count
    const [todayCountResult] = await projectConnection.query(
      `SELECT COUNT(*) as count FROM treedetailsentered 
       WHERE user_id = $1 AND DATE(entered_date) = CURRENT_DATE`,
      {
        bind: [user.login_id],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    // Generate JWT token with the determined project ID
    const token = jwt.sign(
      { 
        login_id: user.login_id,
        member_id: user.member_id,
        treelogy_id: projectId, // Use the determined project ID
        client_id: user.client_id,
        role_name: user.UserMaster?.role_name
      },
      process.env.JWT_SECRET || 'default_secret',
      { expiresIn: '24h' }
    );

    const response = {
      tag: 'login',
      success: 1,
      error: 0,
      uid: user.login_id,
      maptype: 1,
      icontype: 1,
      usertype: 'USER',
      email: user.member_id,
      sqid: 0,
      syncid: 0,
      imei1: '',
      imei2: '',
      ward: 1,
      accuracy: "120",
      alarm_frequency: "1800000",
      location_update_frequency: "5000",
      tree_details_id_add: "0",
      nearby_accuracy: "120",
      nearby_distance: "200",
      nearby_locreq_freq: "8000", 
      user: {
        first_name: user.name,
        last_name: '',
        email: user.member_id,
        mobile_no: user.mobile_number || '',
        created_at: user.createdAt,
        isAdminRole: 0,
        user_type: 'USER'
      },
      treedetail: todayCountResult && todayCountResult.length > 0 ? parseInt(todayCountResult[0].count) : 0,
      totalCountForDay: todayCountResult && todayCountResult.length > 0 ? parseInt(todayCountResult[0].count) : 0,
      token: token,
      project:project
    };

    return res.json(response);
  } catch (error) {
    console.error('Login error:', error);
    return res.json({
      tag: 'login',
      success: 0,
      error: 1,
      error_msg: 'Login failed: ' + error.message
    });
  }
};

const register = async (req, res) => {
  try {
    const { first_name, last_name, email, password, mobile_no, type } = req.body;
    
    if (!first_name || !last_name || !email || !password || !mobile_no || !type) {
      return errorResponse(res, 'All fields are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Check if user already exists
    const [existingUsers] = await projectConnection.query(
      'SELECT uid FROM treeusers WHERE email = $1',
      {
        bind: [email],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    if (existingUsers && existingUsers.length > 0) {
      return res.json({
        tag: 'register',
        error: 2,
        success: 0,
        error_msg: 'User already existed'
      });
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // Insert new user
    await projectConnection.query(
      `INSERT INTO treeusers (first_name, last_name, email, password, mobile_no, isadminrole, isenabled, user_type, created_at) 
       VALUES ($1, $2, $3, $4, $5, 0, 1, $6, NOW())`,
      {
        bind: [first_name, last_name, email, hashedPassword, mobile_no, type]
      }
    );

    // Get the newly created user
    const [newUsers] = await projectConnection.query(
      'SELECT * FROM treeusers WHERE email = $1',
      {
        bind: [email],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    if (newUsers && newUsers.length > 0) {
      const newUser = newUsers[0];
      return res.json({
        tag: 'register',
        success: 1,
        error: 0,
        uid: newUser.uid,
        user: {
          first_name: newUser.first_name,
          last_name: newUser.last_name,
          email: newUser.email,
          mobile_no: newUser.mobile_no,
          created_at: newUser.created_at,
          type: newUser.user_type
        }
      });
    } else {
      return errorResponse(res, 'Registration failed', 500);
    }
  } catch (error) {
    console.error('Registration error:', error);
    return errorResponse(res, 'Registration failed', 500);
  }
};

const updateSqId = async (req, res) => {
  try {
    const { uid, sqid, update } = req.body;
    
    if (!uid || !sqid) {
      return errorResponse(res, 'UID and SQID are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    if (update === "yes") {
      await projectConnection.query(
        'UPDATE treeusers SET sqid = $1 WHERE uid = $2',
        {
          bind: [sqid, uid]
        }
      );
    }

    const [results] = await projectConnection.query(
      'SELECT sqid FROM treeusers WHERE uid = $1',
      {
        bind: [uid],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    if (results && results.length > 0) {
      return res.json({
        tag: 'updateSqId',
        success: 1,
        error: 0,
        sqid: results[0].sqid
      });
    } else {
      return res.json({
        tag: 'updateSqId',
        success: 0,
        error: 1
      });
    }
  } catch (error) {
    console.error('Update SQID error:', error);
    return errorResponse(res, 'Update SQID failed', 500);
  }
};

const getSqId = async (req, res) => {
  try {
    const { uid } = req.body;
    
    if (!uid) {
      return errorResponse(res, 'UID is required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [results] = await projectConnection.query(
      'SELECT sqid FROM treeusers WHERE uid = $1',
      {
        bind: [uid],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    if (results && results.length > 0) {
      return res.json({
        tag: 'getSqId',
        success: 1,
        error: 0,
        sqid: results[0].sqid
      });
    } else {
      return res.json({
        tag: 'getSqId',
        success: 0,
        error: 1
      });
    }
  } catch (error) {
    console.error('Get SQID error:', error);
    return errorResponse(res, 'Get SQID failed', 500);
  }
};

const getSyncId = async (req, res) => {
  try {
    const { uid } = req.body;
    
    if (!uid) {
      return errorResponse(res, 'UID is required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [results] = await projectConnection.query(
      'SELECT syncid FROM treeusers WHERE uid = $1',
      {
        bind: [uid],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    if (results && results.length > 0) {
      return res.json({
        tag: 'getSyncId',
        success: 1,
        error: 0,
        syncid: results[0].syncid
      });
    } else {
      return res.json({
        tag: 'getSyncId',
        success: 0,
        error: 1
      });
    }
  } catch (error) {
    console.error('Get SyncID error:', error);
    return errorResponse(res, 'Get SyncID failed', 500);
  }
};

// Master Data APIs
const getTreeDetails = async (req, res) => {
  try {
    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Get all master data
    const [treeList] = await projectConnection.query('SELECT * FROM treelist', { type: projectConnection.QueryTypes.SELECT });
    const [societyList] = await projectConnection.query('SELECT DISTINCT societyname FROM treedetailsentered WHERE societyname IS NOT NULL', { type: projectConnection.QueryTypes.SELECT });
    const [roadList] = await projectConnection.query('SELECT DISTINCT roadname FROM treedetailsentered WHERE roadname IS NOT NULL', { type: projectConnection.QueryTypes.SELECT });
    const [treeBalImbalance] = await projectConnection.query('SELECT * FROM treebal_imbalance', { type: projectConnection.QueryTypes.SELECT });
    const [treeCondition] = await projectConnection.query('SELECT * FROM condition', { type: projectConnection.QueryTypes.SELECT });
    const [treeOwnership] = await projectConnection.query('SELECT * FROM ownership', { type: projectConnection.QueryTypes.SELECT });
    const [treeRemarks] = await projectConnection.query('SELECT * FROM remarks', { type: projectConnection.QueryTypes.SELECT });
    const [treeSpatialComment] = await projectConnection.query('SELECT * FROM spacial_comment', { type: projectConnection.QueryTypes.SELECT });
    const [birdNest] = await projectConnection.query('SELECT * FROM bird_nest', { type: projectConnection.QueryTypes.SELECT });

    return res.json({
      tag: 'treedetails',
      success: 1,
      error: 0,
      treedetails: {
        treeList: treeList || [],
        societyList: societyList || [],
        roadList: roadList || [],
        treeBal_Imbalance: treeBalImbalance || [],
        treeCondition: treeCondition || [],
        treeOwnerShip: treeOwnership || [],
        treeRemarks: treeRemarks || [],
        treeSpatialComments: treeSpatialComment || [],
        birdNest: birdNest || []
      }
    });
  } catch (error) {
    console.error('Get tree details error:', error);
    return res.json({
      tag: 'treedetails',
      success: 0,
      error: 1,
      error_msg: 'Failed to get tree details: ' + error.message
    });
  }
};

const refreshSocietyRoad = async (req, res) => {
  try {
    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [societyList] = await projectConnection.query('SELECT DISTINCT societyname FROM treedetailsentered WHERE societyname IS NOT NULL', { type: projectConnection.QueryTypes.SELECT });
    const [roadList] = await projectConnection.query('SELECT DISTINCT roadname FROM treedetailsentered WHERE roadname IS NOT NULL', { type: projectConnection.QueryTypes.SELECT });

    return res.json({
      tag: 'refreshsocietyroad',
      success: 1,
      error: 0,
      societyroaddetails: {
        societyList: societyList || [],
        roadList: roadList || []
      }
    });
  } catch (error) {
    console.error('Refresh society road error:', error);
    return errorResponse(res, 'Failed to refresh society road data', 500);
  }
};

// Tree Survey APIs
const storeTreeDetails = async (req, res) => {
  try {
    const {
      user_id, sq_id, tree_id, latitude, longitude, old_latitude, old_longitude,
      drag_distance, othername, grith_cm, height_mtr, canopy_dia_mtr, condition_id,
      remarks_id, other_remarks, ownership_id, ownership_name, ownership_contact_no,
      balImbalance_id, societyname, roadname, googleAddress, entered_date, entered_time,
      updated_date, ward, is_within_boundary, version, dist_frm_prev_tree,
      spatialcomment_id, birdnest, date_of_plantation, client_name, contractor_name
    } = req.body;

    if (!user_id || !tree_id || !latitude || !longitude) {
      return res.json({
        tag: 'storetreedetails',
        success: 0,
        error: 1,
        error_msg: 'Required fields missing'
      });
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Insert tree details
    await projectConnection.query(
      `INSERT INTO treedetailsentered (
        user_id, sq_id, tree_id, latitude, longitude, old_latitude, old_longitude,
        drag_distance, othername, grith_cm, height_mtr, canopy_dia_mtr, condition_id,
        remarks_id, other_remarks, ownership_id, ownership_name, ownership_contact_no,
        balImbalance_id, societyname, roadname, googleAddress, entered_date, entered_time,
        updated_date, ward, is_within_boundary, version, dist_frm_prev_tree,
        spatialcomment_id, birdnest, date_of_plantation, client_name, contractor_name
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34)`,
      {
        bind: [
          user_id, sq_id, tree_id, latitude, longitude, old_latitude, old_longitude,
          drag_distance, othername, grith_cm, height_mtr, canopy_dia_mtr, condition_id,
          remarks_id, other_remarks, ownership_id, ownership_name, ownership_contact_no,
          balImbalance_id, societyname, roadname, googleAddress, entered_date, entered_time,
          updated_date, ward, is_within_boundary, version, dist_frm_prev_tree,
          spatialcomment_id, birdnest, date_of_plantation, client_name, contractor_name
        ]
      }
    );

    return res.json({
      tag: 'storetreedetails',
      success: 1,
      error: 0
    });
  } catch (error) {
    console.error('Store tree details error:', error);
    return res.json({
      tag: 'storetreedetails',
      success: 0,
      error: 1,
      error_msg: 'Failed to store tree details: ' + error.message
    });
  }
};

const updateTreeDetails = async (req, res) => {
  try {
    const {
      tree_details_id, user_id, tree_id, latitude, longitude, othername, grith_cm,
      height_mtr, canopy_dia_mtr, condition_id, remarks_id, other_remarks, ownership_id,
      ownership_name, ownership_contact_no, balImbalance_id, societyname, roadname,
      qc_id, qcstatus, isWithin, dist_frm_prev_tree, spatialcomment_id, birdnest,
      date_of_plantation, client_name, contractor_name
    } = req.body;

    if (!tree_details_id || !user_id) {
      return errorResponse(res, 'Tree details ID and user ID are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Update tree details
    await projectConnection.query(
      `UPDATE treedetailsentered SET 
        tree_id = $1, latitude = $2, longitude = $3, othername = $4, grith_cm = $5,
        height_mtr = $6, canopy_dia_mtr = $7, condition_id = $8, remarks_id = $9,
        other_remarks = $10, ownership_id = $11, ownership_name = $12, ownership_contact_no = $13,
        balImbalance_id = $14, societyname = $15, roadname = $16, qc_done = 1,
        qc_status = $17, qc_user = $18, dist_frm_prev_tree = $19, spatialcomment_id = $20,
        birdnest = $21, date_of_plantation = $22, client_name = $23, contractor_name = $24,
        updated_date = NOW()
      WHERE tree_details_id = $25 AND user_id = $26`,
      {
        bind: [
          tree_id, latitude, longitude, othername, grith_cm, height_mtr, canopy_dia_mtr,
          condition_id, remarks_id, other_remarks, ownership_id, ownership_name,
          ownership_contact_no, balImbalance_id, societyname, roadname, qcstatus,
          qc_id, dist_frm_prev_tree, spatialcomment_id, birdnest, date_of_plantation,
          client_name, contractor_name, tree_details_id, user_id
        ]
      }
    );

    return res.json({
      tag: 'updatetreedetails',
      success: 1,
      error: 0
    });
  } catch (error) {
    console.error('Update tree details error:', error);
    return errorResponse(res, 'Failed to update tree details', 500);
  }
};

const getTreeDetailsByUserID = async (req, res) => {
  try {
    const { user_id } = req.body;
    
    if (!user_id) {
      return errorResponse(res, 'User ID is required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [treeDetails] = await projectConnection.query(
      'SELECT * FROM treedetailsentered WHERE user_id = $1 ORDER BY entered_date DESC',
      {
        bind: [user_id],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    return res.json({
      tag: 'getTreeDetailsByUserID',
      success: 1,
      error: 0,
      treedetail: treeDetails || []
    });
  } catch (error) {
    console.error('Get tree details by user ID error:', error);
    return errorResponse(res, 'Failed to get tree details', 500);
  }
};

// QC APIs
const getTreeDetailsForQC = async (req, res) => {
  try {
    const { user_id } = req.body;
    
    if (!user_id) {
      return errorResponse(res, 'User ID is required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [treeDetails] = await projectConnection.query(
      'SELECT * FROM treedetailsentered WHERE qc_done = 0 OR qc_done IS NULL ORDER BY entered_date DESC',
      { type: projectConnection.QueryTypes.SELECT }
    );

    const [countResult] = await projectConnection.query(
      'SELECT COUNT(*) as count FROM treedetailsentered WHERE qc_done = 0 OR qc_done IS NULL',
      { type: projectConnection.QueryTypes.SELECT }
    );

    return res.json({
      tag: 'getTreeDetailsForQC',
      success: 1,
      error: 0,
      count: countResult && countResult.length > 0 ? countResult[0].count : 0,
      treedetail: treeDetails || []
    });
  } catch (error) {
    console.error('Get QC tree details error:', error);
    return errorResponse(res, 'Failed to get QC tree details', 500);
  }
};

const qc = async (req, res) => {
  try {
    const { qc_id, tree_id, qcstatus, all, user_id, is_admin } = req.body;
    
    if (!qc_id || !tree_id || !qcstatus) {
      return errorResponse(res, 'QC ID, tree ID, and QC status are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Update QC status
    await projectConnection.query(
      'UPDATE treedetailsentered SET qc_done = 1, qc_status = $1, qc_user = $2 WHERE tree_details_id = $3',
      {
        bind: [qcstatus, qc_id, tree_id]
      }
    );

    return res.json({
      tag: 'qc',
      success: 1,
      error: 0
    });
  } catch (error) {
    console.error('QC update error:', error);
    return errorResponse(res, 'Failed to update QC status', 500);
  }
};

// Location Tracking APIs
const submitLocation = async (req, res) => {
  try {
    const { uid, lat, lon } = req.body;
    
    if (!uid || !lat || !lon) {
      return errorResponse(res, 'UID, latitude, and longitude are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Store login details with location
    await projectConnection.query(
      'INSERT INTO login_details (uid, latitude, longitude, login_time) VALUES ($1, $2, $3, NOW())',
      {
        bind: [uid, lat, lon]
      }
    );

    return res.json({
      tag: 'submit_location',
      success: 1,
      error: 0,
      message: 'login details stored'
    });
  } catch (error) {
    console.error('Submit location error:', error);
    return errorResponse(res, 'Failed to store location', 500);
  }
};

const saveTrackPath = async (req, res) => {
  try {
    const { uid, latitude, longitude } = req.body;
    
    if (!uid || !latitude || !longitude) {
      return errorResponse(res, 'UID, latitude, and longitude are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Store tracking path
    await projectConnection.query(
      'INSERT INTO track_path (uid, latitude, longitude, timestamp) VALUES ($1, $2, $3, NOW())',
      {
        bind: [uid, latitude, longitude]
      }
    );

    return res.json({
      tag: 'savetrackpath',
      success: 1,
      error: 0,
      message: 'location stored'
    });
  } catch (error) {
    console.error('Save track path error:', error);
    return errorResponse(res, 'Failed to save track path', 500);
  }
};

const getNearbyTrees = async (req, res) => {
  try {
    const { northLat, southLat, westLon, eastLon } = req.body;
    
    if (!northLat || !southLat || !westLon || !eastLon) {
      return errorResponse(res, 'All coordinate parameters are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [nearbyTrees] = await projectConnection.query(
      `SELECT * FROM treedetailsentered 
       WHERE latitude BETWEEN $1 AND $2 AND longitude BETWEEN $3 AND $4`,
      {
        bind: [southLat, northLat, westLon, eastLon],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    if (!nearbyTrees || nearbyTrees.length === 0) {
      return res.json({
        tag: 'getNearbyTrees',
        success: 2,
        error: 0
      });
    }

    return res.json({
      tag: 'getNearbyTrees',
      success: 1,
      error: 0,
      treedetail: nearbyTrees
    });
  } catch (error) {
    console.error('Get nearby trees error:', error);
    return res.json({
      tag: 'getNearbyTrees',
      success: 0,
      error: 1,
      error_msg: 'Failed to get nearby trees'
    });
  }
};

// Report APIs
const getExcelReport = async (req, res) => {
  try {
    const { fromDate, toDate } = req.body;
    
    if (!fromDate || !toDate) {
      return errorResponse(res, 'From date and to date are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [reportData] = await projectConnection.query(
      `SELECT * FROM treedetailsentered 
       WHERE DATE(entered_date) BETWEEN $1 AND $2 
       ORDER BY entered_date DESC`,
      {
        bind: [fromDate, toDate],
        type: projectConnection.QueryTypes.SELECT
      }
    );

    return res.json({
      tag: 'getExcelReport',
      success: 1,
      error: 0,
      fromdate: fromDate,
      todate: toDate,
      url: `${process.env.BASE_URL || 'http://172.17.46.11:63318'}/api/mobile/project/${req.params.treelogy_id}/excel-report`
    });
  } catch (error) {
    console.error('Get excel report error:', error);
    return errorResponse(res, 'Failed to get excel report', 500);
  }
};

const getQcReport = async (req, res) => {
  try {
    const { uid, utype } = req.body;
    
    if (!uid || !utype) {
      return errorResponse(res, 'UID and user type are required', 400);
    }

    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    // Get QC counts
    const [qcDoneCount] = await projectConnection.query('SELECT COUNT(*) as count FROM treedetailsentered WHERE qc_done = 1', { type: projectConnection.QueryTypes.SELECT });
    const [qcPendingCount] = await projectConnection.query('SELECT COUNT(*) as count FROM treedetailsentered WHERE qc_done = 0 OR qc_done IS NULL', { type: projectConnection.QueryTypes.SELECT });
    const [qcAccCount] = await projectConnection.query('SELECT COUNT(*) as count FROM treedetailsentered WHERE qc_status = 1', { type: projectConnection.QueryTypes.SELECT });
    const [qcRejCount] = await projectConnection.query('SELECT COUNT(*) as count FROM treedetailsentered WHERE qc_status = 0', { type: projectConnection.QueryTypes.SELECT });
    const [qcRecCount] = await projectConnection.query('SELECT COUNT(*) as count FROM treedetailsentered WHERE qc_status = 2', { type: projectConnection.QueryTypes.SELECT });

    return res.json({
      tag: 'getQcReport',
      success: 1,
      error: 0,
      email: 'user@example.com',
      qcDoneCount: qcDoneCount && qcDoneCount.length > 0 ? qcDoneCount[0].count : 0,
      qcPendingCount: qcPendingCount && qcPendingCount.length > 0 ? qcPendingCount[0].count : 0,
      qcAccCount: qcAccCount && qcAccCount.length > 0 ? qcAccCount[0].count : 0,
      qcRejCount: qcRejCount && qcRejCount.length > 0 ? qcRejCount[0].count : 0,
      qcRecCount: qcRecCount && qcRecCount.length > 0 ? qcRecCount[0].count : 0
    });
  } catch (error) {
    console.error('Get QC report error:', error);
    return errorResponse(res, 'Failed to get QC report', 500);
  }
};

// Get enumerators (users list)
const getEnumerators = async (req, res) => {
  try {
    const projectConnection = await getProjectDbConnection(req.params.treelogy_id);
    
    const [results] = await projectConnection.query(
      'SELECT uid, first_name, last_name, email, mobile_no, user_type, isenabled FROM treeusers ORDER BY first_name',
      { type: projectConnection.QueryTypes.SELECT }
    );

    return res.json({
      tag: 'getEnumerators',
      success: 1,
      error: 0,
      enumerators: results || []
    });
  } catch (error) {
    console.error('Get enumerators error:', error);
    return res.json({
      tag: 'getEnumerators',
      success: 0,
      error: 1,
      error_msg: 'Failed to get enumerators'
    });
  }
};

export {
  // Authentication
  login,
  register,
  updateSqId,
  getSqId,
  getSyncId,
  
  // Master Data
  getTreeDetails,
  refreshSocietyRoad,
  getEnumerators,
  
  // Tree Survey
  storeTreeDetails,
  updateTreeDetails,
  getTreeDetailsByUserID,
  
  // QC
  getTreeDetailsForQC,
  qc,
  
  // Location Tracking
  submitLocation,
  saveTrackPath,
  getNearbyTrees,
  
  // Reports
  getExcelReport,
  getQcReport
};

