<?php
/**
 * Enterprise HRM ERP System - Export Preview (AJAX)
 * Returns record count for preview
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

header('Content-Type: application/json');

$siteId = getCurrentSiteId();
$reportType = $_POST['type'] ?? $_GET['type'] ?? 'attendance';
$dateFrom = $_POST['date_from'] ?? $_GET['date_from'] ?? date('Y-m-01');
$dateTo = $_POST['date_to'] ?? $_GET['date_to'] ?? date('Y-m-d');
$departmentId = isset($_POST['department_id']) ? (int)$_POST['department_id'] : (isset($_GET['department_id']) ? (int)$_GET['department_id'] : 0);
$designationId = isset($_POST['designation_id']) ? (int)$_POST['designation_id'] : (isset($_GET['designation_id']) ? (int)$_GET['designation_id'] : 0);
$leaveTypeId = isset($_POST['leave_type_id']) ? (int)$_POST['leave_type_id'] : (isset($_GET['leave_type_id']) ? (int)$_GET['leave_type_id'] : 0);
$periodId = isset($_POST['period_id']) ? (int)$_POST['period_id'] : (isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0);
$status = $_POST['status'] ?? $_GET['status'] ?? '';

try {
    $db = getDB();
    $count = 0;
    
    switch ($reportType) {
        case 'attendance':
            $where = "a.site_id = ? AND a.attendance_date BETWEEN ? AND ?";
            $params = [$siteId, $dateFrom, $dateTo];
            
            if ($departmentId > 0 || $designationId > 0) {
                $where .= " AND EXISTS (
                    SELECT 1 FROM employees e 
                    WHERE e.employee_id = a.employee_id";
                if ($departmentId > 0) {
                    $where .= " AND e.department_id = ?";
                    $params[] = $departmentId;
                }
                if ($designationId > 0) {
                    $where .= " AND e.designation_id = ?";
                    $params[] = $designationId;
                }
                $where .= ")";
            }
            
            $stmt = $db->prepare("SELECT COUNT(*) FROM attendance a WHERE {$where}");
            $stmt->execute($params);
            $count = $stmt->fetchColumn();
            break;
            
        case 'leave':
            $where = "la.site_id = ? AND la.applied_at BETWEEN ? AND ?";
            $params = [$siteId, $dateFrom, $dateTo];
            
            if ($leaveTypeId > 0) {
                $where .= " AND la.leave_type_id = ?";
                $params[] = $leaveTypeId;
            }
            
            if (!empty($status)) {
                $where .= " AND la.application_status = ?";
                $params[] = $status;
            }
            
            if ($departmentId > 0 || $designationId > 0) {
                $where .= " AND EXISTS (
                    SELECT 1 FROM employees e 
                    WHERE e.employee_id = la.employee_id";
                if ($departmentId > 0) {
                    $where .= " AND e.department_id = ?";
                    $params[] = $departmentId;
                }
                if ($designationId > 0) {
                    $where .= " AND e.designation_id = ?";
                    $params[] = $designationId;
                }
                $where .= ")";
            }
            
            $stmt = $db->prepare("SELECT COUNT(*) FROM leave_applications la WHERE {$where}");
            $stmt->execute($params);
            $count = $stmt->fetchColumn();
            break;
            
        case 'payroll':
            $where = "pr.site_id = ?";
            $params = [$siteId];
            
            if ($periodId > 0) {
                $where .= " AND pr.period_id = ?";
                $params[] = $periodId;
            } else {
                $where .= " AND pp.start_date >= ? AND pp.end_date <= ?";
                $params[] = $dateFrom;
                $params[] = $dateTo;
            }
            
            if ($departmentId > 0 || $designationId > 0) {
                $where .= " AND EXISTS (
                    SELECT 1 FROM employees e 
                    WHERE e.employee_id = pr.employee_id";
                if ($departmentId > 0) {
                    $where .= " AND e.department_id = ?";
                    $params[] = $departmentId;
                }
                if ($designationId > 0) {
                    $where .= " AND e.designation_id = ?";
                    $params[] = $designationId;
                }
                $where .= ")";
            }
            
            $stmt = $db->prepare("
                SELECT COUNT(*) 
                FROM payroll_records pr
                INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
                WHERE {$where}
            ");
            $stmt->execute($params);
            $count = $stmt->fetchColumn();
            break;
            
        case 'employee':
            $where = "e.site_id = ?";
            $params = [$siteId];
            
            if ($departmentId > 0) {
                $where .= " AND e.department_id = ?";
                $params[] = $departmentId;
            }
            
            if ($designationId > 0) {
                $where .= " AND e.designation_id = ?";
                $params[] = $designationId;
            }
            
            $stmt = $db->prepare("SELECT COUNT(*) FROM employees e WHERE {$where}");
            $stmt->execute($params);
            $count = $stmt->fetchColumn();
            break;
            
        default:
            $count = 0;
    }
    
    echo json_encode(['count' => (int)$count]);
    
} catch (Exception $e) {
    error_log("Export preview error: " . $e->getMessage());
    echo json_encode(['count' => 0, 'error' => $e->getMessage()]);
}

