<?php
/**
 * Salary Register - CSV Export
 * Exports salary data in Excel-compatible format
 */

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

$siteId = getCurrentSiteId();
$userId = $_SESSION['user_id'] ?? 1;
$db = getDB();

// Get parameters
$selectedMonthFull = $_GET['month'] ?? date('F Y');
$hrFilter = isset($_GET['hr']) && !empty($_GET['hr']) ? intval($_GET['hr']) : null;
$viewType = $_GET['view_type'] ?? 'all';

// Build query with HR-level filtering
$whereConditions = ["e.site_id = ?", "e.employment_status = 'active'", "sr.salary_register_id IS NOT NULL"];
$params = [$selectedMonthFull, $siteId];

// Apply filtering
if (isHRAdmin()) {
    // HR Admin: Only their employees
    $whereConditions[] = "sr.hr_id = ?";
    $params[] = $userId;
} elseif (isSuperAdmin()) {
    // Super Admin: Different view types
    if ($viewType == 'hr_employees') {
        // Show only HR staff
        $whereConditions[] = "EXISTS (SELECT 1 FROM users usr WHERE usr.user_id = e.created_by AND usr.role_id IN (SELECT role_id FROM roles WHERE role_code IN ('hr_admin', 'super_admin')))";
    } 
    elseif ($viewType == 'regular_employees') {
        // Show only regular employees
        $whereConditions[] = "NOT EXISTS (SELECT 1 FROM users usr WHERE usr.user_id = e.created_by AND usr.role_id IN (SELECT role_id FROM roles WHERE role_code IN ('hr_admin', 'super_admin')))";
    }
    elseif ($viewType == 'by_hr' && $hrFilter) {
        // Filter by specific HR
        $whereConditions[] = "sr.hr_id = ?";
        $params[] = $hrFilter;
    }
}

$whereClause = implode(' AND ', $whereConditions);

// Fetch data
$stmt = $db->prepare("
    SELECT 
        e.employee_code,
    CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as employee_name,
    d.designation_name,
    u.full_name as hr_name,
    CASE 
        WHEN EXISTS (
            SELECT 1 FROM users usr 
            INNER JOIN roles r ON usr.role_id = r.role_id 
            WHERE usr.user_id = sr.hr_id 
            AND r.role_code IN ('hr_admin', 'super_admin')
        ) THEN 'HR Staff'
        ELSE 'Regular Employee'
    END as employee_category,
    sr.*
    FROM employees e
    LEFT JOIN designations d ON e.designation_id = d.designation_id
    LEFT JOIN salary_register sr ON e.employee_id = sr.employee_id AND sr.salary_month = ?
    LEFT JOIN users u ON sr.hr_id = u.user_id
    WHERE {$whereClause}
    ORDER BY e.employee_code
");
$stmt->execute($params);
$employees = $stmt->fetchAll();

// Set headers for CSV download
$viewTypeSuffix = '';
if (isSuperAdmin()) {
    switch ($viewType) {
        case 'hr_employees':
            $viewTypeSuffix = '_HR_Staff';
            break;
        case 'regular_employees':
            $viewTypeSuffix = '_Regular_Employees';
            break;
        case 'by_hr':
            $viewTypeSuffix = $hrFilter ? '_HR_' . $hrFilter : '';
            break;
    }
}
$filename = "Salary_Register_" . str_replace(' ', '_', $selectedMonthFull) . $viewTypeSuffix . "_" . date('YmdHis') . ".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

// Create output stream
$output = fopen('php://output', 'w');

// Add BOM for Excel UTF-8 support
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Write headers
$headers = [
    'S/L No',
    'Employee Code',
    'Employee Name',
    'Designation',
    'Employee Category',
    'HR Manager',
    'Employee Type',
    'Category',
    'Status',
    // Employer Structure
    'Basic',
    'VDA',
    'Special Allowance',
    'Other Allowance',
    'HRA',
    'Total Earning',
    // Attendance
    'Present',
    'Absent',
    'Weekly Off',
    'Pay Days',
    // Earned Salary
    'Earned Basic',
    'Earned HRA',
    'Earned Other Allowance',
    'Spl Allowance',
    'Total Earning (Earned)',
    'PF',
    'ESI',
    'PT',
    'Total Deduction',
    'Net Salary',
    // Rebill
    'Provident Fund (12%)',
    'ESIC (3.25%)',
    'Leave',
    'Holiday',
    'Bonus',
    'Uniform',
    'Gratuity',
    'Food Allowance',
    'Total Rebill',
    'Earned CTC',
    'Per Day Wages'
];

fputcsv($output, $headers);

// Write data
$slNo = 1;
foreach ($employees as $emp) {
    $row = [
        $slNo++,
        $emp['employee_code'] ?? '',
        $emp['employee_name'] ?? '',
        $emp['designation_name'] ?? '',
        $emp['employee_category'] ?? 'Regular Employee',
        $emp['hr_name'] ?? 'Not Assigned',
        $emp['employee_type'] ?? 'FTC',
        $emp['category'] ?? 'Skilled',
        ucfirst($emp['employment_status'] ?? 'active'),
        // Employer Structure
        $emp['basic'] ?? 0,
        $emp['vda'] ?? 0,
        $emp['special_allowance'] ?? 0,
        $emp['other_allowance'] ?? 0,
        $emp['hra'] ?? 0,
        $emp['total_earning'] ?? 0,
        // Attendance
        $emp['present'] ?? 0,
        $emp['absent'] ?? 0,
        $emp['weekly_off'] ?? 0,
        $emp['pay_days'] ?? 0,
        // Earned Salary
        $emp['earned_basic'] ?? 0,
        $emp['earned_hra'] ?? 0,
        $emp['earned_other_allowance'] ?? 0,
        $emp['spl_allowance'] ?? 0,
        $emp['total_earning_earned'] ?? 0,
        $emp['pf'] ?? 0,
        $emp['esi'] ?? 0,
        $emp['pt'] ?? 0,
        $emp['total_deduction'] ?? 0,
        $emp['net_salary'] ?? 0,
        // Rebill
        $emp['provident_fund'] ?? 0,
        $emp['esic'] ?? 0,
        $emp['leave_amount'] ?? 0,
        $emp['holiday'] ?? 0,
        $emp['bonus'] ?? 0,
        $emp['uniform'] ?? 0,
        $emp['gratuity'] ?? 0,
        $emp['food_allowance'] ?? 0,
        $emp['total_rebill'] ?? 0,
        $emp['earned_ctc'] ?? 0,
        $emp['per_day_wages'] ?? 0
    ];
    
    fputcsv($output, $row);
}

fclose($output);
exit;
