<?php
/**
 * Salary Register - Period-based System
 * Like Attendance module with month/year selection
 */

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

$pageTitle = "Salary Register";
$currentTab = 'salary_register';
$siteId = getCurrentSiteId();
$db = getDB();
$siteName = $_SESSION['site_name'] ?? 'Base Office';
$userId = $_SESSION['user_id'] ?? 1;

// Check if tables exist
$tablesExist = false;
try {
    $checkTables = $db->query("
        SELECT COUNT(*) as cnt FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name IN ('salary_register', 'salary_periods')
    ");
    $result = $checkTables->fetch();
    $tablesExist = ($result['cnt'] == 2);
} catch (Exception $e) {
    $tablesExist = false;
}

if (!$tablesExist) {
    // Show migration warning with fix link
    $errorMessage = "⚠️ Required tables not found! Please run setup first.";
    $employees = [];
    $periodExists = false;
    $showFixLink = true;
} else {
    // Handle New Period Creation
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_new_period'])) {
        try {
            $newMonth = $_POST['new_month'];
            $newYear = intval($_POST['new_year']);
            
            // Convert to proper format
            $monthAbbr = date('M', strtotime($newMonth . ' 1'));
            $yearAbbr = substr($newYear, -2);
            $salaryMonth = $monthAbbr . '-' . $yearAbbr; // e.g., "Jan-26"
            $periodDisplay = $newMonth . ' ' . $newYear; // e.g., "January 2026"
            
            // Check if period already exists for this HR (or globally for admin)
            if (isHRAdmin()) {
                // HR Admin: Check if they already have this period
            $checkStmt = $db->prepare("
                    SELECT COUNT(*) as cnt FROM salary_register sr
                    INNER JOIN employees e ON sr.employee_id = e.employee_id
                    WHERE sr.site_id = ? AND sr.salary_month = ? AND e.created_by = ?
            ");
                $checkStmt->execute([$siteId, $periodDisplay, $userId]);
                $existingCount = $checkStmt->fetch()['cnt'];
            
                if ($existingCount > 0) {
                    $errorMessage = "Period {$periodDisplay} already exists for your employees!";
            } else {
                $db->beginTransaction();
                
                    // Get HR Admin's active employees
                    $empStmt = $db->prepare("
                        SELECT employee_id FROM employees 
                        WHERE site_id = ? AND employment_status = 'active' AND created_by = ?
                    ");
                    $empStmt->execute([$siteId, $userId]);
                    $employees = $empStmt->fetchAll();
                    
                    if (count($employees) == 0) {
                        throw new Exception("No active employees found under your management.");
                    }
                    
                    // Check if period exists in salary_periods, create if not
                    $periodCheckStmt = $db->prepare("
                        SELECT period_id FROM salary_periods 
                        WHERE site_id = ? AND salary_month = ?
                ");
                    $periodCheckStmt->execute([$siteId, $salaryMonth]);
                    
                    if (!$periodCheckStmt->fetch()) {
                $periodStmt = $db->prepare("
                    INSERT INTO salary_periods 
                    (site_id, salary_month, period_display, employee_count, created_by)
                    VALUES (?, ?, ?, ?, ?)
                ");
                        $periodStmt->execute([$siteId, $salaryMonth, $periodDisplay, count($employees), $userId]);
                    }
                
                    // Initialize salary_register entries with HR assignment
                    $insertStmt = $db->prepare("
                        INSERT INTO salary_register 
                        (site_id, hr_id, employee_id, salary_month, employee_type, category)
                        VALUES (?, ?, ?, ?, 'FTC', 'Skilled')
                    ");
                    
                    foreach ($employees as $emp) {
                        $insertStmt->execute([$siteId, $userId, $emp['employee_id'], $periodDisplay]);
                    }
                    
                    $db->commit();
                    $successMessage = "New salary period created: {$periodDisplay} with " . count($employees) . " employee(s)";
                    
                    // Redirect to new period
                    header("Location: ?m=" . urlencode($salaryMonth) . "&y=" . $yearAbbr);
                    exit;
                }
            } else {
                // Super Admin: Check if period exists globally
                $checkStmt = $db->prepare("
                    SELECT period_id FROM salary_periods 
                    WHERE site_id = ? AND salary_month = ?
                ");
                $checkStmt->execute([$siteId, $salaryMonth]);
                
                if ($checkStmt->fetch()) {
                    $errorMessage = "Period {$periodDisplay} already exists!";
                } else {
                    $db->beginTransaction();
                    
                    // Get ALL active employees
                $empStmt = $db->prepare("
                        SELECT employee_id, created_by FROM employees 
                        WHERE site_id = ? AND employment_status = 'active'
                ");
                    $empStmt->execute([$siteId]);
                $employees = $empStmt->fetchAll();
                
                    // Create period
                    $periodStmt = $db->prepare("
                        INSERT INTO salary_periods 
                        (site_id, salary_month, period_display, employee_count, created_by)
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    $periodStmt->execute([$siteId, $salaryMonth, $periodDisplay, count($employees), $userId]);
                    
                    // Initialize salary_register entries with HR assignment
                $insertStmt = $db->prepare("
                    INSERT INTO salary_register 
                        (site_id, hr_id, employee_id, salary_month, employee_type, category)
                        VALUES (?, ?, ?, ?, 'FTC', 'Skilled')
                ");
                
                foreach ($employees as $emp) {
                        $insertStmt->execute([$siteId, $emp['created_by'], $emp['employee_id'], $periodDisplay]);
                }
                
                $db->commit();
                    $successMessage = "New salary period created: {$periodDisplay} with " . count($employees) . " employee(s)";
                
                // Redirect to new period
                header("Location: ?m=" . urlencode($salaryMonth) . "&y=" . $yearAbbr);
                exit;
                }
            }
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $errorMessage = "Error creating period: " . $e->getMessage();
        }
    }

    // Handle Save Salary Data
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_salary'])) {
        try {
            $db->beginTransaction();
            
            // Get the salary month from POST (sent via hidden field)
            $saveMonthFull = $_POST['salary_month'] ?? date('F Y');
            
            // Debug: Log the save attempt
            error_log("Saving salary for month: " . $saveMonthFull);
            
            if (!isset($_POST['employees']) || !is_array($_POST['employees'])) {
                throw new Exception("No employee data received");
            }
            
            $savedCount = 0;
            foreach ($_POST['employees'] as $empId => $data) {
                $employee_type = $data['employee_type'] ?? 'FTC';
                $category = $data['category'] ?? 'Skilled';
                
                $basic = floatval($data['basic'] ?? 0);
                $vda = floatval($data['vda'] ?? 0);
                $special_allowance = floatval($data['special_allowance'] ?? 0);
                $other_allowance = floatval($data['other_allowance'] ?? 0);
                $hra = floatval($data['hra'] ?? 0);
                $total_earning = $basic + $vda + $special_allowance + $other_allowance + $hra;
                
                $present = intval($data['present'] ?? 0);
                $absent = intval($data['absent'] ?? 0);
                $weekly_off = intval($data['weekly_off'] ?? 0);
                $pay_days = intval($data['pay_days'] ?? 0);
                
                $earned_basic = floatval($data['earned_basic'] ?? 0);
                $earned_hra = floatval($data['earned_hra'] ?? 0);
                $earned_other_allowance = floatval($data['earned_other_allowance'] ?? 0);
                $spl_allowance = floatval($data['spl_allowance'] ?? 0);
                $total_earning_earned = floatval($data['total_earning_earned'] ?? 0);
                
                $pf = floatval($data['pf'] ?? 0);
                $esi = floatval($data['esi'] ?? 0);
                $pt = floatval($data['pt'] ?? 0);
                $total_deduction = $pf + $esi + $pt;
                $net_salary = $total_earning_earned - $total_deduction;
                
                $provident_fund = floatval($data['provident_fund'] ?? 0);
                $esic = floatval($data['esic'] ?? 0);
                $leave_amount = floatval($data['leave'] ?? 0);
                $holiday = floatval($data['holiday'] ?? 0);
                $bonus = floatval($data['bonus'] ?? 0);
                $uniform = floatval($data['uniform'] ?? 0);
                $gratuity = floatval($data['gratuity'] ?? 0);
                $food_allowance = floatval($data['food_allowance'] ?? 0);
                $total_rebill = $provident_fund + $esic + $leave_amount + $holiday + $bonus + $uniform + $gratuity + $food_allowance;
                
                $earned_ctc = $total_earning_earned + $pf + $esi + $esic + $provident_fund;
                $per_day_wages = floatval($data['per_day_wages'] ?? 0);
                
                $stmt = $db->prepare("
                    UPDATE salary_register SET
                        employee_type = ?, category = ?,
                        basic = ?, vda = ?, special_allowance = ?, other_allowance = ?, hra = ?, total_earning = ?,
                        present = ?, absent = ?, weekly_off = ?, pay_days = ?,
                        earned_basic = ?, earned_hra = ?, earned_other_allowance = ?, spl_allowance = ?, total_earning_earned = ?,
                        pf = ?, esi = ?, pt = ?, total_deduction = ?, net_salary = ?,
                        provident_fund = ?, esic = ?, leave_amount = ?, holiday = ?, bonus = ?, uniform = ?, gratuity = ?, food_allowance = ?,
                        total_rebill = ?, earned_ctc = ?, per_day_wages = ?,
                        updated_at = NOW()
                    WHERE employee_id = ? AND salary_month = ? AND site_id = ?
                ");
                $result = $stmt->execute([
                    $employee_type, $category,
                    $basic, $vda, $special_allowance, $other_allowance, $hra, $total_earning,
                    $present, $absent, $weekly_off, $pay_days,
                    $earned_basic, $earned_hra, $earned_other_allowance, $spl_allowance, $total_earning_earned,
                    $pf, $esi, $pt, $total_deduction, $net_salary,
                    $provident_fund, $esic, $leave_amount, $holiday, $bonus, $uniform, $gratuity, $food_allowance,
                    $total_rebill, $earned_ctc, $per_day_wages,
                    $empId, $saveMonthFull, $siteId
                ]);
                
                if ($stmt->rowCount() > 0) {
                    $savedCount++;
                }
            }
            
            $db->commit();
            
            // Redirect with success
            $m = $_GET['m'] ?? '';
            $y = $_GET['y'] ?? '';
            header("Location: ?m=" . urlencode($m) . "&y=" . urlencode($y) . "&saved=" . $savedCount);
            exit;
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $errorMessage = "Error saving: " . $e->getMessage();
        }
    }

    if (isset($_GET['saved'])) {
        $count = intval($_GET['saved']);
        $successMessage = "✅ Salary data saved successfully for {$count} employee(s)!";
    }

    // Get available periods and years
    $availablePeriodsStmt = $db->prepare("
        SELECT DISTINCT salary_month, period_display 
        FROM salary_periods 
        WHERE site_id = ?
        ORDER BY created_at DESC
    ");
    $availablePeriodsStmt->execute([$siteId]);
    $availablePeriods = $availablePeriodsStmt->fetchAll();

    // Get years with data
    $yearsStmt = $db->prepare("
        SELECT DISTINCT SUBSTRING(salary_month, 5, 2) as year_short
        FROM salary_periods
        WHERE site_id = ?
        ORDER BY salary_month DESC
    ");
    $yearsStmt->execute([$siteId]);
    $yearsData = $yearsStmt->fetchAll();

    $years = [];
    $currentYear = intval(date('Y'));
    $baseYears = range(2025, $currentYear + 5);
    foreach ($baseYears as $yr) {
        $yearShort = substr($yr, -2);
        $hasData = false;
        foreach ($yearsData as $yd) {
            if ($yd['year_short'] == $yearShort) {
                $hasData = true;
                break;
            }
        }
        $years[] = ['year' => $yr, 'has_data' => $hasData];
    }

    // Handle month/year selection
    $currentMonthShort = date('M-y'); // e.g., "Jan-25"
    $selectedMonthName = isset($_GET['m']) ? $_GET['m'] : (count($availablePeriods) > 0 ? $availablePeriods[0]['salary_month'] : $currentMonthShort);
    $selectedYearValue = isset($_GET['y']) ? $_GET['y'] : date('y'); // 2-digit year
    
    // Ensure year is 2-digit
    if (strlen($selectedYearValue) == 4) {
        $selectedYearValue = substr($selectedYearValue, -2);
    }
    
    // Convert short month to full for display
    if (preg_match('/^([A-Za-z]{3})-(\d{2})$/', $selectedMonthName, $matches)) {
        $monthName = $matches[1];
        $yearShort = $matches[2];
        $monthFull = date('F', strtotime($monthName . ' 1'));
        $yearFull = '20' . $yearShort;
        $selectedMonthFull = $monthFull . ' ' . $yearFull;
    } else {
        // If full format, extract components
        if (preg_match('/^([A-Z][a-z]+)\s+(\d{4})$/', $selectedMonthName, $matches)) {
            $monthFull = $matches[1];
            $yearFull = $matches[2];
            $selectedMonthFull = $selectedMonthName;
            $yearShort = substr($yearFull, -2);
        } else {
            $selectedMonthFull = $selectedMonthName;
            $yearShort = $selectedYearValue;
        }
    }

    // Check if period exists
    $periodCheckStmt = $db->prepare("
        SELECT period_id FROM salary_periods 
        WHERE site_id = ? AND salary_month = ?
    ");
    $periodCheckStmt->execute([$siteId, $selectedMonthName]);
    $periodExists = $periodCheckStmt->rowCount() > 0;

    // Get employees data with HR-level filtering
    // Show employees even if period doesn't exist (will be read-only)
    $employees = [];
    // Always fetch employees for the selected period
    {
        // Build query with role-based filtering
        // Changed: Removed "sr.salary_register_id IS NOT NULL" to show all active employees
        $whereConditions = ["e.site_id = ?", "e.employment_status = 'active'"];
        $whereParams = [$siteId];
        
        // HR Admin: Only see employees they created/manage
        if (isHRAdmin()) {
            $whereConditions[] = "e.created_by = ?";
            $whereParams[] = $userId;
        }
        // Super Admin: Different view types
        elseif (isSuperAdmin()) {
            $viewType = $_GET['view_type'] ?? 'all';
            
            if ($viewType == 'hr_employees') {
                // Show only HR staff (users who are also employees)
                $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 (not HR staff)
                $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' && isset($_GET['hr']) && !empty($_GET['hr'])) {
                // Filter by specific HR (use created_by as fallback if sr.hr_id is NULL)
                $whereConditions[] = "COALESCE(sr.hr_id, e.created_by) = ?";
                $whereParams[] = intval($_GET['hr']);
            }
            // 'all' - no additional filter, show everyone
        }
        
        $whereClause = implode(' AND ', $whereConditions);
        
        // Build params array in SQL placeholder order:
        // 1. SELECT placeholder (COALESCE)
        // 2. JOIN placeholder (sr.salary_month)
        // 3. WHERE placeholders (site_id, created_by/hr_id if applicable)
        $params = [];
        $params[] = $selectedMonthFull; // For COALESCE(sr.salary_month, ?) in SELECT
        $params[] = $selectedMonthFull; // For JOIN condition sr.salary_month = ?
        $params = array_merge($params, $whereParams); // Add WHERE params
        
        $stmt = $db->prepare("
            SELECT 
                e.employee_id,
                e.employee_code,
                CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                d.designation_name,
                e.employment_status,
                e.created_by,
                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 = COALESCE(sr.hr_id, e.created_by)
                        AND (LOWER(r.role_code) = 'hr_admin' OR r.role_code = 'HR_ADMIN' OR LOWER(r.role_code) = 'super_admin')
                    ) THEN 'HR Staff'
                    ELSE 'Regular Employee'
                END as employee_category,
                COALESCE(sr.salary_register_id, 0) as salary_register_id,
                COALESCE(sr.hr_id, e.created_by) as hr_id,
                COALESCE(sr.salary_month, ?) as salary_month,
                COALESCE(sr.employee_type, 'FTC') as employee_type,
                COALESCE(sr.category, 'Skilled') as category,
                COALESCE(sr.basic, 0) as basic,
                COALESCE(sr.vda, 0) as vda,
                COALESCE(sr.special_allowance, 0) as special_allowance,
                COALESCE(sr.other_allowance, 0) as other_allowance,
                COALESCE(sr.hra, 0) as hra,
                COALESCE(sr.total_earning, 0) as total_earning,
                COALESCE(sr.present, 0) as present,
                COALESCE(sr.absent, 0) as absent,
                COALESCE(sr.weekly_off, 0) as weekly_off,
                COALESCE(sr.pay_days, 0) as pay_days,
                COALESCE(sr.earned_basic, 0) as earned_basic,
                COALESCE(sr.earned_hra, 0) as earned_hra,
                COALESCE(sr.earned_other_allowance, 0) as earned_other_allowance,
                COALESCE(sr.spl_allowance, 0) as spl_allowance,
                COALESCE(sr.total_earning_earned, 0) as total_earning_earned,
                COALESCE(sr.pf, 0) as pf,
                COALESCE(sr.esi, 0) as esi,
                COALESCE(sr.pt, 0) as pt,
                COALESCE(sr.total_deduction, 0) as total_deduction,
                COALESCE(sr.net_salary, 0) as net_salary,
                COALESCE(sr.provident_fund, 0) as provident_fund,
                COALESCE(sr.esic, 0) as esic,
                COALESCE(sr.leave_amount, 0) as leave_amount,
                COALESCE(sr.holiday, 0) as holiday,
                COALESCE(sr.bonus, 0) as bonus,
                COALESCE(sr.uniform, 0) as uniform,
                COALESCE(sr.gratuity, 0) as gratuity,
                COALESCE(sr.food_allowance, 0) as food_allowance,
                COALESCE(sr.total_rebill, 0) as total_rebill,
                COALESCE(sr.earned_ctc, 0) as earned_ctc,
                COALESCE(sr.per_day_wages, 0) as per_day_wages
            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 COALESCE(sr.hr_id, e.created_by) = u.user_id
            WHERE {$whereClause}
            ORDER BY e.employee_code
        ");
        // Params are already built in correct order above
        $stmt->execute($params);
        $employees = $stmt->fetchAll();
        
        // Auto-create salary_register entries for employees that don't have them yet (only if period exists)
        if ($periodExists && count($employees) > 0) {
            try {
                $db->beginTransaction();
                $insertStmt = $db->prepare("
                    INSERT INTO salary_register 
                    (site_id, hr_id, employee_id, salary_month, employee_type, category)
                    VALUES (?, ?, ?, ?, 'FTC', 'Skilled')
                    ON DUPLICATE KEY UPDATE updated_at = NOW()
                ");
                
                foreach ($employees as $emp) {
                    if ($emp['salary_register_id'] == 0) {
                        // Employee doesn't have salary_register entry, create it
                        $hrId = $emp['hr_id'] ?? $emp['created_by'] ?? null;
                        $insertStmt->execute([
                            $siteId,
                            $hrId,
                            $emp['employee_id'],
                            $selectedMonthFull
                        ]);
                    }
                }
                $db->commit();
            } catch (Exception $e) {
                if ($db->inTransaction()) {
                    $db->rollBack();
                }
                error_log("Error auto-creating salary_register entries: " . $e->getMessage());
                // Continue anyway - employees will still show
            }
        }
    }
}

// Handle save "To" name POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_to_name'])) {
    try {
        $toName = trim($_POST['to_name'] ?? '');
        
        // Create table if not exists
        $db->exec("
            CREATE TABLE IF NOT EXISTS `salary_register_to_names` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `site_id` int(11) NOT NULL,
                `to_name` varchar(255) DEFAULT NULL,
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                UNIQUE KEY `unique_site` (`site_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        // Check if record exists for this site
        $checkStmt = $db->prepare("SELECT id FROM salary_register_to_names WHERE site_id = ?");
        $checkStmt->execute([$siteId]);
        $existing = $checkStmt->fetch();
        
        if ($existing) {
            $updateStmt = $db->prepare("UPDATE salary_register_to_names SET to_name = ? WHERE site_id = ?");
            $updateStmt->execute([$toName, $siteId]);
        } else {
            $insertStmt = $db->prepare("INSERT INTO salary_register_to_names (site_id, to_name) VALUES (?, ?)");
            $insertStmt->execute([$siteId, $toName]);
        }
        
        $successMessage = 'To Name saved successfully!';
        // Redirect to prevent form resubmission
        $redirectUrl = '?';
        if (isset($_GET['m'])) $redirectUrl .= 'm=' . urlencode($_GET['m']) . '&';
        if (isset($_GET['y'])) $redirectUrl .= 'y=' . urlencode($_GET['y']) . '&';
        $redirectUrl .= 'to_saved=1';
        header('Location: ' . $redirectUrl);
        exit;
    } catch (Exception $e) {
        error_log("Error saving salary register To Name: " . $e->getMessage());
        $errorMessage = 'Error saving To Name: ' . $e->getMessage();
    }
}

// Check for to_saved parameter
if (isset($_GET['to_saved']) && $_GET['to_saved'] === '1') {
    $successMessage = 'To Name saved successfully!';
}

// Fetch current To name for this site
$currentToName = '';
try {
    // Create table if not exists
    $db->exec("
        CREATE TABLE IF NOT EXISTS `salary_register_to_names` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `site_id` int(11) NOT NULL,
            `to_name` varchar(255) DEFAULT NULL,
            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
            `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_site` (`site_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    
    $toNameStmt = $db->prepare("SELECT to_name FROM salary_register_to_names WHERE site_id = ?");
    $toNameStmt->execute([$siteId]);
    $toNameRecord = $toNameStmt->fetch();
    $currentToName = $toNameRecord ? $toNameRecord['to_name'] : '';
} catch (Exception $e) {
    error_log("Error fetching salary register To Name: " . $e->getMessage());
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
body {
    font-family: Arial, sans-serif;
    font-size: 11px;
}

.salary-container {
    background: white;
    padding: 10px;
    overflow-x: auto;
}

.period-controls {
    background: #f8f9fa;
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
    border: 1px solid #e0e0e0;
}

.control-group {
    display: contents;
}

.input-wrapper {
    display: flex;
    flex-direction: column;
    gap: 4px;
    min-width: 120px;
}

/* Buttons wrapper for grid alignment */
.buttons-wrapper {
    display: flex;
    gap: 6px;
    align-items: center;
    flex-wrap: wrap;
    margin-left: auto;
}

.input-wrapper label {
    font-weight: 600;
    font-size: 10px;
    color: #555;
    white-space: nowrap;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.input-wrapper select,
.input-wrapper input[type="text"] {
    padding: 6px 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 12px;
    min-width: 100px;
    height: 34px;
    box-sizing: border-box;
}

.input-wrapper select:focus,
.input-wrapper input[type="text"]:focus {
    border-color: #007bff;
    outline: none;
    box-shadow: 0 0 0 2px rgba(0,123,255,0.15);
}

.year-indicator {
    font-size: 9px;
    color: #28a745;
    margin-top: 2px;
}

.controls-right {
    display: flex;
    gap: 10px;
    align-items: flex-start;
}

.btn {
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 11px;
    font-weight: 600;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    height: 34px;
    box-sizing: border-box;
}

/* Smaller buttons used in period controls */
.btn-small {
    padding: 6px 14px;
    font-size: 11px;
    min-width: 60px;
    height: 34px;
}

.btn-primary {
    background: #007bff;
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-success:hover {
    background: #1e7e34;
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
}

.btn-export {
    background: #6f42c1;
    color: white;
}

.btn-export:hover {
    background: #5a32a3;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}

/* To Name Form Styling */
.to-name-form {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    background: #fff;
    padding: 4px 10px;
    border-radius: 4px;
    border: 1px solid #dee2e6;
    height: 34px;
    box-sizing: border-box;
}

.to-name-form label {
    font-size: 10px;
    font-weight: 600;
    color: #495057;
    white-space: nowrap;
}

.to-name-form input {
    padding: 4px 8px;
    border: 1px solid #ced4da;
    border-radius: 3px;
    font-size: 11px;
    width: 100px;
    height: 24px;
    box-sizing: border-box;
}

.to-name-form button {
    padding: 4px 8px;
    font-size: 10px;
    background: #28a745;
    border: none;
    color: white;
    border-radius: 3px;
    cursor: pointer;
    height: 24px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.to-name-form button:hover {
    background: #1e7e34;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.month-header {
    background: white;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #000;
}

.month-header table {
    width: 100%;
    border-collapse: collapse;
}

.month-header td {
    padding: 5px;
    border: 1px solid #000;
}

.month-header .label {
    background: #00008B;
    color: white;
    font-weight: bold;
    width: 150px;
}

.salary-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: auto;
    min-width: 3500px;
}

.salary-table th,
.salary-table td {
    border: 1px solid #000;
    padding: 4px 2px;
    text-align: center;
    font-size: 10px;
}

.salary-table th {
    background: #00008B;
    color: white;
    font-weight: bold;
    padding: 6px 2px;
    position: sticky;
    top: 0;
    z-index: 10;
}

.section-header {
    background: #00008B;
    color: white;
    font-weight: bold;
    text-align: center;
    font-size: 11px;
}

.salary-table input[type="text"],
.salary-table input[type="number"],
.salary-table select {
    width: 100%;
    border: none;
    padding: 2px;
    text-align: center;
    font-size: 10px;
    background: white;
}

.salary-table input[type="number"]:focus,
.salary-table input[type="text"]:focus {
    background: #ffffcc;
    outline: 1px solid #0066cc;
}

.col-slno { width: 30px; }
.col-name { width: 120px; }
.col-designation { width: 100px; }
.col-type { width: 80px; }
.col-category { width: 100px; }
.col-status { width: 70px; }
.col-amount { width: 70px; }
.col-attendance { width: 40px; }
.col-days { width: 50px; }
.col-total { width: 80px; background: #FFA500; font-weight: bold; }

.alert {
    padding: 12px 20px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 10% auto;
    padding: 30px;
    border-radius: 12px;
    width: 500px;
    max-width: 90%;
}

.modal-header {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #555;
}

.form-group select,
.form-group input {
    width: 100%;
    padding: 10px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 25px;
}

.warning-box {
    background: #fff3cd;
    border: 2px solid #ffc107;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
}
</style>

<div class="salary-container">
    <?php include __DIR__ . '/_navigation.php'; ?>
    <?php if (isset($successMessage)): ?>
        <div class="alert alert-success"><?php echo $successMessage; ?></div>
    <?php endif; ?>
    
    <?php if (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
            <?php if (isset($showFixLink) && $showFixLink): ?>
                <br><br>
                <a href="fix_salary_data.php" class="btn btn-primary" style="background: #ff5722;">
                    🔧 Auto-Fix & Setup
                </a>
                <a href="<?php echo BASE_URL; ?>/debug_salary_data.php" class="btn btn-info" style="background: #2196F3; margin-left: 10px;">
                    🔍 Check Database Status
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($tablesExist): ?>
    <input type="hidden" id="selectedMonthFull" value="<?php echo htmlspecialchars($selectedMonthFull); ?>">
    <div class="period-controls">
            <?php if (isSuperAdmin()): ?>
            <div class="input-wrapper">
                <label>View:</label>
                <select id="viewTypeFilter" onchange="updatePeriod()">
                    <option value="all" <?php echo (!isset($_GET['view_type']) || $_GET['view_type'] == 'all') ? 'selected' : ''; ?>>All Employees</option>
                    <option value="hr_employees" <?php echo (isset($_GET['view_type']) && $_GET['view_type'] == 'hr_employees') ? 'selected' : ''; ?>>HR Staff Only</option>
                    <option value="regular_employees" <?php echo (isset($_GET['view_type']) && $_GET['view_type'] == 'regular_employees') ? 'selected' : ''; ?>>Regular Only</option>
                    <option value="by_hr" <?php echo (isset($_GET['view_type']) && $_GET['view_type'] == 'by_hr') ? 'selected' : ''; ?>>By HR Manager</option>
                </select>
            </div>
            
            <div class="input-wrapper" id="hrFilterWrapper" style="<?php echo (isset($_GET['view_type']) && $_GET['view_type'] == 'by_hr') ? '' : 'display:none;'; ?>">
                <label>Select HR Manager:</label>
                <select id="hrFilter" onchange="updatePeriod()">
                    <option value="">Select HR...</option>
                    <?php
                    // Get HR list with employee counts (both uppercase and lowercase role codes)
                    try {
                    $hrStmt = $db->prepare("
                            SELECT u.user_id, u.full_name, COUNT(DISTINCT e.employee_id) as emp_count
                        FROM users u
                        INNER JOIN roles r ON u.role_id = r.role_id
                            LEFT JOIN employees e ON e.created_by = u.user_id AND e.employment_status = 'active' AND e.site_id = ?
                            WHERE (LOWER(r.role_code) = 'hr_admin' OR r.role_code = 'HR_ADMIN') 
                            AND u.user_status = 'active' 
                            AND u.site_id = ?
                        GROUP BY u.user_id, u.full_name
                        ORDER BY u.full_name
                    ");
                        $hrStmt->execute([$siteId, $siteId]);
                    $hrs = $hrStmt->fetchAll();
                        
                        if (count($hrs) == 0) {
                            // If no HRs found with employees, show all HR users
                            $hrStmt = $db->prepare("
                                SELECT u.user_id, u.full_name, 0 as emp_count
                                FROM users u
                                INNER JOIN roles r ON u.role_id = r.role_id
                                WHERE (LOWER(r.role_code) = 'hr_admin' OR r.role_code = 'HR_ADMIN')
                                AND u.user_status = 'active' 
                                AND u.site_id = ?
                                ORDER BY u.full_name
                            ");
                            $hrStmt->execute([$siteId]);
                            $hrs = $hrStmt->fetchAll();
                        }
                        
                    $selectedHR = $_GET['hr'] ?? '';
                    foreach ($hrs as $hr) {
                        $selected = ($selectedHR == $hr['user_id']) ? 'selected' : '';
                            $empText = $hr['emp_count'] > 0 ? " ({$hr['emp_count']} emp)" : "";
                            echo "<option value='{$hr['user_id']}' $selected>{$hr['full_name']}{$empText}</option>";
                        }
                        
                        if (count($hrs) == 0) {
                            echo "<option value='' disabled>No HR users found</option>";
                        }
                    } catch (Exception $e) {
                        error_log("Error fetching HR list: " . $e->getMessage());
                        echo "<option value='' disabled>Error loading HRs</option>";
                    }
                    ?>
                </select>
            </div>
            <?php endif; ?>
            
            <div class="input-wrapper">
                <label>Month:</label>
                <select id="monthSelect" onchange="updatePeriod()">
                    <?php
                    $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    $currentMonth = date('F');
                    foreach ($months as $month) {
                        $selected = (isset($_GET['m']) && strpos($_GET['m'], substr($month, 0, 3)) !== false) || (!isset($_GET['m']) && $month === $currentMonth) ? 'selected' : '';
                        echo "<option value='$month' $selected>$month</option>";
                    }
                    ?>
                </select>
            </div>
            
            <div class="input-wrapper">
                <label>Year:</label>
                <input type="text" id="yearInput" value="<?php echo $selectedYearValue; ?>" 
                       maxlength="4" pattern="\d{2,4}" placeholder="25" style="width: 70px; text-align: center;">
                <div class="year-indicator">
                    <?php
                    $yearDisplay = [];
                    foreach ($years as $y) {
                        if ($y['has_data']) {
                            $yearDisplay[] = substr($y['year'], -2);
                        }
                    }
                    if (count($yearDisplay) > 0) {
                        echo "✓ " . implode(', ', $yearDisplay);
                    }
                    ?>
                </div>
            </div>
            
            <div class="buttons-wrapper">
                <!-- To Name Input Field -->
                <form method="POST" class="to-name-form">
                    <label>To:</label>
                    <input type="text" name="to_name" value="<?php echo htmlspecialchars($currentToName); ?>" placeholder="Recipient">
                    <button type="submit" name="save_to_name" title="Save To Name">✓</button>
                </form>
                
                <button type="button" class="btn btn-primary btn-small" onclick="updatePeriod()">Go →</button>
                <?php if ($periodExists): ?>
                <button type="submit" form="salary-form" class="btn btn-success btn-small">Save</button>
                <button type="button" class="btn btn-info btn-small" onclick="document.getElementById('newPeriodModal').style.display='block'">New</button>
                <button type="button" class="btn btn-export btn-small" onclick="exportSalaryData()">Export</button>
                <?php else: ?>
                <button type="button" class="btn btn-info btn-small" onclick="document.getElementById('newPeriodModal').style.display='block'">New</button>
                <?php endif; ?>
            </div>
    </div>
    
    <div style="text-align: center; margin: 15px 0; padding: 15px; background: #e8f4fd; border-radius: 8px; border: 1px solid #b8daff;">
        <span style="font-size: 15px; font-weight: bold; color: #004085;">
            <?php 
            if ($periodExists && count($employees) > 0) {
                $viewTypeLabel = '';
                if (isSuperAdmin()) {
                    $viewType = $_GET['view_type'] ?? 'all';
                    switch ($viewType) {
                        case 'hr_employees':
                            $viewTypeLabel = ' - HR Staff Only';
                            break;
                        case 'regular_employees':
                            $viewTypeLabel = ' - Regular Employees Only';
                            break;
                        case 'by_hr':
                            if (isset($_GET['hr']) && !empty($_GET['hr'])) {
                                // Find HR name
                                foreach ($hrs as $hr) {
                                    if ($hr['user_id'] == $_GET['hr']) {
                                        $viewTypeLabel = ' - ' . $hr['full_name'] . "'s Employees";
                                        break;
                                    }
                                }
                            } else {
                                $viewTypeLabel = ' - All HRs';
                            }
                            break;
                        default:
                            $viewTypeLabel = ' - All Employees';
                    }
                }
                echo "✓ Period exists: " . htmlspecialchars($selectedMonthFull) . " (" . count($employees) . " employee" . (count($employees) != 1 ? "s" : "") . ")" . $viewTypeLabel;
            } else if ($periodExists && count($employees) == 0) {
                echo "✓ Period exists: " . htmlspecialchars($selectedMonthFull) . " (0 employees)";
            } else {
                echo "⚠️ Period not created for " . htmlspecialchars($selectedMonthFull);
            }
            ?>
        </span>
    </div>
    
    <!-- Month Header -->
    <div class="month-header">
        <table>
            <tr>
                <td class="label">Site Name</td>
                <td><?php echo htmlspecialchars($siteName); ?></td>
            </tr>
            <tr>
                <td class="label">Month</td>
                <td><?php echo htmlspecialchars($selectedMonthFull); ?></td>
            </tr>
        </table>
    </div>
    
    <?php if (!$periodExists): ?>
        <!-- No period at all: show prompt, do NOT show salary table -->
        <div class="warning-box">
            <h3>⚠️ Salary Period Not Created</h3>
            <p>
                Salary data for <strong><?php echo htmlspecialchars($selectedMonthFull); ?></strong> has not been created yet.<br>
                Please create the period to initialize salary data for this month.
            </p>
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'" style="margin-top: 15px;">
                ➕ Create Period
            </button>
        </div>
    <?php elseif ($periodExists && count($employees) == 0): ?>
        <!-- Period exists but no salary rows: show message, no table -->
        <div class="warning-box">
            <h3>⚠️ No Salary Data For This Month</h3>
            <p>
                There is currently no salary data for <strong><?php echo htmlspecialchars($selectedMonthFull); ?></strong>.<br>
                Use <strong>New</strong> to initialize the salary register for this period.
            </p>
        </div>
    <?php else: ?>
    <!-- Period exists and has salary data: show editable table -->
    <form id="salary-form" method="POST">
        <input type="hidden" name="save_salary" value="1">
        <input type="hidden" name="salary_month" value="<?php echo htmlspecialchars($selectedMonthFull); ?>">
        
        <table class="salary-table">
            <thead>
                <tr>
                    <th rowspan="2" class="col-slno">S/L No</th>
                    <th rowspan="2" class="col-name">Employee Name</th>
                    <th rowspan="2" class="col-designation">Designation</th>
                    <?php if (isSuperAdmin()): ?>
                    <th rowspan="2" class="col-designation">Type</th>
                    <th rowspan="2" class="col-designation">HR Manager</th>
                    <?php endif; ?>
                    <th rowspan="2" class="col-type">Employee Type</th>
                    <th rowspan="2" class="col-category">Category</th>
                    <th rowspan="2" class="col-status">Status</th>
                    <th colspan="6" class="section-header">Employer Structure</th>
                    <th colspan="4" class="section-header">Attendence</th>
                    <th colspan="10" class="section-header">Earned Salary</th>
                    <th colspan="11" class="section-header">Rebill</th>
                </tr>
                <tr>
                    <!-- Employer Structure -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">VDA</th>
                    <th class="col-amount">Special<br>Allowance</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-total">Total<br>Earning</th>
                    
                    <!-- Attendance -->
                    <th class="col-attendance">P</th>
                    <th class="col-attendance">A</th>
                    <th class="col-attendance">W/O</th>
                    <th class="col-days">Pay Days</th>
                    
                    <!-- Earned Salary -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">Spl<br>Allowance</th>
                    <th class="col-total">Total<br>Earning</th>
                    <th class="col-amount">PF</th>
                    <th class="col-amount">ESI</th>
                    <th class="col-amount">PT</th>
                    <th class="col-amount">Total<br>Deduction</th>
                    <th class="col-total">Net<br>Salary</th>
                    
                    <!-- Rebill -->
                    <th class="col-amount">Provident<br>Fund (12%)</th>
                    <th class="col-amount">ESIC (3.25%)</th>
                    <th class="col-amount">Leave</th>
                    <th class="col-amount">Holiday</th>
                    <th class="col-amount">Bonus</th>
                    <th class="col-amount">Uniform</th>
                    <th class="col-amount">Gratuity</th>
                    <th class="col-amount">Food<br>Allowance</th>
                    <th class="col-total">Total</th>
                    <th class="col-total">Earned<br>CTC</th>
                    <th class="col-amount">Per day<br>Wages</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $slNo = 1;
                // For valid periods we keep all fields editable
                $readonlyAttr = '';
                $disabledAttr = '';
                foreach ($employees as $emp):
                    $empId = $emp['employee_id'];
                ?>
                <tr>
                    <td><?php echo $slNo++; ?></td>
                    <td style="text-align: left; padding-left: 5px;"><?php echo htmlspecialchars($emp['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($emp['designation_name'] ?? ''); ?></td>
                    <?php if (isSuperAdmin()): ?>
                    <td style="text-align: center; font-size: 10px; font-weight: bold; color: <?php echo ($emp['employee_category'] ?? '') == 'HR Staff' ? '#e91e63' : '#4caf50'; ?>;">
                        <?php echo htmlspecialchars($emp['employee_category'] ?? 'Regular'); ?>
                    </td>
                    <td style="text-align: left; padding-left: 5px; font-size: 9px; color: #666;">
                        <?php echo htmlspecialchars($emp['hr_name'] ?? 'Not Assigned'); ?>
                    </td>
                    <?php endif; ?>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][employee_type]" <?php echo $disabledAttr; ?>>
                            <option value="FTC" <?php echo ($emp['employee_type'] ?? '') === 'FTC' ? 'selected' : ''; ?>>FTC</option>
                            <option value="Regular" <?php echo ($emp['employee_type'] ?? '') === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                        </select>
                    </td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][category]" <?php echo $disabledAttr; ?>>
                            <option value="Highly Skilled" <?php echo ($emp['category'] ?? '') === 'Highly Skilled' ? 'selected' : ''; ?>>Highly Skilled</option>
                            <option value="Skilled" <?php echo ($emp['category'] ?? '') === 'Skilled' ? 'selected' : ''; ?>>Skilled</option>
                            <option value="Semi Skilled" <?php echo ($emp['category'] ?? '') === 'Semi Skilled' ? 'selected' : ''; ?>>Semi Skilled</option>
                            <option value="Unskilled" <?php echo ($emp['category'] ?? '') === 'Unskilled' ? 'selected' : ''; ?>>Unskilled</option>
                        </select>
                    </td>
                    <td><?php echo ucfirst($emp['employment_status']); ?></td>
                    
                    <!-- Employer Structure -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][basic]" value="<?php echo $emp['basic'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][vda]" value="<?php echo $emp['vda'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][special_allowance]" value="<?php echo $emp['special_allowance'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][other_allowance]" value="<?php echo $emp['other_allowance'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][hra]" value="<?php echo $emp['hra'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning]" value="<?php echo $emp['total_earning'] ?? 0; ?>" step="0.01" readonly style="background: #FFA500;"></td>
                    
                    <!-- Attendance -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][present]" value="<?php echo $emp['present'] ?? 0; ?>" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][absent]" value="<?php echo $emp['absent'] ?? 0; ?>" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][weekly_off]" value="<?php echo $emp['weekly_off'] ?? 0; ?>" <?php echo $readonlyAttr; ?>></td>
                    <td style="background: #90EE90;"><input type="number" name="employees[<?php echo $empId; ?>][pay_days]" value="<?php echo $emp['pay_days'] ?? 0; ?>" style="background: #90EE90;" <?php echo $readonlyAttr; ?>></td>
                    
                    <!-- Earned Salary -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_basic]" value="<?php echo $emp['earned_basic'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_hra]" value="<?php echo $emp['earned_hra'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_other_allowance]" value="<?php echo $emp['earned_other_allowance'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][spl_allowance]" value="<?php echo $emp['spl_allowance'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning_earned]" value="<?php echo $emp['total_earning_earned'] ?? 0; ?>" step="0.01" style="background: #87CEEB;" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pf]" value="<?php echo $emp['pf'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esi]" value="<?php echo $emp['esi'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pt]" value="<?php echo $emp['pt'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][total_deduction]" value="<?php echo $emp['total_deduction'] ?? 0; ?>" step="0.01" readonly></td>
                    <td class="col-total" style="background: #4682B4; color: white;"><input type="number" name="employees[<?php echo $empId; ?>][net_salary]" value="<?php echo $emp['net_salary'] ?? 0; ?>" step="0.01" readonly style="background: #4682B4; color: white;"></td>
                    
                    <!-- Rebill -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][provident_fund]" value="<?php echo $emp['provident_fund'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esic]" value="<?php echo $emp['esic'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][leave]" value="<?php echo $emp['leave_amount'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][holiday]" value="<?php echo $emp['holiday'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][bonus]" value="<?php echo $emp['bonus'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][uniform]" value="<?php echo $emp['uniform'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][gratuity]" value="<?php echo $emp['gratuity'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][food_allowance]" value="<?php echo $emp['food_allowance'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_rebill]" value="<?php echo $emp['total_rebill'] ?? 0; ?>" step="0.01" readonly style="background: #4169E1; color: white;"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][earned_ctc]" value="<?php echo $emp['earned_ctc'] ?? 0; ?>" step="0.01" readonly style="background: #00008B; color: white;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][per_day_wages]" value="<?php echo $emp['per_day_wages'] ?? 0; ?>" step="0.01" <?php echo $readonlyAttr; ?>></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </form>
    <?php endif; ?>
    
    <!-- New Period Modal -->
    <div id="newPeriodModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">➕ Create New Salary Period</div>
            <form method="POST">
                <input type="hidden" name="create_new_period" value="1">
                
                <div class="form-group">
                    <label>Month:</label>
                    <select name="new_month" required>
                        <?php
                        $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                        foreach ($months as $month) {
                            echo "<option value='$month'>$month</option>";
                        }
                        ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Year:</label>
                    <input type="text" name="new_year" required placeholder="2025" maxlength="4" pattern="\d{4}">
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="document.getElementById('newPeriodModal').style.display='none'">Cancel</button>
                    <button type="submit" class="btn btn-success">✓ Create Period</button>
                </div>
            </form>
        </div>
    </div>
    
    <?php endif; // End of $tablesExist ?>
</div>

<script>
// Global export function
function exportSalaryData() {
    try {
        let month = '';
        const monthHidden = document.getElementById('selectedMonthFull');
        if (monthHidden && monthHidden.value) {
            month = monthHidden.value.trim();
        }
        if (!month) {
            const monthSelect = document.getElementById('monthSelect');
            const yearInput = document.getElementById('yearInput');
            if (monthSelect && yearInput) {
                let year = yearInput.value.trim();
                if (year.length === 2) year = '20' + year;
                if (year.length === 4) month = monthSelect.value + ' ' + year;
            }
        }
        if (!month) {
            alert('Unable to detect selected salary month. Please ensure a period is selected.');
            return;
        }
        let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('view_type')) url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
        if (urlParams.get('hr')) url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
        window.location.href = url;
    } catch (error) {
        alert('Export error: ' + error.message);
    }
}
function exportCSV() { exportSalaryData(); }

function updatePeriod() {
    const month = document.getElementById('monthSelect').value;
    let year = document.getElementById('yearInput').value.trim();
    
    // Convert 2-digit to 4-digit year
    if (year.length === 2) {
        year = '20' + year;
    } else if (year.length !== 4) {
        alert('Please enter a valid year (e.g., 25 or 2025)');
        return;
    }
    
    const yearShort = year.substr(-2);
    const monthShort = month.substr(0, 3);
    const period = monthShort + '-' + yearShort;
    
    let url = '?m=' + encodeURIComponent(period) + '&y=' + yearShort;
    
    // Add view type filter if present (for Super Admin)
    const viewTypeFilter = document.getElementById('viewTypeFilter');
    if (viewTypeFilter && viewTypeFilter.value) {
        url += '&view_type=' + viewTypeFilter.value;
        
        // Add HR filter if view type is 'by_hr'
        if (viewTypeFilter.value === 'by_hr') {
    const hrFilter = document.getElementById('hrFilter');
    if (hrFilter && hrFilter.value) {
        url += '&hr=' + hrFilter.value;
            }
        }
    }
    
    window.location.href = url;
}

// Show/hide HR filter based on view type
document.addEventListener('DOMContentLoaded', function() {
    const viewTypeFilter = document.getElementById('viewTypeFilter');
    const hrFilterWrapper = document.getElementById('hrFilterWrapper');
    
    if (viewTypeFilter && hrFilterWrapper) {
        // Initial state on page load
        if (viewTypeFilter.value === 'by_hr') {
            hrFilterWrapper.style.display = '';
        } else {
            hrFilterWrapper.style.display = 'none';
        }
        
        // Handle change event
        viewTypeFilter.addEventListener('change', function() {
            if (this.value === 'by_hr') {
                hrFilterWrapper.style.display = '';
                hrFilterWrapper.style.opacity = '1';
                // Focus on HR dropdown for better UX
                setTimeout(function() {
                    document.getElementById('hrFilter').focus();
                }, 100);
            } else {
                hrFilterWrapper.style.display = 'none';
            }
        });
    }
});

// Auto-calculate totals
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('salary-form');
    if (!form) return;
    
    form.addEventListener('input', function(e) {
        const input = e.target;
        if (input.type === 'number') {
            const row = input.closest('tr');
            calculateRowTotals(row);
        }
    });
    
    function calculateRowTotals(row) {
        const inputs = row.querySelectorAll('input[type="number"]');
        const getName = (name) => {
            for (let input of inputs) {
                if (input.name.includes(name)) return input;
            }
            return null;
        };
        
        // Calculate Total Earning
        const basic = parseFloat(getName('basic')?.value || 0);
        const vda = parseFloat(getName('vda')?.value || 0);
        const special = parseFloat(getName('special_allowance')?.value || 0);
        const other = parseFloat(getName('other_allowance')?.value || 0);
        const hra = parseFloat(getName('hra')?.value || 0);
        
        const totalEarning = basic + vda + special + other + hra;
        const totalEarningInput = getName('total_earning');
        if (totalEarningInput) totalEarningInput.value = totalEarning.toFixed(2);
        
        // Calculate Total Deduction
        const pf = parseFloat(getName('pf')?.value || 0);
        const esi = parseFloat(getName('esi')?.value || 0);
        const pt = parseFloat(getName('pt')?.value || 0);
        
        const totalDeduction = pf + esi + pt;
        const totalDeductionInput = getName('total_deduction');
        if (totalDeductionInput) totalDeductionInput.value = totalDeduction.toFixed(2);
        
        // Calculate Total Earning Earned (from earned components)
        const earnedBasic = parseFloat(getName('earned_basic')?.value || 0);
        const earnedHra = parseFloat(getName('earned_hra')?.value || 0);
        const earnedOtherAllowance = parseFloat(getName('earned_other_allowance')?.value || 0);
        const splAllowance = parseFloat(getName('spl_allowance')?.value || 0);
        
        const totalEarningEarned = earnedBasic + earnedHra + earnedOtherAllowance + splAllowance;
        const totalEarningEarnedInput = getName('total_earning_earned');
        if (totalEarningEarnedInput) totalEarningEarnedInput.value = totalEarningEarned.toFixed(2);
        
        // Calculate Net Salary
        const netSalary = totalEarningEarned - totalDeduction;
        const netSalaryInput = getName('net_salary');
        if (netSalaryInput) netSalaryInput.value = netSalary.toFixed(2);
        
        // Calculate Total Rebill
        const providentFund = parseFloat(getName('provident_fund')?.value || 0);
        const esicRebill = parseFloat(getName('esic')?.value || 0);
        const leave = parseFloat(getName('leave')?.value || 0);
        const holiday = parseFloat(getName('holiday')?.value || 0);
        const bonus = parseFloat(getName('bonus')?.value || 0);
        const uniform = parseFloat(getName('uniform')?.value || 0);
        const gratuity = parseFloat(getName('gratuity')?.value || 0);
        const foodAllowance = parseFloat(getName('food_allowance')?.value || 0);
        
        const totalRebill = providentFund + esicRebill + leave + holiday + bonus + uniform + gratuity + foodAllowance;
        const totalRebillInput = getName('total_rebill');
        if (totalRebillInput) totalRebillInput.value = totalRebill.toFixed(2);
        
        // Calculate Earned CTC
        const earnedCtc = totalEarningEarned + pf + esi + esicRebill + providentFund;
        const earnedCtcInput = getName('earned_ctc');
        if (earnedCtcInput) earnedCtcInput.value = earnedCtc.toFixed(2);
    }
    
    // Initial calculation
    document.querySelectorAll('.salary-table tbody tr').forEach(row => {
        calculateRowTotals(row);
    });
});

// CSV export is now handled by separate PHP file

// Close modal on outside click
window.onclick = function(event) {
    const modal = document.getElementById('newPeriodModal');
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; return; ?>

<?php
/**
 * Salary Register - Period-based System
 * Like Attendance module with month/year selection
 */

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

$pageTitle = "Salary Register";
$currentTab = 'salary_register';
$siteId = getCurrentSiteId();
$db = getDB();
$siteName = $_SESSION['site_name'] ?? 'Base Office';
$userId = $_SESSION['user_id'] ?? 1;

// Check if tables exist
$tablesExist = false;
try {
    $checkTables = $db->query("
        SELECT COUNT(*) as cnt FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name IN ('salary_register', 'salary_periods')
    ");
    $result = $checkTables->fetch();
    $tablesExist = ($result['cnt'] == 2);
} catch (Exception $e) {
    $tablesExist = false;
}

if (!$tablesExist) {
    // Show migration warning
    $errorMessage = "⚠️ Required tables not found! Please run migrations first.";
    $employees = [];
    $periodExists = false;
} else {
    // Handle New Period Creation
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_new_period'])) {
        try {
            $newMonth = $_POST['new_month'];
            $newYear = intval($_POST['new_year']);
            
            // Convert to proper format
            $monthAbbr = date('M', strtotime($newMonth . ' 1'));
            $yearAbbr = substr($newYear, -2);
            $salaryMonth = $monthAbbr . '-' . $yearAbbr; // e.g., "Jan-26"
            $periodDisplay = $newMonth . ' ' . $newYear; // e.g., "January 2026"
            
            // Check if period already exists
            $checkStmt = $db->prepare("
                SELECT period_id FROM salary_periods 
                WHERE site_id = ? AND salary_month = ?
            ");
            $checkStmt->execute([$siteId, $salaryMonth]);
            
            if ($checkStmt->fetch()) {
                $errorMessage = "Period {$periodDisplay} already exists!";
            } else {
                $db->beginTransaction();
                
                // Get active employees count
                $countStmt = $db->prepare("
                    SELECT COUNT(*) as cnt FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $countStmt->execute([$siteId]);
                $empCount = $countStmt->fetch()['cnt'];
                
                // Create period
                $periodStmt = $db->prepare("
                    INSERT INTO salary_periods 
                    (site_id, salary_month, period_display, employee_count, created_by)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $periodStmt->execute([$siteId, $salaryMonth, $periodDisplay, $empCount, $userId]);
                
                // Initialize salary_register entries for all active employees
                $empStmt = $db->prepare("
                    SELECT employee_id FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $empStmt->execute([$siteId]);
                $employees = $empStmt->fetchAll();
                
                $insertStmt = $db->prepare("
                    INSERT INTO salary_register 
                    (site_id, employee_id, salary_month, employee_type, category)
                    VALUES (?, ?, ?, 'FTC', 'Skilled')
                ");
                
                foreach ($employees as $emp) {
                    $insertStmt->execute([$siteId, $emp['employee_id'], $periodDisplay]);
                }
                
                $db->commit();
                $successMessage = "New salary period created: {$periodDisplay}";
                
                // Redirect to new period
                header("Location: ?m=" . urlencode($salaryMonth) . "&y=" . $yearAbbr);
                exit;
            }
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $errorMessage = "Error creating period: " . $e->getMessage();
        }
    }

    // Handle Save Salary Data
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_salary'])) {
        try {
            $db->beginTransaction();
            
            foreach ($_POST['employees'] as $empId => $data) {
                $employee_type = $data['employee_type'] ?? 'FTC';
                $category = $data['category'] ?? 'Skilled';
                
                $basic = floatval($data['basic'] ?? 0);
                $vda = floatval($data['vda'] ?? 0);
                $special_allowance = floatval($data['special_allowance'] ?? 0);
                $other_allowance = floatval($data['other_allowance'] ?? 0);
                $hra = floatval($data['hra'] ?? 0);
                $total_earning = $basic + $vda + $special_allowance + $other_allowance + $hra;
                
                $present = intval($data['present'] ?? 0);
                $absent = intval($data['absent'] ?? 0);
                $weekly_off = intval($data['weekly_off'] ?? 0);
                $pay_days = intval($data['pay_days'] ?? 0);
                
                $earned_basic = floatval($data['earned_basic'] ?? 0);
                $earned_hra = floatval($data['earned_hra'] ?? 0);
                $earned_other_allowance = floatval($data['earned_other_allowance'] ?? 0);
                $spl_allowance = floatval($data['spl_allowance'] ?? 0);
                $total_earning_earned = floatval($data['total_earning_earned'] ?? 0);
                
                $pf = floatval($data['pf'] ?? 0);
                $esi = floatval($data['esi'] ?? 0);
                $pt = floatval($data['pt'] ?? 0);
                $total_deduction = $pf + $esi + $pt;
                $net_salary = $total_earning_earned - $total_deduction;
                
                $provident_fund = floatval($data['provident_fund'] ?? 0);
                $esic = floatval($data['esic'] ?? 0);
                $leave_amount = floatval($data['leave'] ?? 0);
                $holiday = floatval($data['holiday'] ?? 0);
                $bonus = floatval($data['bonus'] ?? 0);
                $uniform = floatval($data['uniform'] ?? 0);
                $gratuity = floatval($data['gratuity'] ?? 0);
                $food_allowance = floatval($data['food_allowance'] ?? 0);
                $total_rebill = $provident_fund + $esic + $leave_amount + $holiday + $bonus + $uniform + $gratuity + $food_allowance;
                
                $earned_ctc = $total_earning_earned + $pf + $esi + $esic + $provident_fund;
                $per_day_wages = floatval($data['per_day_wages'] ?? 0);
                
                $selectedMonthFull = $_GET['month'] ?? date('F Y');
                
                $stmt = $db->prepare("
                    UPDATE salary_register SET
                        employee_type = ?, category = ?,
                        basic = ?, vda = ?, special_allowance = ?, other_allowance = ?, hra = ?, total_earning = ?,
                        present = ?, absent = ?, weekly_off = ?, pay_days = ?,
                        earned_basic = ?, earned_hra = ?, earned_other_allowance = ?, spl_allowance = ?, total_earning_earned = ?,
                        pf = ?, esi = ?, pt = ?, total_deduction = ?, net_salary = ?,
                        provident_fund = ?, esic = ?, leave_amount = ?, holiday = ?, bonus = ?, uniform = ?, gratuity = ?, food_allowance = ?,
                        total_rebill = ?, earned_ctc = ?, per_day_wages = ?,
                        updated_at = NOW()
                    WHERE employee_id = ? AND salary_month = ? AND site_id = ?
                ");
                $stmt->execute([
                    $employee_type, $category,
                    $basic, $vda, $special_allowance, $other_allowance, $hra, $total_earning,
                    $present, $absent, $weekly_off, $pay_days,
                    $earned_basic, $earned_hra, $earned_other_allowance, $spl_allowance, $total_earning_earned,
                    $pf, $esi, $pt, $total_deduction, $net_salary,
                    $provident_fund, $esic, $leave_amount, $holiday, $bonus, $uniform, $gratuity, $food_allowance,
                    $total_rebill, $earned_ctc, $per_day_wages,
                    $empId, $selectedMonthFull, $siteId
                ]);
            }
            
            $db->commit();
            $m = $_GET['m'] ?? '';
            $y = $_GET['y'] ?? '';
            header("Location: ?m=" . urlencode($m) . "&y=" . urlencode($y) . "&saved=1");
            exit;
        } catch (Exception $e) {
            $db->rollBack();
            $errorMessage = "Error saving: " . $e->getMessage();
        }
    }

    if (isset($_GET['saved'])) {
        $successMessage = "Salary data saved successfully!";
    }

    // Get available periods and years
    $availablePeriodsStmt = $db->prepare("
        SELECT DISTINCT salary_month, period_display 
        FROM salary_periods 
        WHERE site_id = ?
        ORDER BY created_at DESC
    ");
    $availablePeriodsStmt->execute([$siteId]);
    $availablePeriods = $availablePeriodsStmt->fetchAll();

    // Get years with data
    $yearsStmt = $db->prepare("
        SELECT DISTINCT SUBSTRING(salary_month, 5, 2) as year_short
        FROM salary_periods
        WHERE site_id = ?
        ORDER BY salary_month DESC
    ");
    $yearsStmt->execute([$siteId]);
    $yearsData = $yearsStmt->fetchAll();

    $years = [];
    $currentYear = date('Y');
    $baseYears = range(2025, $currentYear + 5);
    foreach ($baseYears as $yr) {
        $yearShort = substr($yr, -2);
        $hasData = false;
        foreach ($yearsData as $yd) {
            if ($yd['year_short'] == $yearShort) {
                $hasData = true;
                break;
            }
        }
        $years[] = ['year' => $yr, 'has_data' => $hasData];
    }

    // Handle month/year selection
    $selectedMonthName = isset($_GET['m']) ? $_GET['m'] : (count($availablePeriods) > 0 ? $availablePeriods[0]['salary_month'] : date('M-y'));
    $selectedYearValue = isset($_GET['y']) ? $_GET['y'] : substr(date('y'), -2);
    
    // Convert short month to full
    if (preg_match('/^([A-Za-z]{3})-(\d{2})$/', $selectedMonthName, $matches)) {
        $monthName = $matches[1];
        $yearShort = $matches[2];
        $monthFull = date('F', strtotime($monthName . ' 1'));
        $yearFull = '20' . $yearShort;
        $selectedMonthFull = $monthFull . ' ' . $yearFull;
    } else {
        $selectedMonthFull = $selectedMonthName;
    }

    // Check if period exists
    $periodCheckStmt = $db->prepare("
        SELECT period_id FROM salary_periods 
        WHERE site_id = ? AND salary_month = ?
    ");
    $periodCheckStmt->execute([$siteId, $selectedMonthName]);
    $periodExists = $periodCheckStmt->rowCount() > 0;

    // Get employees data
    $employees = [];
    if ($periodExists) {
        $stmt = $db->prepare("
            SELECT 
                e.employee_id,
                e.employee_code,
                CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                d.designation_name,
                e.employment_status,
                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 = ?
            WHERE e.site_id = ? AND e.employment_status = 'active' AND sr.salary_register_id IS NOT NULL
            ORDER BY e.employee_code
        ");
        $stmt->execute([$selectedMonthFull, $siteId]);
        $employees = $stmt->fetchAll();
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
body {
    font-family: Arial, sans-serif;
    font-size: 11px;
}

.salary-container {
    background: white;
    padding: 10px;
    overflow-x: auto;
}

.period-controls {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    flex-wrap: wrap;
}

.control-group {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    min-height: 70px;
}

.input-wrapper {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.input-wrapper label {
    font-weight: bold;
    font-size: 12px;
    color: #333;
}

.input-wrapper select,
.input-wrapper input[type="text"] {
    padding: 8px 12px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 13px;
    min-width: 150px;
}

.year-indicator {
    font-size: 11px;
    color: #28a745;
    margin-top: 3px;
}

.controls-right {
    display: flex;
    gap: 10px;
    align-items: flex-start;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
}

.btn-success {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
}

.btn-info {
    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
    color: white;
}

.month-header {
    background: white;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #000;
}

.month-header table {
    width: 100%;
    border-collapse: collapse;
}

.month-header td {
    padding: 5px;
    border: 1px solid #000;
}

.month-header .label {
    background: #00008B;
    color: white;
    font-weight: bold;
    width: 150px;
}

.salary-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: auto;
    min-width: 3500px;
}

.salary-table th,
.salary-table td {
    border: 1px solid #000;
    padding: 4px 2px;
    text-align: center;
    font-size: 10px;
}

.salary-table th {
    background: #00008B;
    color: white;
    font-weight: bold;
    padding: 6px 2px;
    position: sticky;
    top: 0;
    z-index: 10;
}

.section-header {
    background: #00008B;
    color: white;
    font-weight: bold;
    text-align: center;
    font-size: 11px;
}

.salary-table input[type="text"],
.salary-table input[type="number"],
.salary-table select {
    width: 100%;
    border: none;
    padding: 2px;
    text-align: center;
    font-size: 10px;
    background: white;
}

.salary-table input[type="number"]:focus,
.salary-table input[type="text"]:focus {
    background: #ffffcc;
    outline: 1px solid #0066cc;
}

.col-slno { width: 30px; }
.col-name { width: 120px; }
.col-designation { width: 100px; }
.col-type { width: 80px; }
.col-category { width: 100px; }
.col-status { width: 70px; }
.col-amount { width: 70px; }
.col-attendance { width: 40px; }
.col-days { width: 50px; }
.col-total { width: 80px; background: #FFA500; font-weight: bold; }

.alert {
    padding: 12px 20px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 10% auto;
    padding: 30px;
    border-radius: 12px;
    width: 500px;
    max-width: 90%;
}

.modal-header {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #555;
}

.form-group select,
.form-group input {
    width: 100%;
    padding: 10px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 25px;
}

.warning-box {
    background: #fff3cd;
    border: 2px solid #ffc107;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
}
</style>

<div class="salary-container">
    <?php include __DIR__ . '/_navigation.php'; ?>
    
    <h1 style="margin: 20px 0;">💰 Salary Register</h1>
    
    <?php if (isset($successMessage)): ?>
        <div class="alert alert-success"><?php echo $successMessage; ?></div>
    <?php endif; ?>
    
    <?php if (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
            <?php if (!$tablesExist): ?>
                <br><br>
                <a href="<?php echo BASE_URL; ?>/database/create_salary_table_direct.php" class="btn btn-primary">
                    🚀 Run Migration Now
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($tablesExist): ?>
    <div class="period-controls">
        <div class="control-group">
            <div class="input-wrapper">
                <label>Select Month:</label>
                <select id="monthSelect" onchange="updatePeriod()">
                    <?php
                    $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    $currentMonth = date('F');
                    foreach ($months as $month) {
                        $selected = (isset($_GET['m']) && strpos($_GET['m'], substr($month, 0, 3)) !== false) || (!isset($_GET['m']) && $month === $currentMonth) ? 'selected' : '';
                        echo "<option value='$month' $selected>$month</option>";
                    }
                    ?>
                </select>
            </div>
            
            <div class="input-wrapper">
                <label>Enter Year:</label>
                <input type="text" id="yearInput" value="<?php echo $selectedYearValue; ?>" 
                       maxlength="4" pattern="\d{2,4}" placeholder="25 or 2025">
                <div class="year-indicator">
                    <?php
                    $yearDisplay = [];
                    foreach ($years as $y) {
                        if ($y['has_data']) {
                            $yearDisplay[] = substr($y['year'], -2);
                        }
                    }
                    if (count($yearDisplay) > 0) {
                        echo "✓ Years with data: " . implode(', ', $yearDisplay);
                    }
                    ?>
                </div>
            </div>
            
            <div class="input-wrapper">
                <label>&nbsp;</label>
                <button type="button" class="btn btn-primary" onclick="updatePeriod()" style="height: 40px;">
                    Go →
                </button>
            </div>
        </div>
        
        <div class="controls-right">
            <?php if ($periodExists): ?>
            <button type="submit" form="salary-form" class="btn btn-success">
                ✓ Save Salary Data
            </button>
            <?php endif; ?>
            
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'">
                ➕ New Salary Period
            </button>
            
            <button type="button" class="btn btn-primary" onclick="exportSalaryData()">
                📥 Export CSV
            </button>
        </div>
    </div>
    
    <div style="text-align: center; margin: 15px 0; padding: 10px; background: #e8f4fd; border-radius: 6px;">
        <span style="font-size: 14px; font-weight: bold; color: #333;">
            <?php 
            if ($periodExists) {
                echo "✓ Period exists: " . htmlspecialchars($selectedMonthFull) . " (" . count($employees) . " employees)";
            } else {
                echo "⚠️ Period not created for " . htmlspecialchars($selectedMonthFull);
            }
            ?>
        </span>
    </div>
    
    <?php if ($periodExists && count($employees) > 0): ?>
    <!-- Month Header -->
    <div class="month-header">
        <table>
            <tr>
                <td class="label">Site Name</td>
                <td><?php echo htmlspecialchars($siteName); ?></td>
            </tr>
            <tr>
                <td class="label">Month</td>
                <td><?php echo htmlspecialchars($selectedMonthFull); ?></td>
            </tr>
        </table>
    </div>
    
    <form id="salary-form" method="POST">
        <input type="hidden" name="save_salary" value="1">
        <input type="hidden" name="month" value="<?php echo htmlspecialchars($selectedMonthFull); ?>">
        
        <table class="salary-table">
            <thead>
                <tr>
                    <th rowspan="2" class="col-slno">S/L No</th>
                    <th rowspan="2" class="col-name">Employee Name</th>
                    <th rowspan="2" class="col-designation">Designation</th>
                    <th rowspan="2" class="col-type">Employee Type</th>
                    <th rowspan="2" class="col-category">Category</th>
                    <th rowspan="2" class="col-status">Status</th>
                    <th colspan="6" class="section-header">Employer Structure</th>
                    <th colspan="4" class="section-header">Attendence</th>
                    <th colspan="10" class="section-header">Earned Salary</th>
                    <th colspan="11" class="section-header">Rebill</th>
                </tr>
                <tr>
                    <!-- Employer Structure -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">VDA</th>
                    <th class="col-amount">Special<br>Allowance</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-total">Total<br>Earning</th>
                    
                    <!-- Attendance -->
                    <th class="col-attendance">P</th>
                    <th class="col-attendance">A</th>
                    <th class="col-attendance">W/O</th>
                    <th class="col-days">Pay Days</th>
                    
                    <!-- Earned Salary -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">Spl<br>Allowance</th>
                    <th class="col-total">Total<br>Earning</th>
                    <th class="col-amount">PF</th>
                    <th class="col-amount">ESI</th>
                    <th class="col-amount">PT</th>
                    <th class="col-amount">Total<br>Deduction</th>
                    <th class="col-total">Net<br>Salary</th>
                    
                    <!-- Rebill -->
                    <th class="col-amount">Provident<br>Fund (12%)</th>
                    <th class="col-amount">ESIC (3.25%)</th>
                    <th class="col-amount">Leave</th>
                    <th class="col-amount">Holiday</th>
                    <th class="col-amount">Bonus</th>
                    <th class="col-amount">Uniform</th>
                    <th class="col-amount">Gratuity</th>
                    <th class="col-amount">Food<br>Allowance</th>
                    <th class="col-total">Total</th>
                    <th class="col-total">Earned<br>CTC</th>
                    <th class="col-amount">Per day<br>Wages</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $slNo = 1;
                foreach ($employees as $emp):
                    $empId = $emp['employee_id'];
                ?>
                <tr>
                    <td><?php echo $slNo++; ?></td>
                    <td style="text-align: left; padding-left: 5px;"><?php echo htmlspecialchars($emp['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($emp['designation_name'] ?? ''); ?></td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][employee_type]">
                            <option value="FTC" <?php echo ($emp['employee_type'] ?? '') === 'FTC' ? 'selected' : ''; ?>>FTC</option>
                            <option value="Regular" <?php echo ($emp['employee_type'] ?? '') === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                        </select>
                    </td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][category]">
                            <option value="Highly Skilled" <?php echo ($emp['category'] ?? '') === 'Highly Skilled' ? 'selected' : ''; ?>>Highly Skilled</option>
                            <option value="Skilled" <?php echo ($emp['category'] ?? '') === 'Skilled' ? 'selected' : ''; ?>>Skilled</option>
                            <option value="Semi Skilled" <?php echo ($emp['category'] ?? '') === 'Semi Skilled' ? 'selected' : ''; ?>>Semi Skilled</option>
                            <option value="Unskilled" <?php echo ($emp['category'] ?? '') === 'Unskilled' ? 'selected' : ''; ?>>Unskilled</option>
                        </select>
                    </td>
                    <td><?php echo ucfirst($emp['employment_status']); ?></td>
                    
                    <!-- Employer Structure -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][basic]" value="<?php echo $emp['basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][vda]" value="<?php echo $emp['vda'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][special_allowance]" value="<?php echo $emp['special_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][other_allowance]" value="<?php echo $emp['other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][hra]" value="<?php echo $emp['hra'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning]" value="<?php echo $emp['total_earning'] ?? 0; ?>" step="0.01" readonly style="background: #FFA500;"></td>
                    
                    <!-- Attendance -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][present]" value="<?php echo $emp['present'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][absent]" value="<?php echo $emp['absent'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][weekly_off]" value="<?php echo $emp['weekly_off'] ?? 0; ?>"></td>
                    <td style="background: #90EE90;"><input type="number" name="employees[<?php echo $empId; ?>][pay_days]" value="<?php echo $emp['pay_days'] ?? 0; ?>" style="background: #90EE90;"></td>
                    
                    <!-- Earned Salary -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_basic]" value="<?php echo $emp['earned_basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_hra]" value="<?php echo $emp['earned_hra'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_other_allowance]" value="<?php echo $emp['earned_other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][spl_allowance]" value="<?php echo $emp['spl_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning_earned]" value="<?php echo $emp['total_earning_earned'] ?? 0; ?>" step="0.01" style="background: #87CEEB;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pf]" value="<?php echo $emp['pf'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esi]" value="<?php echo $emp['esi'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pt]" value="<?php echo $emp['pt'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][total_deduction]" value="<?php echo $emp['total_deduction'] ?? 0; ?>" step="0.01" readonly></td>
                    <td class="col-total" style="background: #4682B4; color: white;"><input type="number" name="employees[<?php echo $empId; ?>][net_salary]" value="<?php echo $emp['net_salary'] ?? 0; ?>" step="0.01" readonly style="background: #4682B4; color: white;"></td>
                    
                    <!-- Rebill -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][provident_fund]" value="<?php echo $emp['provident_fund'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esic]" value="<?php echo $emp['esic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][leave]" value="<?php echo $emp['leave_amount'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][holiday]" value="<?php echo $emp['holiday'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][bonus]" value="<?php echo $emp['bonus'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][uniform]" value="<?php echo $emp['uniform'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][gratuity]" value="<?php echo $emp['gratuity'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][food_allowance]" value="<?php echo $emp['food_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_rebill]" value="<?php echo $emp['total_rebill'] ?? 0; ?>" step="0.01" readonly style="background: #4169E1; color: white;"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][earned_ctc]" value="<?php echo $emp['earned_ctc'] ?? 0; ?>" step="0.01" readonly style="background: #00008B; color: white;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][per_day_wages]" value="<?php echo $emp['per_day_wages'] ?? 0; ?>" step="0.01"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </form>
    
    <?php elseif ($periodExists && count($employees) == 0): ?>
        <div class="warning-box">
            <h3>⚠️ No Employees Found</h3>
            <p>There are no active employees for this period.</p>
        </div>
    <?php else: ?>
        <div class="warning-box">
            <h3>⚠️ Period Not Created</h3>
            <p>Please create a salary period for <strong><?php echo htmlspecialchars($selectedMonthFull); ?></strong> first.</p>
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'" style="margin-top: 15px;">
                ➕ Create New Period
            </button>
        </div>
    <?php endif; ?>
    
    <!-- New Period Modal -->
    <div id="newPeriodModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">➕ Create New Salary Period</div>
            <form method="POST">
                <input type="hidden" name="create_new_period" value="1">
                
                <div class="form-group">
                    <label>Month:</label>
                    <select name="new_month" required>
                        <?php
                        $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                        foreach ($months as $month) {
                            echo "<option value='$month'>$month</option>";
                        }
                        ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Year:</label>
                    <input type="text" name="new_year" required placeholder="2025" maxlength="4" pattern="\d{4}">
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="document.getElementById('newPeriodModal').style.display='none'">Cancel</button>
                    <button type="submit" class="btn btn-success">✓ Create Period</button>
                </div>
            </form>
        </div>
    </div>
    
    <?php endif; // End of $tablesExist ?>
</div>

<script>
// Global export function
function exportSalaryData() {
    try {
        let month = '';
        const monthHidden = document.getElementById('selectedMonthFull');
        if (monthHidden && monthHidden.value) {
            month = monthHidden.value.trim();
        }
        if (!month) {
            const monthSelect = document.getElementById('monthSelect');
            const yearInput = document.getElementById('yearInput');
            if (monthSelect && yearInput) {
                let year = yearInput.value.trim();
                if (year.length === 2) year = '20' + year;
                if (year.length === 4) month = monthSelect.value + ' ' + year;
            }
        }
        if (!month) {
            alert('Unable to detect selected salary month. Please ensure a period is selected.');
            return;
        }
        let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('view_type')) url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
        if (urlParams.get('hr')) url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
        window.location.href = url;
    } catch (error) {
        alert('Export error: ' + error.message);
    }
}
function exportCSV() { exportSalaryData(); }

function updatePeriod() {
    const month = document.getElementById('monthSelect').value;
    let year = document.getElementById('yearInput').value.trim();
    
    // Convert 2-digit to 4-digit year
    if (year.length === 2) {
        year = '20' + year;
    } else if (year.length !== 4) {
        alert('Please enter a valid year (e.g., 25 or 2025)');
        return;
    }
    
    const yearShort = year.substr(-2);
    const monthShort = month.substr(0, 3);
    const period = monthShort + '-' + yearShort;
    
    window.location.href = '?m=' + encodeURIComponent(period) + '&y=' + yearShort;
}

// Auto-calculate totals
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('salary-form');
    if (!form) return;
    
    form.addEventListener('input', function(e) {
        const input = e.target;
        if (input.type === 'number') {
            const row = input.closest('tr');
            calculateRowTotals(row);
        }
    });
    
    function calculateRowTotals(row) {
        const inputs = row.querySelectorAll('input[type="number"]');
        const getName = (name) => {
            for (let input of inputs) {
                if (input.name.includes(name)) return input;
            }
            return null;
        };
        
        // Calculate Total Earning
        const basic = parseFloat(getName('basic')?.value || 0);
        const vda = parseFloat(getName('vda')?.value || 0);
        const special = parseFloat(getName('special_allowance')?.value || 0);
        const other = parseFloat(getName('other_allowance')?.value || 0);
        const hra = parseFloat(getName('hra')?.value || 0);
        
        const totalEarning = basic + vda + special + other + hra;
        const totalEarningInput = getName('total_earning');
        if (totalEarningInput) totalEarningInput.value = totalEarning.toFixed(2);
        
        // Calculate Total Deduction
        const pf = parseFloat(getName('pf')?.value || 0);
        const esi = parseFloat(getName('esi')?.value || 0);
        const pt = parseFloat(getName('pt')?.value || 0);
        
        const totalDeduction = pf + esi + pt;
        const totalDeductionInput = getName('total_deduction');
        if (totalDeductionInput) totalDeductionInput.value = totalDeduction.toFixed(2);
        
        // Calculate Net Salary
        const totalEarningEarned = parseFloat(getName('total_earning_earned')?.value || 0);
        const netSalary = totalEarningEarned - totalDeduction;
        const netSalaryInput = getName('net_salary');
        if (netSalaryInput) netSalaryInput.value = netSalary.toFixed(2);
        
        // Calculate Total Rebill
        const providentFund = parseFloat(getName('provident_fund')?.value || 0);
        const esicRebill = parseFloat(getName('esic')?.value || 0);
        const leave = parseFloat(getName('leave')?.value || 0);
        const holiday = parseFloat(getName('holiday')?.value || 0);
        const bonus = parseFloat(getName('bonus')?.value || 0);
        const uniform = parseFloat(getName('uniform')?.value || 0);
        const gratuity = parseFloat(getName('gratuity')?.value || 0);
        const foodAllowance = parseFloat(getName('food_allowance')?.value || 0);
        
        const totalRebill = providentFund + esicRebill + leave + holiday + bonus + uniform + gratuity + foodAllowance;
        const totalRebillInput = getName('total_rebill');
        if (totalRebillInput) totalRebillInput.value = totalRebill.toFixed(2);
        
        // Calculate Earned CTC
        const earnedCtc = totalEarningEarned + pf + esi + esicRebill + providentFund;
        const earnedCtcInput = getName('earned_ctc');
        if (earnedCtcInput) earnedCtcInput.value = earnedCtc.toFixed(2);
    }
    
    // Initial calculation
    document.querySelectorAll('.salary-table tbody tr').forEach(row => {
        calculateRowTotals(row);
    });
});

function exportCSV() {
    // Get month from hidden input (most reliable)
    let month = '';
    const monthHidden = document.getElementById('selectedMonthFull');
    if (monthHidden && monthHidden.value) {
        month = monthHidden.value.trim();
    }
    
    // Fallback 1: Try month header
    if (!month) {
        const monthLabelCell = document.querySelector('.month-header td:last-child');
        if (monthLabelCell) {
            month = monthLabelCell.textContent.trim();
        }
    }
    
    // Fallback 2: Try period status message
    if (!month) {
        const periodStatus = document.querySelector('.period-meta span, [style*="background: #e8f4fd"] span');
        if (periodStatus) {
            const text = periodStatus.textContent || '';
            const match = text.match(/(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}/);
            if (match) {
                month = match[0];
            }
        }
    }
    
    // Fallback 3: Try month + year controls
    if (!month) {
        const monthSelect = document.getElementById('monthSelect');
        const yearInput = document.getElementById('yearInput');
        if (monthSelect && yearInput) {
            let year = yearInput.value.trim();
            // Convert 2-digit to 4-digit year
            if (year.length === 2) {
                year = '20' + year;
            } else if (year.length !== 4) {
                alert('Invalid year format. Please enter a valid year.');
                return;
            }
            month = monthSelect.value + ' ' + year;
        }
    }
    
    if (!month) {
        alert('Unable to detect selected salary month to export. Please ensure a period is selected.');
        return;
    }
    
    // Build export URL
    let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
    
    // Pass view filters if present
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('view_type')) {
        url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
    }
    if (urlParams.get('hr')) {
        url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
    }
    
    // Navigate to export URL
    window.location.href = url;
}

// Close modal on outside click
window.onclick = function(event) {
    const modal = document.getElementById('newPeriodModal');
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

<?php
/**
 * Salary Register - Period-based System
 * Like Attendance module with month/year selection
 */

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

$pageTitle = "Salary Register";
$currentTab = 'salary_register';
$siteId = getCurrentSiteId();
$db = getDB();
$siteName = $_SESSION['site_name'] ?? 'Base Office';
$userId = $_SESSION['user_id'] ?? 1;

// Check if tables exist
$tablesExist = false;
try {
    $checkTables = $db->query("
        SELECT COUNT(*) as cnt FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name IN ('salary_register', 'salary_periods')
    ");
    $result = $checkTables->fetch();
    $tablesExist = ($result['cnt'] == 2);
} catch (Exception $e) {
    $tablesExist = false;
}

if (!$tablesExist) {
    // Show migration warning
    $errorMessage = "⚠️ Required tables not found! Please run migrations first.";
    $employees = [];
    $periodExists = false;
} else {
    // Handle New Period Creation
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_new_period'])) {
        try {
            $newMonth = $_POST['new_month'];
            $newYear = intval($_POST['new_year']);
            
            // Convert to proper format
            $monthAbbr = date('M', strtotime($newMonth . ' 1'));
            $yearAbbr = substr($newYear, -2);
            $salaryMonth = $monthAbbr . '-' . $yearAbbr; // e.g., "Jan-26"
            $periodDisplay = $newMonth . ' ' . $newYear; // e.g., "January 2026"
            
            // Check if period already exists
            $checkStmt = $db->prepare("
                SELECT period_id FROM salary_periods 
                WHERE site_id = ? AND salary_month = ?
            ");
            $checkStmt->execute([$siteId, $salaryMonth]);
            
            if ($checkStmt->fetch()) {
                $errorMessage = "Period {$periodDisplay} already exists!";
            } else {
                $db->beginTransaction();
                
                // Get active employees count
                $countStmt = $db->prepare("
                    SELECT COUNT(*) as cnt FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $countStmt->execute([$siteId]);
                $empCount = $countStmt->fetch()['cnt'];
                
                // Create period
                $periodStmt = $db->prepare("
                    INSERT INTO salary_periods 
                    (site_id, salary_month, period_display, employee_count, created_by)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $periodStmt->execute([$siteId, $salaryMonth, $periodDisplay, $empCount, $userId]);
                
                // Initialize salary_register entries for all active employees
                $empStmt = $db->prepare("
                    SELECT employee_id FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $empStmt->execute([$siteId]);
                $employees = $empStmt->fetchAll();
                
                $insertStmt = $db->prepare("
                    INSERT INTO salary_register 
                    (site_id, employee_id, salary_month, employee_type, category)
                    VALUES (?, ?, ?, 'FTC', 'Skilled')
                ");
                
                foreach ($employees as $emp) {
                    $insertStmt->execute([$siteId, $emp['employee_id'], $periodDisplay]);
                }
                
                $db->commit();
                $successMessage = "New salary period created: {$periodDisplay}";
                
                // Redirect to new period
                header("Location: ?m=" . urlencode($salaryMonth) . "&y=" . $yearAbbr);
                exit;
            }
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $errorMessage = "Error creating period: " . $e->getMessage();
        }
    }

    // Handle Save Salary Data
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_salary'])) {
        try {
            $db->beginTransaction();
            
            foreach ($_POST['employees'] as $empId => $data) {
                $employee_type = $data['employee_type'] ?? 'FTC';
                $category = $data['category'] ?? 'Skilled';
                
                $basic = floatval($data['basic'] ?? 0);
                $vda = floatval($data['vda'] ?? 0);
                $special_allowance = floatval($data['special_allowance'] ?? 0);
                $other_allowance = floatval($data['other_allowance'] ?? 0);
                $hra = floatval($data['hra'] ?? 0);
                $total_earning = $basic + $vda + $special_allowance + $other_allowance + $hra;
                
                $present = intval($data['present'] ?? 0);
                $absent = intval($data['absent'] ?? 0);
                $weekly_off = intval($data['weekly_off'] ?? 0);
                $pay_days = intval($data['pay_days'] ?? 0);
                
                $earned_basic = floatval($data['earned_basic'] ?? 0);
                $earned_hra = floatval($data['earned_hra'] ?? 0);
                $earned_other_allowance = floatval($data['earned_other_allowance'] ?? 0);
                $spl_allowance = floatval($data['spl_allowance'] ?? 0);
                $total_earning_earned = floatval($data['total_earning_earned'] ?? 0);
                
                $pf = floatval($data['pf'] ?? 0);
                $esi = floatval($data['esi'] ?? 0);
                $pt = floatval($data['pt'] ?? 0);
                $total_deduction = $pf + $esi + $pt;
                $net_salary = $total_earning_earned - $total_deduction;
                
                $provident_fund = floatval($data['provident_fund'] ?? 0);
                $esic = floatval($data['esic'] ?? 0);
                $leave_amount = floatval($data['leave'] ?? 0);
                $holiday = floatval($data['holiday'] ?? 0);
                $bonus = floatval($data['bonus'] ?? 0);
                $uniform = floatval($data['uniform'] ?? 0);
                $gratuity = floatval($data['gratuity'] ?? 0);
                $food_allowance = floatval($data['food_allowance'] ?? 0);
                $total_rebill = $provident_fund + $esic + $leave_amount + $holiday + $bonus + $uniform + $gratuity + $food_allowance;
                
                $earned_ctc = $total_earning_earned + $pf + $esi + $esic + $provident_fund;
                $per_day_wages = floatval($data['per_day_wages'] ?? 0);
                
                $selectedMonthFull = $_GET['month'] ?? date('F Y');
                
                $stmt = $db->prepare("
                    UPDATE salary_register SET
                        employee_type = ?, category = ?,
                        basic = ?, vda = ?, special_allowance = ?, other_allowance = ?, hra = ?, total_earning = ?,
                        present = ?, absent = ?, weekly_off = ?, pay_days = ?,
                        earned_basic = ?, earned_hra = ?, earned_other_allowance = ?, spl_allowance = ?, total_earning_earned = ?,
                        pf = ?, esi = ?, pt = ?, total_deduction = ?, net_salary = ?,
                        provident_fund = ?, esic = ?, leave_amount = ?, holiday = ?, bonus = ?, uniform = ?, gratuity = ?, food_allowance = ?,
                        total_rebill = ?, earned_ctc = ?, per_day_wages = ?,
                        updated_at = NOW()
                    WHERE employee_id = ? AND salary_month = ? AND site_id = ?
                ");
                $stmt->execute([
                    $employee_type, $category,
                    $basic, $vda, $special_allowance, $other_allowance, $hra, $total_earning,
                    $present, $absent, $weekly_off, $pay_days,
                    $earned_basic, $earned_hra, $earned_other_allowance, $spl_allowance, $total_earning_earned,
                    $pf, $esi, $pt, $total_deduction, $net_salary,
                    $provident_fund, $esic, $leave_amount, $holiday, $bonus, $uniform, $gratuity, $food_allowance,
                    $total_rebill, $earned_ctc, $per_day_wages,
                    $empId, $selectedMonthFull, $siteId
                ]);
            }
            
            $db->commit();
            $m = $_GET['m'] ?? '';
            $y = $_GET['y'] ?? '';
            header("Location: ?m=" . urlencode($m) . "&y=" . urlencode($y) . "&saved=1");
            exit;
        } catch (Exception $e) {
            $db->rollBack();
            $errorMessage = "Error saving: " . $e->getMessage();
        }
    }

    if (isset($_GET['saved'])) {
        $successMessage = "Salary data saved successfully!";
    }

    // Get available periods and years
    $availablePeriodsStmt = $db->prepare("
        SELECT DISTINCT salary_month, period_display 
        FROM salary_periods 
        WHERE site_id = ?
        ORDER BY created_at DESC
    ");
    $availablePeriodsStmt->execute([$siteId]);
    $availablePeriods = $availablePeriodsStmt->fetchAll();

    // Get years with data
    $yearsStmt = $db->prepare("
        SELECT DISTINCT SUBSTRING(salary_month, 5, 2) as year_short
        FROM salary_periods
        WHERE site_id = ?
        ORDER BY salary_month DESC
    ");
    $yearsStmt->execute([$siteId]);
    $yearsData = $yearsStmt->fetchAll();

    $years = [];
    $currentYear = date('Y');
    $baseYears = range(2025, $currentYear + 5);
    foreach ($baseYears as $yr) {
        $yearShort = substr($yr, -2);
        $hasData = false;
        foreach ($yearsData as $yd) {
            if ($yd['year_short'] == $yearShort) {
                $hasData = true;
                break;
            }
        }
        $years[] = ['year' => $yr, 'has_data' => $hasData];
    }

    // Handle month/year selection
    $selectedMonthName = isset($_GET['m']) ? $_GET['m'] : (count($availablePeriods) > 0 ? $availablePeriods[0]['salary_month'] : date('M-y'));
    $selectedYearValue = isset($_GET['y']) ? $_GET['y'] : substr(date('y'), -2);
    
    // Convert short month to full
    if (preg_match('/^([A-Za-z]{3})-(\d{2})$/', $selectedMonthName, $matches)) {
        $monthName = $matches[1];
        $yearShort = $matches[2];
        $monthFull = date('F', strtotime($monthName . ' 1'));
        $yearFull = '20' . $yearShort;
        $selectedMonthFull = $monthFull . ' ' . $yearFull;
    } else {
        $selectedMonthFull = $selectedMonthName;
    }

    // Check if period exists
    $periodCheckStmt = $db->prepare("
        SELECT period_id FROM salary_periods 
        WHERE site_id = ? AND salary_month = ?
    ");
    $periodCheckStmt->execute([$siteId, $selectedMonthName]);
    $periodExists = $periodCheckStmt->rowCount() > 0;

    // Get employees data
    $employees = [];
    if ($periodExists) {
        $stmt = $db->prepare("
            SELECT 
                e.employee_id,
                e.employee_code,
                CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                d.designation_name,
                e.employment_status,
                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 = ?
            WHERE e.site_id = ? AND e.employment_status = 'active' AND sr.salary_register_id IS NOT NULL
            ORDER BY e.employee_code
        ");
        $stmt->execute([$selectedMonthFull, $siteId]);
        $employees = $stmt->fetchAll();
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
body {
    font-family: Arial, sans-serif;
    font-size: 11px;
}

.salary-container {
    background: white;
    padding: 10px;
    overflow-x: auto;
}

.period-controls {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    flex-wrap: wrap;
}

.control-group {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    min-height: 70px;
}

.input-wrapper {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.input-wrapper label {
    font-weight: bold;
    font-size: 12px;
    color: #333;
}

.input-wrapper select,
.input-wrapper input[type="text"] {
    padding: 8px 12px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 13px;
    min-width: 150px;
}

.year-indicator {
    font-size: 11px;
    color: #28a745;
    margin-top: 3px;
}

.controls-right {
    display: flex;
    gap: 10px;
    align-items: flex-start;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
}

.btn-success {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
}

.btn-info {
    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
    color: white;
}

.month-header {
    background: white;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #000;
}

.month-header table {
    width: 100%;
    border-collapse: collapse;
}

.month-header td {
    padding: 5px;
    border: 1px solid #000;
}

.month-header .label {
    background: #00008B;
    color: white;
    font-weight: bold;
    width: 150px;
}

.salary-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: auto;
    min-width: 3500px;
}

.salary-table th,
.salary-table td {
    border: 1px solid #000;
    padding: 4px 2px;
    text-align: center;
    font-size: 10px;
}

.salary-table th {
    background: #00008B;
    color: white;
    font-weight: bold;
    padding: 6px 2px;
    position: sticky;
    top: 0;
    z-index: 10;
}

.section-header {
    background: #00008B;
    color: white;
    font-weight: bold;
    text-align: center;
    font-size: 11px;
}

.salary-table input[type="text"],
.salary-table input[type="number"],
.salary-table select {
    width: 100%;
    border: none;
    padding: 2px;
    text-align: center;
    font-size: 10px;
    background: white;
}

.salary-table input[type="number"]:focus,
.salary-table input[type="text"]:focus {
    background: #ffffcc;
    outline: 1px solid #0066cc;
}

.col-slno { width: 30px; }
.col-name { width: 120px; }
.col-designation { width: 100px; }
.col-type { width: 80px; }
.col-category { width: 100px; }
.col-status { width: 70px; }
.col-amount { width: 70px; }
.col-attendance { width: 40px; }
.col-days { width: 50px; }
.col-total { width: 80px; background: #FFA500; font-weight: bold; }

.alert {
    padding: 12px 20px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 10% auto;
    padding: 30px;
    border-radius: 12px;
    width: 500px;
    max-width: 90%;
}

.modal-header {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #555;
}

.form-group select,
.form-group input {
    width: 100%;
    padding: 10px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 25px;
}

.warning-box {
    background: #fff3cd;
    border: 2px solid #ffc107;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
}
</style>

<div class="salary-container">
    <?php include __DIR__ . '/_navigation.php'; ?>
    
    <h1 style="margin: 20px 0;">💰 Salary Register</h1>
    
    <?php if (isset($successMessage)): ?>
        <div class="alert alert-success"><?php echo $successMessage; ?></div>
    <?php endif; ?>
    
    <?php if (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
            <?php if (!$tablesExist): ?>
                <br><br>
                <a href="<?php echo BASE_URL; ?>/database/create_salary_table_direct.php" class="btn btn-primary">
                    🚀 Run Migration Now
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($tablesExist): ?>
    <div class="period-controls">
        <div class="control-group">
            <div class="input-wrapper">
                <label>Select Month:</label>
                <select id="monthSelect" onchange="updatePeriod()">
                    <?php
                    $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    $currentMonth = date('F');
                    foreach ($months as $month) {
                        $selected = (isset($_GET['m']) && strpos($_GET['m'], substr($month, 0, 3)) !== false) || (!isset($_GET['m']) && $month === $currentMonth) ? 'selected' : '';
                        echo "<option value='$month' $selected>$month</option>";
                    }
                    ?>
                </select>
            </div>
            
            <div class="input-wrapper">
                <label>Enter Year:</label>
                <input type="text" id="yearInput" value="<?php echo $selectedYearValue; ?>" 
                       maxlength="4" pattern="\d{2,4}" placeholder="25 or 2025">
                <div class="year-indicator">
                    <?php
                    $yearDisplay = [];
                    foreach ($years as $y) {
                        if ($y['has_data']) {
                            $yearDisplay[] = substr($y['year'], -2);
                        }
                    }
                    if (count($yearDisplay) > 0) {
                        echo "✓ Years with data: " . implode(', ', $yearDisplay);
                    }
                    ?>
                </div>
            </div>
            
            <div class="input-wrapper">
                <label>&nbsp;</label>
                <button type="button" class="btn btn-primary" onclick="updatePeriod()" style="height: 40px;">
                    Go →
                </button>
            </div>
        </div>
        
        <div class="controls-right">
            <?php if ($periodExists): ?>
            <button type="submit" form="salary-form" class="btn btn-success">
                ✓ Save Salary Data
            </button>
            <?php endif; ?>
            
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'">
                ➕ New Salary Period
            </button>
            
            <button type="button" class="btn btn-primary" onclick="exportSalaryData()">
                📥 Export CSV
            </button>
        </div>
    </div>
    
    <div style="text-align: center; margin: 15px 0; padding: 10px; background: #e8f4fd; border-radius: 6px;">
        <span style="font-size: 14px; font-weight: bold; color: #333;">
            <?php 
            if ($periodExists) {
                echo "✓ Period exists: " . htmlspecialchars($selectedMonthFull) . " (" . count($employees) . " employees)";
            } else {
                echo "⚠️ Period not created for " . htmlspecialchars($selectedMonthFull);
            }
            ?>
        </span>
    </div>
    
    <?php if ($periodExists && count($employees) > 0): ?>
    <!-- Month Header -->
    <div class="month-header">
        <table>
            <tr>
                <td class="label">Site Name</td>
                <td><?php echo htmlspecialchars($siteName); ?></td>
            </tr>
            <tr>
                <td class="label">Month</td>
                <td><?php echo htmlspecialchars($selectedMonthFull); ?></td>
            </tr>
        </table>
    </div>
    
    <form id="salary-form" method="POST">
        <input type="hidden" name="save_salary" value="1">
        <input type="hidden" name="month" value="<?php echo htmlspecialchars($selectedMonthFull); ?>">
        
        <table class="salary-table">
            <thead>
                <tr>
                    <th rowspan="2" class="col-slno">S/L No</th>
                    <th rowspan="2" class="col-name">Employee Name</th>
                    <th rowspan="2" class="col-designation">Designation</th>
                    <th rowspan="2" class="col-type">Employee Type</th>
                    <th rowspan="2" class="col-category">Category</th>
                    <th rowspan="2" class="col-status">Status</th>
                    <th colspan="6" class="section-header">Employer Structure</th>
                    <th colspan="4" class="section-header">Attendence</th>
                    <th colspan="10" class="section-header">Earned Salary</th>
                    <th colspan="11" class="section-header">Rebill</th>
                </tr>
                <tr>
                    <!-- Employer Structure -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">VDA</th>
                    <th class="col-amount">Special<br>Allowance</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-total">Total<br>Earning</th>
                    
                    <!-- Attendance -->
                    <th class="col-attendance">P</th>
                    <th class="col-attendance">A</th>
                    <th class="col-attendance">W/O</th>
                    <th class="col-days">Pay Days</th>
                    
                    <!-- Earned Salary -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">Spl<br>Allowance</th>
                    <th class="col-total">Total<br>Earning</th>
                    <th class="col-amount">PF</th>
                    <th class="col-amount">ESI</th>
                    <th class="col-amount">PT</th>
                    <th class="col-amount">Total<br>Deduction</th>
                    <th class="col-total">Net<br>Salary</th>
                    
                    <!-- Rebill -->
                    <th class="col-amount">Provident<br>Fund (12%)</th>
                    <th class="col-amount">ESIC (3.25%)</th>
                    <th class="col-amount">Leave</th>
                    <th class="col-amount">Holiday</th>
                    <th class="col-amount">Bonus</th>
                    <th class="col-amount">Uniform</th>
                    <th class="col-amount">Gratuity</th>
                    <th class="col-amount">Food<br>Allowance</th>
                    <th class="col-total">Total</th>
                    <th class="col-total">Earned<br>CTC</th>
                    <th class="col-amount">Per day<br>Wages</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $slNo = 1;
                foreach ($employees as $emp):
                    $empId = $emp['employee_id'];
                ?>
                <tr>
                    <td><?php echo $slNo++; ?></td>
                    <td style="text-align: left; padding-left: 5px;"><?php echo htmlspecialchars($emp['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($emp['designation_name'] ?? ''); ?></td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][employee_type]">
                            <option value="FTC" <?php echo ($emp['employee_type'] ?? '') === 'FTC' ? 'selected' : ''; ?>>FTC</option>
                            <option value="Regular" <?php echo ($emp['employee_type'] ?? '') === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                        </select>
                    </td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][category]">
                            <option value="Highly Skilled" <?php echo ($emp['category'] ?? '') === 'Highly Skilled' ? 'selected' : ''; ?>>Highly Skilled</option>
                            <option value="Skilled" <?php echo ($emp['category'] ?? '') === 'Skilled' ? 'selected' : ''; ?>>Skilled</option>
                            <option value="Semi Skilled" <?php echo ($emp['category'] ?? '') === 'Semi Skilled' ? 'selected' : ''; ?>>Semi Skilled</option>
                            <option value="Unskilled" <?php echo ($emp['category'] ?? '') === 'Unskilled' ? 'selected' : ''; ?>>Unskilled</option>
                        </select>
                    </td>
                    <td><?php echo ucfirst($emp['employment_status']); ?></td>
                    
                    <!-- Employer Structure -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][basic]" value="<?php echo $emp['basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][vda]" value="<?php echo $emp['vda'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][special_allowance]" value="<?php echo $emp['special_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][other_allowance]" value="<?php echo $emp['other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][hra]" value="<?php echo $emp['hra'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning]" value="<?php echo $emp['total_earning'] ?? 0; ?>" step="0.01" readonly style="background: #FFA500;"></td>
                    
                    <!-- Attendance -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][present]" value="<?php echo $emp['present'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][absent]" value="<?php echo $emp['absent'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][weekly_off]" value="<?php echo $emp['weekly_off'] ?? 0; ?>"></td>
                    <td style="background: #90EE90;"><input type="number" name="employees[<?php echo $empId; ?>][pay_days]" value="<?php echo $emp['pay_days'] ?? 0; ?>" style="background: #90EE90;"></td>
                    
                    <!-- Earned Salary -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_basic]" value="<?php echo $emp['earned_basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_hra]" value="<?php echo $emp['earned_hra'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_other_allowance]" value="<?php echo $emp['earned_other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][spl_allowance]" value="<?php echo $emp['spl_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning_earned]" value="<?php echo $emp['total_earning_earned'] ?? 0; ?>" step="0.01" style="background: #87CEEB;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pf]" value="<?php echo $emp['pf'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esi]" value="<?php echo $emp['esi'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pt]" value="<?php echo $emp['pt'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][total_deduction]" value="<?php echo $emp['total_deduction'] ?? 0; ?>" step="0.01" readonly></td>
                    <td class="col-total" style="background: #4682B4; color: white;"><input type="number" name="employees[<?php echo $empId; ?>][net_salary]" value="<?php echo $emp['net_salary'] ?? 0; ?>" step="0.01" readonly style="background: #4682B4; color: white;"></td>
                    
                    <!-- Rebill -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][provident_fund]" value="<?php echo $emp['provident_fund'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esic]" value="<?php echo $emp['esic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][leave]" value="<?php echo $emp['leave_amount'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][holiday]" value="<?php echo $emp['holiday'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][bonus]" value="<?php echo $emp['bonus'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][uniform]" value="<?php echo $emp['uniform'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][gratuity]" value="<?php echo $emp['gratuity'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][food_allowance]" value="<?php echo $emp['food_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_rebill]" value="<?php echo $emp['total_rebill'] ?? 0; ?>" step="0.01" readonly style="background: #4169E1; color: white;"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][earned_ctc]" value="<?php echo $emp['earned_ctc'] ?? 0; ?>" step="0.01" readonly style="background: #00008B; color: white;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][per_day_wages]" value="<?php echo $emp['per_day_wages'] ?? 0; ?>" step="0.01"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </form>
    
    <?php elseif ($periodExists && count($employees) == 0): ?>
        <div class="warning-box">
            <h3>⚠️ No Employees Found</h3>
            <p>There are no active employees for this period.</p>
        </div>
    <?php else: ?>
        <div class="warning-box">
            <h3>⚠️ Period Not Created</h3>
            <p>Please create a salary period for <strong><?php echo htmlspecialchars($selectedMonthFull); ?></strong> first.</p>
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'" style="margin-top: 15px;">
                ➕ Create New Period
            </button>
        </div>
    <?php endif; ?>
    
    <!-- New Period Modal -->
    <div id="newPeriodModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">➕ Create New Salary Period</div>
            <form method="POST">
                <input type="hidden" name="create_new_period" value="1">
                
                <div class="form-group">
                    <label>Month:</label>
                    <select name="new_month" required>
                        <?php
                        $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                        foreach ($months as $month) {
                            echo "<option value='$month'>$month</option>";
                        }
                        ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Year:</label>
                    <input type="text" name="new_year" required placeholder="2025" maxlength="4" pattern="\d{4}">
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="document.getElementById('newPeriodModal').style.display='none'">Cancel</button>
                    <button type="submit" class="btn btn-success">✓ Create Period</button>
                </div>
            </form>
        </div>
    </div>
    
    <?php endif; // End of $tablesExist ?>
</div>

<script>
// Global export function
function exportSalaryData() {
    try {
        let month = '';
        const monthHidden = document.getElementById('selectedMonthFull');
        if (monthHidden && monthHidden.value) {
            month = monthHidden.value.trim();
        }
        if (!month) {
            const monthSelect = document.getElementById('monthSelect');
            const yearInput = document.getElementById('yearInput');
            if (monthSelect && yearInput) {
                let year = yearInput.value.trim();
                if (year.length === 2) year = '20' + year;
                if (year.length === 4) month = monthSelect.value + ' ' + year;
            }
        }
        if (!month) {
            alert('Unable to detect selected salary month. Please ensure a period is selected.');
            return;
        }
        let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('view_type')) url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
        if (urlParams.get('hr')) url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
        window.location.href = url;
    } catch (error) {
        alert('Export error: ' + error.message);
    }
}
function exportCSV() { exportSalaryData(); }

function updatePeriod() {
    const month = document.getElementById('monthSelect').value;
    let year = document.getElementById('yearInput').value.trim();
    
    // Convert 2-digit to 4-digit year
    if (year.length === 2) {
        year = '20' + year;
    } else if (year.length !== 4) {
        alert('Please enter a valid year (e.g., 25 or 2025)');
        return;
    }
    
    const yearShort = year.substr(-2);
    const monthShort = month.substr(0, 3);
    const period = monthShort + '-' + yearShort;
    
    window.location.href = '?m=' + encodeURIComponent(period) + '&y=' + yearShort;
}

// Auto-calculate totals
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('salary-form');
    if (!form) return;
    
    form.addEventListener('input', function(e) {
        const input = e.target;
        if (input.type === 'number') {
            const row = input.closest('tr');
            calculateRowTotals(row);
        }
    });
    
    function calculateRowTotals(row) {
        const inputs = row.querySelectorAll('input[type="number"]');
        const getName = (name) => {
            for (let input of inputs) {
                if (input.name.includes(name)) return input;
            }
            return null;
        };
        
        // Calculate Total Earning
        const basic = parseFloat(getName('basic')?.value || 0);
        const vda = parseFloat(getName('vda')?.value || 0);
        const special = parseFloat(getName('special_allowance')?.value || 0);
        const other = parseFloat(getName('other_allowance')?.value || 0);
        const hra = parseFloat(getName('hra')?.value || 0);
        
        const totalEarning = basic + vda + special + other + hra;
        const totalEarningInput = getName('total_earning');
        if (totalEarningInput) totalEarningInput.value = totalEarning.toFixed(2);
        
        // Calculate Total Deduction
        const pf = parseFloat(getName('pf')?.value || 0);
        const esi = parseFloat(getName('esi')?.value || 0);
        const pt = parseFloat(getName('pt')?.value || 0);
        
        const totalDeduction = pf + esi + pt;
        const totalDeductionInput = getName('total_deduction');
        if (totalDeductionInput) totalDeductionInput.value = totalDeduction.toFixed(2);
        
        // Calculate Net Salary
        const totalEarningEarned = parseFloat(getName('total_earning_earned')?.value || 0);
        const netSalary = totalEarningEarned - totalDeduction;
        const netSalaryInput = getName('net_salary');
        if (netSalaryInput) netSalaryInput.value = netSalary.toFixed(2);
        
        // Calculate Total Rebill
        const providentFund = parseFloat(getName('provident_fund')?.value || 0);
        const esicRebill = parseFloat(getName('esic')?.value || 0);
        const leave = parseFloat(getName('leave')?.value || 0);
        const holiday = parseFloat(getName('holiday')?.value || 0);
        const bonus = parseFloat(getName('bonus')?.value || 0);
        const uniform = parseFloat(getName('uniform')?.value || 0);
        const gratuity = parseFloat(getName('gratuity')?.value || 0);
        const foodAllowance = parseFloat(getName('food_allowance')?.value || 0);
        
        const totalRebill = providentFund + esicRebill + leave + holiday + bonus + uniform + gratuity + foodAllowance;
        const totalRebillInput = getName('total_rebill');
        if (totalRebillInput) totalRebillInput.value = totalRebill.toFixed(2);
        
        // Calculate Earned CTC
        const earnedCtc = totalEarningEarned + pf + esi + esicRebill + providentFund;
        const earnedCtcInput = getName('earned_ctc');
        if (earnedCtcInput) earnedCtcInput.value = earnedCtc.toFixed(2);
    }
    
    // Initial calculation
    document.querySelectorAll('.salary-table tbody tr').forEach(row => {
        calculateRowTotals(row);
    });
});

function exportCSV() {
    // Get month from hidden input (most reliable)
    let month = '';
    const monthHidden = document.getElementById('selectedMonthFull');
    if (monthHidden && monthHidden.value) {
        month = monthHidden.value.trim();
    }
    
    // Fallback 1: Try month header
    if (!month) {
        const monthLabelCell = document.querySelector('.month-header td:last-child');
        if (monthLabelCell) {
            month = monthLabelCell.textContent.trim();
        }
    }
    
    // Fallback 2: Try period status message
    if (!month) {
        const periodStatus = document.querySelector('.period-meta span, [style*="background: #e8f4fd"] span');
        if (periodStatus) {
            const text = periodStatus.textContent || '';
            const match = text.match(/(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}/);
            if (match) {
                month = match[0];
            }
        }
    }
    
    // Fallback 3: Try month + year controls
    if (!month) {
        const monthSelect = document.getElementById('monthSelect');
        const yearInput = document.getElementById('yearInput');
        if (monthSelect && yearInput) {
            let year = yearInput.value.trim();
            // Convert 2-digit to 4-digit year
            if (year.length === 2) {
                year = '20' + year;
            } else if (year.length !== 4) {
                alert('Invalid year format. Please enter a valid year.');
                return;
            }
            month = monthSelect.value + ' ' + year;
        }
    }
    
    if (!month) {
        alert('Unable to detect selected salary month to export. Please ensure a period is selected.');
        return;
    }
    
    // Build export URL
    let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
    
    // Pass view filters if present
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('view_type')) {
        url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
    }
    if (urlParams.get('hr')) {
        url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
    }
    
    // Navigate to export URL
    window.location.href = url;
}

// Close modal on outside click
window.onclick = function(event) {
    const modal = document.getElementById('newPeriodModal');
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

<?php
/**
 * Salary Register - Period-based System
 * Like Attendance module with month/year selection
 */

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

$pageTitle = "Salary Register";
$currentTab = 'salary_register';
$siteId = getCurrentSiteId();
$db = getDB();
$siteName = $_SESSION['site_name'] ?? 'Base Office';
$userId = $_SESSION['user_id'] ?? 1;

// Check if tables exist
$tablesExist = false;
try {
    $checkTables = $db->query("
        SELECT COUNT(*) as cnt FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name IN ('salary_register', 'salary_periods')
    ");
    $result = $checkTables->fetch();
    $tablesExist = ($result['cnt'] == 2);
} catch (Exception $e) {
    $tablesExist = false;
}

if (!$tablesExist) {
    // Show migration warning
    $errorMessage = "⚠️ Required tables not found! Please run migrations first.";
    $employees = [];
    $periodExists = false;
} else {
    // Handle New Period Creation
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_new_period'])) {
        try {
            $newMonth = $_POST['new_month'];
            $newYear = intval($_POST['new_year']);
            
            // Convert to proper format
            $monthAbbr = date('M', strtotime($newMonth . ' 1'));
            $yearAbbr = substr($newYear, -2);
            $salaryMonth = $monthAbbr . '-' . $yearAbbr; // e.g., "Jan-26"
            $periodDisplay = $newMonth . ' ' . $newYear; // e.g., "January 2026"
            
            // Check if period already exists
            $checkStmt = $db->prepare("
                SELECT period_id FROM salary_periods 
                WHERE site_id = ? AND salary_month = ?
            ");
            $checkStmt->execute([$siteId, $salaryMonth]);
            
            if ($checkStmt->fetch()) {
                $errorMessage = "Period {$periodDisplay} already exists!";
            } else {
                $db->beginTransaction();
                
                // Get active employees count
                $countStmt = $db->prepare("
                    SELECT COUNT(*) as cnt FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $countStmt->execute([$siteId]);
                $empCount = $countStmt->fetch()['cnt'];
                
                // Create period
                $periodStmt = $db->prepare("
                    INSERT INTO salary_periods 
                    (site_id, salary_month, period_display, employee_count, created_by)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $periodStmt->execute([$siteId, $salaryMonth, $periodDisplay, $empCount, $userId]);
                
                // Initialize salary_register entries for all active employees
                $empStmt = $db->prepare("
                    SELECT employee_id FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $empStmt->execute([$siteId]);
                $employees = $empStmt->fetchAll();
                
                $insertStmt = $db->prepare("
                    INSERT INTO salary_register 
                    (site_id, employee_id, salary_month, employee_type, category)
                    VALUES (?, ?, ?, 'FTC', 'Skilled')
                ");
                
                foreach ($employees as $emp) {
                    $insertStmt->execute([$siteId, $emp['employee_id'], $periodDisplay]);
                }
                
                $db->commit();
                $successMessage = "New salary period created: {$periodDisplay}";
                
                // Redirect to new period
                header("Location: ?m=" . urlencode($salaryMonth) . "&y=" . $yearAbbr);
                exit;
            }
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $errorMessage = "Error creating period: " . $e->getMessage();
        }
    }

    // Handle Save Salary Data
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_salary'])) {
        try {
            $db->beginTransaction();
            
            foreach ($_POST['employees'] as $empId => $data) {
                $employee_type = $data['employee_type'] ?? 'FTC';
                $category = $data['category'] ?? 'Skilled';
                
                $basic = floatval($data['basic'] ?? 0);
                $vda = floatval($data['vda'] ?? 0);
                $special_allowance = floatval($data['special_allowance'] ?? 0);
                $other_allowance = floatval($data['other_allowance'] ?? 0);
                $hra = floatval($data['hra'] ?? 0);
                $total_earning = $basic + $vda + $special_allowance + $other_allowance + $hra;
                
                $present = intval($data['present'] ?? 0);
                $absent = intval($data['absent'] ?? 0);
                $weekly_off = intval($data['weekly_off'] ?? 0);
                $pay_days = intval($data['pay_days'] ?? 0);
                
                $earned_basic = floatval($data['earned_basic'] ?? 0);
                $earned_hra = floatval($data['earned_hra'] ?? 0);
                $earned_other_allowance = floatval($data['earned_other_allowance'] ?? 0);
                $spl_allowance = floatval($data['spl_allowance'] ?? 0);
                $total_earning_earned = floatval($data['total_earning_earned'] ?? 0);
                
                $pf = floatval($data['pf'] ?? 0);
                $esi = floatval($data['esi'] ?? 0);
                $pt = floatval($data['pt'] ?? 0);
                $total_deduction = $pf + $esi + $pt;
                $net_salary = $total_earning_earned - $total_deduction;
                
                $provident_fund = floatval($data['provident_fund'] ?? 0);
                $esic = floatval($data['esic'] ?? 0);
                $leave_amount = floatval($data['leave'] ?? 0);
                $holiday = floatval($data['holiday'] ?? 0);
                $bonus = floatval($data['bonus'] ?? 0);
                $uniform = floatval($data['uniform'] ?? 0);
                $gratuity = floatval($data['gratuity'] ?? 0);
                $food_allowance = floatval($data['food_allowance'] ?? 0);
                $total_rebill = $provident_fund + $esic + $leave_amount + $holiday + $bonus + $uniform + $gratuity + $food_allowance;
                
                $earned_ctc = $total_earning_earned + $pf + $esi + $esic + $provident_fund;
                $per_day_wages = floatval($data['per_day_wages'] ?? 0);
                
                $selectedMonthFull = $_GET['month'] ?? date('F Y');
                
                $stmt = $db->prepare("
                    UPDATE salary_register SET
                        employee_type = ?, category = ?,
                        basic = ?, vda = ?, special_allowance = ?, other_allowance = ?, hra = ?, total_earning = ?,
                        present = ?, absent = ?, weekly_off = ?, pay_days = ?,
                        earned_basic = ?, earned_hra = ?, earned_other_allowance = ?, spl_allowance = ?, total_earning_earned = ?,
                        pf = ?, esi = ?, pt = ?, total_deduction = ?, net_salary = ?,
                        provident_fund = ?, esic = ?, leave_amount = ?, holiday = ?, bonus = ?, uniform = ?, gratuity = ?, food_allowance = ?,
                        total_rebill = ?, earned_ctc = ?, per_day_wages = ?,
                        updated_at = NOW()
                    WHERE employee_id = ? AND salary_month = ? AND site_id = ?
                ");
                $stmt->execute([
                    $employee_type, $category,
                    $basic, $vda, $special_allowance, $other_allowance, $hra, $total_earning,
                    $present, $absent, $weekly_off, $pay_days,
                    $earned_basic, $earned_hra, $earned_other_allowance, $spl_allowance, $total_earning_earned,
                    $pf, $esi, $pt, $total_deduction, $net_salary,
                    $provident_fund, $esic, $leave_amount, $holiday, $bonus, $uniform, $gratuity, $food_allowance,
                    $total_rebill, $earned_ctc, $per_day_wages,
                    $empId, $selectedMonthFull, $siteId
                ]);
            }
            
            $db->commit();
            $m = $_GET['m'] ?? '';
            $y = $_GET['y'] ?? '';
            header("Location: ?m=" . urlencode($m) . "&y=" . urlencode($y) . "&saved=1");
            exit;
        } catch (Exception $e) {
            $db->rollBack();
            $errorMessage = "Error saving: " . $e->getMessage();
        }
    }

    if (isset($_GET['saved'])) {
        $successMessage = "Salary data saved successfully!";
    }

    // Get available periods and years
    $availablePeriodsStmt = $db->prepare("
        SELECT DISTINCT salary_month, period_display 
        FROM salary_periods 
        WHERE site_id = ?
        ORDER BY created_at DESC
    ");
    $availablePeriodsStmt->execute([$siteId]);
    $availablePeriods = $availablePeriodsStmt->fetchAll();

    // Get years with data
    $yearsStmt = $db->prepare("
        SELECT DISTINCT SUBSTRING(salary_month, 5, 2) as year_short
        FROM salary_periods
        WHERE site_id = ?
        ORDER BY salary_month DESC
    ");
    $yearsStmt->execute([$siteId]);
    $yearsData = $yearsStmt->fetchAll();

    $years = [];
    $currentYear = date('Y');
    $baseYears = range(2025, $currentYear + 5);
    foreach ($baseYears as $yr) {
        $yearShort = substr($yr, -2);
        $hasData = false;
        foreach ($yearsData as $yd) {
            if ($yd['year_short'] == $yearShort) {
                $hasData = true;
                break;
            }
        }
        $years[] = ['year' => $yr, 'has_data' => $hasData];
    }

    // Handle month/year selection
    $selectedMonthName = isset($_GET['m']) ? $_GET['m'] : (count($availablePeriods) > 0 ? $availablePeriods[0]['salary_month'] : date('M-y'));
    $selectedYearValue = isset($_GET['y']) ? $_GET['y'] : substr(date('y'), -2);
    
    // Convert short month to full
    if (preg_match('/^([A-Za-z]{3})-(\d{2})$/', $selectedMonthName, $matches)) {
        $monthName = $matches[1];
        $yearShort = $matches[2];
        $monthFull = date('F', strtotime($monthName . ' 1'));
        $yearFull = '20' . $yearShort;
        $selectedMonthFull = $monthFull . ' ' . $yearFull;
    } else {
        $selectedMonthFull = $selectedMonthName;
    }

    // Check if period exists
    $periodCheckStmt = $db->prepare("
        SELECT period_id FROM salary_periods 
        WHERE site_id = ? AND salary_month = ?
    ");
    $periodCheckStmt->execute([$siteId, $selectedMonthName]);
    $periodExists = $periodCheckStmt->rowCount() > 0;

    // Get employees data
    $employees = [];
    if ($periodExists) {
        $stmt = $db->prepare("
            SELECT 
                e.employee_id,
                e.employee_code,
                CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                d.designation_name,
                e.employment_status,
                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 = ?
            WHERE e.site_id = ? AND e.employment_status = 'active' AND sr.salary_register_id IS NOT NULL
            ORDER BY e.employee_code
        ");
        $stmt->execute([$selectedMonthFull, $siteId]);
        $employees = $stmt->fetchAll();
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
body {
    font-family: Arial, sans-serif;
    font-size: 11px;
}

.salary-container {
    background: white;
    padding: 10px;
    overflow-x: auto;
}

.period-controls {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    flex-wrap: wrap;
}

.control-group {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    min-height: 70px;
}

.input-wrapper {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.input-wrapper label {
    font-weight: bold;
    font-size: 12px;
    color: #333;
}

.input-wrapper select,
.input-wrapper input[type="text"] {
    padding: 8px 12px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 13px;
    min-width: 150px;
}

.year-indicator {
    font-size: 11px;
    color: #28a745;
    margin-top: 3px;
}

.controls-right {
    display: flex;
    gap: 10px;
    align-items: flex-start;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
}

.btn-success {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
}

.btn-info {
    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
    color: white;
}

.month-header {
    background: white;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #000;
}

.month-header table {
    width: 100%;
    border-collapse: collapse;
}

.month-header td {
    padding: 5px;
    border: 1px solid #000;
}

.month-header .label {
    background: #00008B;
    color: white;
    font-weight: bold;
    width: 150px;
}

.salary-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: auto;
    min-width: 3500px;
}

.salary-table th,
.salary-table td {
    border: 1px solid #000;
    padding: 4px 2px;
    text-align: center;
    font-size: 10px;
}

.salary-table th {
    background: #00008B;
    color: white;
    font-weight: bold;
    padding: 6px 2px;
    position: sticky;
    top: 0;
    z-index: 10;
}

.section-header {
    background: #00008B;
    color: white;
    font-weight: bold;
    text-align: center;
    font-size: 11px;
}

.salary-table input[type="text"],
.salary-table input[type="number"],
.salary-table select {
    width: 100%;
    border: none;
    padding: 2px;
    text-align: center;
    font-size: 10px;
    background: white;
}

.salary-table input[type="number"]:focus,
.salary-table input[type="text"]:focus {
    background: #ffffcc;
    outline: 1px solid #0066cc;
}

.col-slno { width: 30px; }
.col-name { width: 120px; }
.col-designation { width: 100px; }
.col-type { width: 80px; }
.col-category { width: 100px; }
.col-status { width: 70px; }
.col-amount { width: 70px; }
.col-attendance { width: 40px; }
.col-days { width: 50px; }
.col-total { width: 80px; background: #FFA500; font-weight: bold; }

.alert {
    padding: 12px 20px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 10% auto;
    padding: 30px;
    border-radius: 12px;
    width: 500px;
    max-width: 90%;
}

.modal-header {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #555;
}

.form-group select,
.form-group input {
    width: 100%;
    padding: 10px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 25px;
}

.warning-box {
    background: #fff3cd;
    border: 2px solid #ffc107;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
}
</style>

<div class="salary-container">
    <?php include __DIR__ . '/_navigation.php'; ?>
    
    <h1 style="margin: 20px 0;">💰 Salary Register</h1>
    
    <?php if (isset($successMessage)): ?>
        <div class="alert alert-success"><?php echo $successMessage; ?></div>
    <?php endif; ?>
    
    <?php if (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
            <?php if (!$tablesExist): ?>
                <br><br>
                <a href="<?php echo BASE_URL; ?>/database/create_salary_table_direct.php" class="btn btn-primary">
                    🚀 Run Migration Now
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($tablesExist): ?>
    <div class="period-controls">
        <div class="control-group">
            <div class="input-wrapper">
                <label>Select Month:</label>
                <select id="monthSelect" onchange="updatePeriod()">
                    <?php
                    $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    $currentMonth = date('F');
                    foreach ($months as $month) {
                        $selected = (isset($_GET['m']) && strpos($_GET['m'], substr($month, 0, 3)) !== false) || (!isset($_GET['m']) && $month === $currentMonth) ? 'selected' : '';
                        echo "<option value='$month' $selected>$month</option>";
                    }
                    ?>
                </select>
            </div>
            
            <div class="input-wrapper">
                <label>Enter Year:</label>
                <input type="text" id="yearInput" value="<?php echo $selectedYearValue; ?>" 
                       maxlength="4" pattern="\d{2,4}" placeholder="25 or 2025">
                <div class="year-indicator">
                    <?php
                    $yearDisplay = [];
                    foreach ($years as $y) {
                        if ($y['has_data']) {
                            $yearDisplay[] = substr($y['year'], -2);
                        }
                    }
                    if (count($yearDisplay) > 0) {
                        echo "✓ Years with data: " . implode(', ', $yearDisplay);
                    }
                    ?>
                </div>
            </div>
            
            <div class="input-wrapper">
                <label>&nbsp;</label>
                <button type="button" class="btn btn-primary" onclick="updatePeriod()" style="height: 40px;">
                    Go →
                </button>
            </div>
        </div>
        
        <div class="controls-right">
            <?php if ($periodExists): ?>
            <button type="submit" form="salary-form" class="btn btn-success">
                ✓ Save Salary Data
            </button>
            <?php endif; ?>
            
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'">
                ➕ New Salary Period
            </button>
            
            <button type="button" class="btn btn-primary" onclick="exportSalaryData()">
                📥 Export CSV
            </button>
        </div>
    </div>
    
    <div style="text-align: center; margin: 15px 0; padding: 10px; background: #e8f4fd; border-radius: 6px;">
        <span style="font-size: 14px; font-weight: bold; color: #333;">
            <?php 
            if ($periodExists) {
                echo "✓ Period exists: " . htmlspecialchars($selectedMonthFull) . " (" . count($employees) . " employees)";
            } else {
                echo "⚠️ Period not created for " . htmlspecialchars($selectedMonthFull);
            }
            ?>
        </span>
    </div>
    
    <?php if ($periodExists && count($employees) > 0): ?>
    <!-- Month Header -->
    <div class="month-header">
        <table>
            <tr>
                <td class="label">Site Name</td>
                <td><?php echo htmlspecialchars($siteName); ?></td>
            </tr>
            <tr>
                <td class="label">Month</td>
                <td><?php echo htmlspecialchars($selectedMonthFull); ?></td>
            </tr>
        </table>
    </div>
    
    <form id="salary-form" method="POST">
        <input type="hidden" name="save_salary" value="1">
        <input type="hidden" name="month" value="<?php echo htmlspecialchars($selectedMonthFull); ?>">
        
        <table class="salary-table">
            <thead>
                <tr>
                    <th rowspan="2" class="col-slno">S/L No</th>
                    <th rowspan="2" class="col-name">Employee Name</th>
                    <th rowspan="2" class="col-designation">Designation</th>
                    <th rowspan="2" class="col-type">Employee Type</th>
                    <th rowspan="2" class="col-category">Category</th>
                    <th rowspan="2" class="col-status">Status</th>
                    <th colspan="6" class="section-header">Employer Structure</th>
                    <th colspan="4" class="section-header">Attendence</th>
                    <th colspan="10" class="section-header">Earned Salary</th>
                    <th colspan="11" class="section-header">Rebill</th>
                </tr>
                <tr>
                    <!-- Employer Structure -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">VDA</th>
                    <th class="col-amount">Special<br>Allowance</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-total">Total<br>Earning</th>
                    
                    <!-- Attendance -->
                    <th class="col-attendance">P</th>
                    <th class="col-attendance">A</th>
                    <th class="col-attendance">W/O</th>
                    <th class="col-days">Pay Days</th>
                    
                    <!-- Earned Salary -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">Spl<br>Allowance</th>
                    <th class="col-total">Total<br>Earning</th>
                    <th class="col-amount">PF</th>
                    <th class="col-amount">ESI</th>
                    <th class="col-amount">PT</th>
                    <th class="col-amount">Total<br>Deduction</th>
                    <th class="col-total">Net<br>Salary</th>
                    
                    <!-- Rebill -->
                    <th class="col-amount">Provident<br>Fund (12%)</th>
                    <th class="col-amount">ESIC (3.25%)</th>
                    <th class="col-amount">Leave</th>
                    <th class="col-amount">Holiday</th>
                    <th class="col-amount">Bonus</th>
                    <th class="col-amount">Uniform</th>
                    <th class="col-amount">Gratuity</th>
                    <th class="col-amount">Food<br>Allowance</th>
                    <th class="col-total">Total</th>
                    <th class="col-total">Earned<br>CTC</th>
                    <th class="col-amount">Per day<br>Wages</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $slNo = 1;
                foreach ($employees as $emp):
                    $empId = $emp['employee_id'];
                ?>
                <tr>
                    <td><?php echo $slNo++; ?></td>
                    <td style="text-align: left; padding-left: 5px;"><?php echo htmlspecialchars($emp['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($emp['designation_name'] ?? ''); ?></td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][employee_type]">
                            <option value="FTC" <?php echo ($emp['employee_type'] ?? '') === 'FTC' ? 'selected' : ''; ?>>FTC</option>
                            <option value="Regular" <?php echo ($emp['employee_type'] ?? '') === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                        </select>
                    </td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][category]">
                            <option value="Highly Skilled" <?php echo ($emp['category'] ?? '') === 'Highly Skilled' ? 'selected' : ''; ?>>Highly Skilled</option>
                            <option value="Skilled" <?php echo ($emp['category'] ?? '') === 'Skilled' ? 'selected' : ''; ?>>Skilled</option>
                            <option value="Semi Skilled" <?php echo ($emp['category'] ?? '') === 'Semi Skilled' ? 'selected' : ''; ?>>Semi Skilled</option>
                            <option value="Unskilled" <?php echo ($emp['category'] ?? '') === 'Unskilled' ? 'selected' : ''; ?>>Unskilled</option>
                        </select>
                    </td>
                    <td><?php echo ucfirst($emp['employment_status']); ?></td>
                    
                    <!-- Employer Structure -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][basic]" value="<?php echo $emp['basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][vda]" value="<?php echo $emp['vda'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][special_allowance]" value="<?php echo $emp['special_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][other_allowance]" value="<?php echo $emp['other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][hra]" value="<?php echo $emp['hra'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning]" value="<?php echo $emp['total_earning'] ?? 0; ?>" step="0.01" readonly style="background: #FFA500;"></td>
                    
                    <!-- Attendance -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][present]" value="<?php echo $emp['present'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][absent]" value="<?php echo $emp['absent'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][weekly_off]" value="<?php echo $emp['weekly_off'] ?? 0; ?>"></td>
                    <td style="background: #90EE90;"><input type="number" name="employees[<?php echo $empId; ?>][pay_days]" value="<?php echo $emp['pay_days'] ?? 0; ?>" style="background: #90EE90;"></td>
                    
                    <!-- Earned Salary -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_basic]" value="<?php echo $emp['earned_basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_hra]" value="<?php echo $emp['earned_hra'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_other_allowance]" value="<?php echo $emp['earned_other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][spl_allowance]" value="<?php echo $emp['spl_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning_earned]" value="<?php echo $emp['total_earning_earned'] ?? 0; ?>" step="0.01" style="background: #87CEEB;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pf]" value="<?php echo $emp['pf'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esi]" value="<?php echo $emp['esi'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pt]" value="<?php echo $emp['pt'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][total_deduction]" value="<?php echo $emp['total_deduction'] ?? 0; ?>" step="0.01" readonly></td>
                    <td class="col-total" style="background: #4682B4; color: white;"><input type="number" name="employees[<?php echo $empId; ?>][net_salary]" value="<?php echo $emp['net_salary'] ?? 0; ?>" step="0.01" readonly style="background: #4682B4; color: white;"></td>
                    
                    <!-- Rebill -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][provident_fund]" value="<?php echo $emp['provident_fund'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esic]" value="<?php echo $emp['esic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][leave]" value="<?php echo $emp['leave_amount'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][holiday]" value="<?php echo $emp['holiday'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][bonus]" value="<?php echo $emp['bonus'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][uniform]" value="<?php echo $emp['uniform'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][gratuity]" value="<?php echo $emp['gratuity'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][food_allowance]" value="<?php echo $emp['food_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_rebill]" value="<?php echo $emp['total_rebill'] ?? 0; ?>" step="0.01" readonly style="background: #4169E1; color: white;"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][earned_ctc]" value="<?php echo $emp['earned_ctc'] ?? 0; ?>" step="0.01" readonly style="background: #00008B; color: white;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][per_day_wages]" value="<?php echo $emp['per_day_wages'] ?? 0; ?>" step="0.01"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </form>
    
    <?php elseif ($periodExists && count($employees) == 0): ?>
        <div class="warning-box">
            <h3>⚠️ No Employees Found</h3>
            <p>There are no active employees for this period.</p>
        </div>
    <?php else: ?>
        <div class="warning-box">
            <h3>⚠️ Period Not Created</h3>
            <p>Please create a salary period for <strong><?php echo htmlspecialchars($selectedMonthFull); ?></strong> first.</p>
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'" style="margin-top: 15px;">
                ➕ Create New Period
            </button>
        </div>
    <?php endif; ?>
    
    <!-- New Period Modal -->
    <div id="newPeriodModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">➕ Create New Salary Period</div>
            <form method="POST">
                <input type="hidden" name="create_new_period" value="1">
                
                <div class="form-group">
                    <label>Month:</label>
                    <select name="new_month" required>
                        <?php
                        $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                        foreach ($months as $month) {
                            echo "<option value='$month'>$month</option>";
                        }
                        ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Year:</label>
                    <input type="text" name="new_year" required placeholder="2025" maxlength="4" pattern="\d{4}">
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="document.getElementById('newPeriodModal').style.display='none'">Cancel</button>
                    <button type="submit" class="btn btn-success">✓ Create Period</button>
                </div>
            </form>
        </div>
    </div>
    
    <?php endif; // End of $tablesExist ?>
</div>

<script>
// Global export function
function exportSalaryData() {
    try {
        let month = '';
        const monthHidden = document.getElementById('selectedMonthFull');
        if (monthHidden && monthHidden.value) {
            month = monthHidden.value.trim();
        }
        if (!month) {
            const monthSelect = document.getElementById('monthSelect');
            const yearInput = document.getElementById('yearInput');
            if (monthSelect && yearInput) {
                let year = yearInput.value.trim();
                if (year.length === 2) year = '20' + year;
                if (year.length === 4) month = monthSelect.value + ' ' + year;
            }
        }
        if (!month) {
            alert('Unable to detect selected salary month. Please ensure a period is selected.');
            return;
        }
        let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('view_type')) url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
        if (urlParams.get('hr')) url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
        window.location.href = url;
    } catch (error) {
        alert('Export error: ' + error.message);
    }
}
function exportCSV() { exportSalaryData(); }

function updatePeriod() {
    const month = document.getElementById('monthSelect').value;
    let year = document.getElementById('yearInput').value.trim();
    
    // Convert 2-digit to 4-digit year
    if (year.length === 2) {
        year = '20' + year;
    } else if (year.length !== 4) {
        alert('Please enter a valid year (e.g., 25 or 2025)');
        return;
    }
    
    const yearShort = year.substr(-2);
    const monthShort = month.substr(0, 3);
    const period = monthShort + '-' + yearShort;
    
    window.location.href = '?m=' + encodeURIComponent(period) + '&y=' + yearShort;
}

// Auto-calculate totals
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('salary-form');
    if (!form) return;
    
    form.addEventListener('input', function(e) {
        const input = e.target;
        if (input.type === 'number') {
            const row = input.closest('tr');
            calculateRowTotals(row);
        }
    });
    
    function calculateRowTotals(row) {
        const inputs = row.querySelectorAll('input[type="number"]');
        const getName = (name) => {
            for (let input of inputs) {
                if (input.name.includes(name)) return input;
            }
            return null;
        };
        
        // Calculate Total Earning
        const basic = parseFloat(getName('basic')?.value || 0);
        const vda = parseFloat(getName('vda')?.value || 0);
        const special = parseFloat(getName('special_allowance')?.value || 0);
        const other = parseFloat(getName('other_allowance')?.value || 0);
        const hra = parseFloat(getName('hra')?.value || 0);
        
        const totalEarning = basic + vda + special + other + hra;
        const totalEarningInput = getName('total_earning');
        if (totalEarningInput) totalEarningInput.value = totalEarning.toFixed(2);
        
        // Calculate Total Deduction
        const pf = parseFloat(getName('pf')?.value || 0);
        const esi = parseFloat(getName('esi')?.value || 0);
        const pt = parseFloat(getName('pt')?.value || 0);
        
        const totalDeduction = pf + esi + pt;
        const totalDeductionInput = getName('total_deduction');
        if (totalDeductionInput) totalDeductionInput.value = totalDeduction.toFixed(2);
        
        // Calculate Net Salary
        const totalEarningEarned = parseFloat(getName('total_earning_earned')?.value || 0);
        const netSalary = totalEarningEarned - totalDeduction;
        const netSalaryInput = getName('net_salary');
        if (netSalaryInput) netSalaryInput.value = netSalary.toFixed(2);
        
        // Calculate Total Rebill
        const providentFund = parseFloat(getName('provident_fund')?.value || 0);
        const esicRebill = parseFloat(getName('esic')?.value || 0);
        const leave = parseFloat(getName('leave')?.value || 0);
        const holiday = parseFloat(getName('holiday')?.value || 0);
        const bonus = parseFloat(getName('bonus')?.value || 0);
        const uniform = parseFloat(getName('uniform')?.value || 0);
        const gratuity = parseFloat(getName('gratuity')?.value || 0);
        const foodAllowance = parseFloat(getName('food_allowance')?.value || 0);
        
        const totalRebill = providentFund + esicRebill + leave + holiday + bonus + uniform + gratuity + foodAllowance;
        const totalRebillInput = getName('total_rebill');
        if (totalRebillInput) totalRebillInput.value = totalRebill.toFixed(2);
        
        // Calculate Earned CTC
        const earnedCtc = totalEarningEarned + pf + esi + esicRebill + providentFund;
        const earnedCtcInput = getName('earned_ctc');
        if (earnedCtcInput) earnedCtcInput.value = earnedCtc.toFixed(2);
    }
    
    // Initial calculation
    document.querySelectorAll('.salary-table tbody tr').forEach(row => {
        calculateRowTotals(row);
    });
});

function exportCSV() {
    // Get month from hidden input (most reliable)
    let month = '';
    const monthHidden = document.getElementById('selectedMonthFull');
    if (monthHidden && monthHidden.value) {
        month = monthHidden.value.trim();
    }
    
    // Fallback 1: Try month header
    if (!month) {
        const monthLabelCell = document.querySelector('.month-header td:last-child');
        if (monthLabelCell) {
            month = monthLabelCell.textContent.trim();
        }
    }
    
    // Fallback 2: Try period status message
    if (!month) {
        const periodStatus = document.querySelector('.period-meta span, [style*="background: #e8f4fd"] span');
        if (periodStatus) {
            const text = periodStatus.textContent || '';
            const match = text.match(/(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}/);
            if (match) {
                month = match[0];
            }
        }
    }
    
    // Fallback 3: Try month + year controls
    if (!month) {
        const monthSelect = document.getElementById('monthSelect');
        const yearInput = document.getElementById('yearInput');
        if (monthSelect && yearInput) {
            let year = yearInput.value.trim();
            // Convert 2-digit to 4-digit year
            if (year.length === 2) {
                year = '20' + year;
            } else if (year.length !== 4) {
                alert('Invalid year format. Please enter a valid year.');
                return;
            }
            month = monthSelect.value + ' ' + year;
        }
    }
    
    if (!month) {
        alert('Unable to detect selected salary month to export. Please ensure a period is selected.');
        return;
    }
    
    // Build export URL
    let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
    
    // Pass view filters if present
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('view_type')) {
        url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
    }
    if (urlParams.get('hr')) {
        url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
    }
    
    // Navigate to export URL
    window.location.href = url;
}

// Close modal on outside click
window.onclick = function(event) {
    const modal = document.getElementById('newPeriodModal');
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

<?php
/**
 * Salary Register - Period-based System
 * Like Attendance module with month/year selection
 */

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

$pageTitle = "Salary Register";
$currentTab = 'salary_register';
$siteId = getCurrentSiteId();
$db = getDB();
$siteName = $_SESSION['site_name'] ?? 'Base Office';
$userId = $_SESSION['user_id'] ?? 1;

// Check if tables exist
$tablesExist = false;
try {
    $checkTables = $db->query("
        SELECT COUNT(*) as cnt FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name IN ('salary_register', 'salary_periods')
    ");
    $result = $checkTables->fetch();
    $tablesExist = ($result['cnt'] == 2);
} catch (Exception $e) {
    $tablesExist = false;
}

if (!$tablesExist) {
    // Show migration warning
    $errorMessage = "⚠️ Required tables not found! Please run migrations first.";
    $employees = [];
    $periodExists = false;
} else {
    // Handle New Period Creation
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_new_period'])) {
        try {
            $newMonth = $_POST['new_month'];
            $newYear = intval($_POST['new_year']);
            
            // Convert to proper format
            $monthAbbr = date('M', strtotime($newMonth . ' 1'));
            $yearAbbr = substr($newYear, -2);
            $salaryMonth = $monthAbbr . '-' . $yearAbbr; // e.g., "Jan-26"
            $periodDisplay = $newMonth . ' ' . $newYear; // e.g., "January 2026"
            
            // Check if period already exists
            $checkStmt = $db->prepare("
                SELECT period_id FROM salary_periods 
                WHERE site_id = ? AND salary_month = ?
            ");
            $checkStmt->execute([$siteId, $salaryMonth]);
            
            if ($checkStmt->fetch()) {
                $errorMessage = "Period {$periodDisplay} already exists!";
            } else {
                $db->beginTransaction();
                
                // Get active employees count
                $countStmt = $db->prepare("
                    SELECT COUNT(*) as cnt FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $countStmt->execute([$siteId]);
                $empCount = $countStmt->fetch()['cnt'];
                
                // Create period
                $periodStmt = $db->prepare("
                    INSERT INTO salary_periods 
                    (site_id, salary_month, period_display, employee_count, created_by)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $periodStmt->execute([$siteId, $salaryMonth, $periodDisplay, $empCount, $userId]);
                
                // Initialize salary_register entries for all active employees
                $empStmt = $db->prepare("
                    SELECT employee_id FROM employees 
                    WHERE site_id = ? AND employment_status = 'active'
                ");
                $empStmt->execute([$siteId]);
                $employees = $empStmt->fetchAll();
                
                $insertStmt = $db->prepare("
                    INSERT INTO salary_register 
                    (site_id, employee_id, salary_month, employee_type, category)
                    VALUES (?, ?, ?, 'FTC', 'Skilled')
                ");
                
                foreach ($employees as $emp) {
                    $insertStmt->execute([$siteId, $emp['employee_id'], $periodDisplay]);
                }
                
                $db->commit();
                $successMessage = "New salary period created: {$periodDisplay}";
                
                // Redirect to new period
                header("Location: ?m=" . urlencode($salaryMonth) . "&y=" . $yearAbbr);
                exit;
            }
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $errorMessage = "Error creating period: " . $e->getMessage();
        }
    }

    // Handle Save Salary Data
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_salary'])) {
        try {
            $db->beginTransaction();
            
            foreach ($_POST['employees'] as $empId => $data) {
                $employee_type = $data['employee_type'] ?? 'FTC';
                $category = $data['category'] ?? 'Skilled';
                
                $basic = floatval($data['basic'] ?? 0);
                $vda = floatval($data['vda'] ?? 0);
                $special_allowance = floatval($data['special_allowance'] ?? 0);
                $other_allowance = floatval($data['other_allowance'] ?? 0);
                $hra = floatval($data['hra'] ?? 0);
                $total_earning = $basic + $vda + $special_allowance + $other_allowance + $hra;
                
                $present = intval($data['present'] ?? 0);
                $absent = intval($data['absent'] ?? 0);
                $weekly_off = intval($data['weekly_off'] ?? 0);
                $pay_days = intval($data['pay_days'] ?? 0);
                
                $earned_basic = floatval($data['earned_basic'] ?? 0);
                $earned_hra = floatval($data['earned_hra'] ?? 0);
                $earned_other_allowance = floatval($data['earned_other_allowance'] ?? 0);
                $spl_allowance = floatval($data['spl_allowance'] ?? 0);
                $total_earning_earned = floatval($data['total_earning_earned'] ?? 0);
                
                $pf = floatval($data['pf'] ?? 0);
                $esi = floatval($data['esi'] ?? 0);
                $pt = floatval($data['pt'] ?? 0);
                $total_deduction = $pf + $esi + $pt;
                $net_salary = $total_earning_earned - $total_deduction;
                
                $provident_fund = floatval($data['provident_fund'] ?? 0);
                $esic = floatval($data['esic'] ?? 0);
                $leave_amount = floatval($data['leave'] ?? 0);
                $holiday = floatval($data['holiday'] ?? 0);
                $bonus = floatval($data['bonus'] ?? 0);
                $uniform = floatval($data['uniform'] ?? 0);
                $gratuity = floatval($data['gratuity'] ?? 0);
                $food_allowance = floatval($data['food_allowance'] ?? 0);
                $total_rebill = $provident_fund + $esic + $leave_amount + $holiday + $bonus + $uniform + $gratuity + $food_allowance;
                
                $earned_ctc = $total_earning_earned + $pf + $esi + $esic + $provident_fund;
                $per_day_wages = floatval($data['per_day_wages'] ?? 0);
                
                $selectedMonthFull = $_GET['month'] ?? date('F Y');
                
                $stmt = $db->prepare("
                    UPDATE salary_register SET
                        employee_type = ?, category = ?,
                        basic = ?, vda = ?, special_allowance = ?, other_allowance = ?, hra = ?, total_earning = ?,
                        present = ?, absent = ?, weekly_off = ?, pay_days = ?,
                        earned_basic = ?, earned_hra = ?, earned_other_allowance = ?, spl_allowance = ?, total_earning_earned = ?,
                        pf = ?, esi = ?, pt = ?, total_deduction = ?, net_salary = ?,
                        provident_fund = ?, esic = ?, leave_amount = ?, holiday = ?, bonus = ?, uniform = ?, gratuity = ?, food_allowance = ?,
                        total_rebill = ?, earned_ctc = ?, per_day_wages = ?,
                        updated_at = NOW()
                    WHERE employee_id = ? AND salary_month = ? AND site_id = ?
                ");
                $stmt->execute([
                    $employee_type, $category,
                    $basic, $vda, $special_allowance, $other_allowance, $hra, $total_earning,
                    $present, $absent, $weekly_off, $pay_days,
                    $earned_basic, $earned_hra, $earned_other_allowance, $spl_allowance, $total_earning_earned,
                    $pf, $esi, $pt, $total_deduction, $net_salary,
                    $provident_fund, $esic, $leave_amount, $holiday, $bonus, $uniform, $gratuity, $food_allowance,
                    $total_rebill, $earned_ctc, $per_day_wages,
                    $empId, $selectedMonthFull, $siteId
                ]);
            }
            
            $db->commit();
            $m = $_GET['m'] ?? '';
            $y = $_GET['y'] ?? '';
            header("Location: ?m=" . urlencode($m) . "&y=" . urlencode($y) . "&saved=1");
            exit;
        } catch (Exception $e) {
            $db->rollBack();
            $errorMessage = "Error saving: " . $e->getMessage();
        }
    }

    if (isset($_GET['saved'])) {
        $successMessage = "Salary data saved successfully!";
    }

    // Get available periods and years
    $availablePeriodsStmt = $db->prepare("
        SELECT DISTINCT salary_month, period_display 
        FROM salary_periods 
        WHERE site_id = ?
        ORDER BY created_at DESC
    ");
    $availablePeriodsStmt->execute([$siteId]);
    $availablePeriods = $availablePeriodsStmt->fetchAll();

    // Get years with data
    $yearsStmt = $db->prepare("
        SELECT DISTINCT SUBSTRING(salary_month, 5, 2) as year_short
        FROM salary_periods
        WHERE site_id = ?
        ORDER BY salary_month DESC
    ");
    $yearsStmt->execute([$siteId]);
    $yearsData = $yearsStmt->fetchAll();

    $years = [];
    $currentYear = date('Y');
    $baseYears = range(2025, $currentYear + 5);
    foreach ($baseYears as $yr) {
        $yearShort = substr($yr, -2);
        $hasData = false;
        foreach ($yearsData as $yd) {
            if ($yd['year_short'] == $yearShort) {
                $hasData = true;
                break;
            }
        }
        $years[] = ['year' => $yr, 'has_data' => $hasData];
    }

    // Handle month/year selection
    $selectedMonthName = isset($_GET['m']) ? $_GET['m'] : (count($availablePeriods) > 0 ? $availablePeriods[0]['salary_month'] : date('M-y'));
    $selectedYearValue = isset($_GET['y']) ? $_GET['y'] : substr(date('y'), -2);
    
    // Convert short month to full
    if (preg_match('/^([A-Za-z]{3})-(\d{2})$/', $selectedMonthName, $matches)) {
        $monthName = $matches[1];
        $yearShort = $matches[2];
        $monthFull = date('F', strtotime($monthName . ' 1'));
        $yearFull = '20' . $yearShort;
        $selectedMonthFull = $monthFull . ' ' . $yearFull;
    } else {
        $selectedMonthFull = $selectedMonthName;
    }

    // Check if period exists
    $periodCheckStmt = $db->prepare("
        SELECT period_id FROM salary_periods 
        WHERE site_id = ? AND salary_month = ?
    ");
    $periodCheckStmt->execute([$siteId, $selectedMonthName]);
    $periodExists = $periodCheckStmt->rowCount() > 0;

    // Get employees data
    $employees = [];
    if ($periodExists) {
        $stmt = $db->prepare("
            SELECT 
                e.employee_id,
                e.employee_code,
                CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                d.designation_name,
                e.employment_status,
                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 = ?
            WHERE e.site_id = ? AND e.employment_status = 'active' AND sr.salary_register_id IS NOT NULL
            ORDER BY e.employee_code
        ");
        $stmt->execute([$selectedMonthFull, $siteId]);
        $employees = $stmt->fetchAll();
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
body {
    font-family: Arial, sans-serif;
    font-size: 11px;
}

.salary-container {
    background: white;
    padding: 10px;
    overflow-x: auto;
}

.period-controls {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    flex-wrap: wrap;
}

.control-group {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    min-height: 70px;
}

.input-wrapper {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.input-wrapper label {
    font-weight: bold;
    font-size: 12px;
    color: #333;
}

.input-wrapper select,
.input-wrapper input[type="text"] {
    padding: 8px 12px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 13px;
    min-width: 150px;
}

.year-indicator {
    font-size: 11px;
    color: #28a745;
    margin-top: 3px;
}

.controls-right {
    display: flex;
    gap: 10px;
    align-items: flex-start;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
}

.btn-success {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
}

.btn-info {
    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
    color: white;
}

.month-header {
    background: white;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #000;
}

.month-header table {
    width: 100%;
    border-collapse: collapse;
}

.month-header td {
    padding: 5px;
    border: 1px solid #000;
}

.month-header .label {
    background: #00008B;
    color: white;
    font-weight: bold;
    width: 150px;
}

.salary-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: auto;
    min-width: 3500px;
}

.salary-table th,
.salary-table td {
    border: 1px solid #000;
    padding: 4px 2px;
    text-align: center;
    font-size: 10px;
}

.salary-table th {
    background: #00008B;
    color: white;
    font-weight: bold;
    padding: 6px 2px;
    position: sticky;
    top: 0;
    z-index: 10;
}

.section-header {
    background: #00008B;
    color: white;
    font-weight: bold;
    text-align: center;
    font-size: 11px;
}

.salary-table input[type="text"],
.salary-table input[type="number"],
.salary-table select {
    width: 100%;
    border: none;
    padding: 2px;
    text-align: center;
    font-size: 10px;
    background: white;
}

.salary-table input[type="number"]:focus,
.salary-table input[type="text"]:focus {
    background: #ffffcc;
    outline: 1px solid #0066cc;
}

.col-slno { width: 30px; }
.col-name { width: 120px; }
.col-designation { width: 100px; }
.col-type { width: 80px; }
.col-category { width: 100px; }
.col-status { width: 70px; }
.col-amount { width: 70px; }
.col-attendance { width: 40px; }
.col-days { width: 50px; }
.col-total { width: 80px; background: #FFA500; font-weight: bold; }

.alert {
    padding: 12px 20px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 10% auto;
    padding: 30px;
    border-radius: 12px;
    width: 500px;
    max-width: 90%;
}

.modal-header {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #555;
}

.form-group select,
.form-group input {
    width: 100%;
    padding: 10px;
    border: 2px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 25px;
}

.warning-box {
    background: #fff3cd;
    border: 2px solid #ffc107;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
}
</style>

<div class="salary-container">
    <?php include __DIR__ . '/_navigation.php'; ?>
    
    <h1 style="margin: 20px 0;">💰 Salary Register</h1>
    
    <?php if (isset($successMessage)): ?>
        <div class="alert alert-success"><?php echo $successMessage; ?></div>
    <?php endif; ?>
    
    <?php if (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
            <?php if (!$tablesExist): ?>
                <br><br>
                <a href="<?php echo BASE_URL; ?>/database/create_salary_table_direct.php" class="btn btn-primary">
                    🚀 Run Migration Now
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($tablesExist): ?>
    <div class="period-controls">
        <div class="control-group">
            <div class="input-wrapper">
                <label>Select Month:</label>
                <select id="monthSelect" onchange="updatePeriod()">
                    <?php
                    $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    $currentMonth = date('F');
                    foreach ($months as $month) {
                        $selected = (isset($_GET['m']) && strpos($_GET['m'], substr($month, 0, 3)) !== false) || (!isset($_GET['m']) && $month === $currentMonth) ? 'selected' : '';
                        echo "<option value='$month' $selected>$month</option>";
                    }
                    ?>
                </select>
            </div>
            
            <div class="input-wrapper">
                <label>Enter Year:</label>
                <input type="text" id="yearInput" value="<?php echo $selectedYearValue; ?>" 
                       maxlength="4" pattern="\d{2,4}" placeholder="25 or 2025">
                <div class="year-indicator">
                    <?php
                    $yearDisplay = [];
                    foreach ($years as $y) {
                        if ($y['has_data']) {
                            $yearDisplay[] = substr($y['year'], -2);
                        }
                    }
                    if (count($yearDisplay) > 0) {
                        echo "✓ Years with data: " . implode(', ', $yearDisplay);
                    }
                    ?>
                </div>
            </div>
            
            <div class="input-wrapper">
                <label>&nbsp;</label>
                <button type="button" class="btn btn-primary" onclick="updatePeriod()" style="height: 40px;">
                    Go →
                </button>
            </div>
        </div>
        
        <div class="controls-right">
            <?php if ($periodExists): ?>
            <button type="submit" form="salary-form" class="btn btn-success">
                ✓ Save Salary Data
            </button>
            <?php endif; ?>
            
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'">
                ➕ New Salary Period
            </button>
            
            <button type="button" class="btn btn-primary" onclick="exportSalaryData()">
                📥 Export CSV
            </button>
        </div>
    </div>
    
    <div style="text-align: center; margin: 15px 0; padding: 10px; background: #e8f4fd; border-radius: 6px;">
        <span style="font-size: 14px; font-weight: bold; color: #333;">
            <?php 
            if ($periodExists) {
                echo "✓ Period exists: " . htmlspecialchars($selectedMonthFull) . " (" . count($employees) . " employees)";
            } else {
                echo "⚠️ Period not created for " . htmlspecialchars($selectedMonthFull);
            }
            ?>
        </span>
    </div>
    
    <?php if ($periodExists && count($employees) > 0): ?>
    <!-- Month Header -->
    <div class="month-header">
        <table>
            <tr>
                <td class="label">Site Name</td>
                <td><?php echo htmlspecialchars($siteName); ?></td>
            </tr>
            <tr>
                <td class="label">Month</td>
                <td><?php echo htmlspecialchars($selectedMonthFull); ?></td>
            </tr>
        </table>
    </div>
    
    <form id="salary-form" method="POST">
        <input type="hidden" name="save_salary" value="1">
        <input type="hidden" name="month" value="<?php echo htmlspecialchars($selectedMonthFull); ?>">
        
        <table class="salary-table">
            <thead>
                <tr>
                    <th rowspan="2" class="col-slno">S/L No</th>
                    <th rowspan="2" class="col-name">Employee Name</th>
                    <th rowspan="2" class="col-designation">Designation</th>
                    <th rowspan="2" class="col-type">Employee Type</th>
                    <th rowspan="2" class="col-category">Category</th>
                    <th rowspan="2" class="col-status">Status</th>
                    <th colspan="6" class="section-header">Employer Structure</th>
                    <th colspan="4" class="section-header">Attendence</th>
                    <th colspan="10" class="section-header">Earned Salary</th>
                    <th colspan="11" class="section-header">Rebill</th>
                </tr>
                <tr>
                    <!-- Employer Structure -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">VDA</th>
                    <th class="col-amount">Special<br>Allowance</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-total">Total<br>Earning</th>
                    
                    <!-- Attendance -->
                    <th class="col-attendance">P</th>
                    <th class="col-attendance">A</th>
                    <th class="col-attendance">W/O</th>
                    <th class="col-days">Pay Days</th>
                    
                    <!-- Earned Salary -->
                    <th class="col-amount">Basic</th>
                    <th class="col-amount">HRA</th>
                    <th class="col-amount">Other<br>Allowance</th>
                    <th class="col-amount">Spl<br>Allowance</th>
                    <th class="col-total">Total<br>Earning</th>
                    <th class="col-amount">PF</th>
                    <th class="col-amount">ESI</th>
                    <th class="col-amount">PT</th>
                    <th class="col-amount">Total<br>Deduction</th>
                    <th class="col-total">Net<br>Salary</th>
                    
                    <!-- Rebill -->
                    <th class="col-amount">Provident<br>Fund (12%)</th>
                    <th class="col-amount">ESIC (3.25%)</th>
                    <th class="col-amount">Leave</th>
                    <th class="col-amount">Holiday</th>
                    <th class="col-amount">Bonus</th>
                    <th class="col-amount">Uniform</th>
                    <th class="col-amount">Gratuity</th>
                    <th class="col-amount">Food<br>Allowance</th>
                    <th class="col-total">Total</th>
                    <th class="col-total">Earned<br>CTC</th>
                    <th class="col-amount">Per day<br>Wages</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $slNo = 1;
                foreach ($employees as $emp):
                    $empId = $emp['employee_id'];
                ?>
                <tr>
                    <td><?php echo $slNo++; ?></td>
                    <td style="text-align: left; padding-left: 5px;"><?php echo htmlspecialchars($emp['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($emp['designation_name'] ?? ''); ?></td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][employee_type]">
                            <option value="FTC" <?php echo ($emp['employee_type'] ?? '') === 'FTC' ? 'selected' : ''; ?>>FTC</option>
                            <option value="Regular" <?php echo ($emp['employee_type'] ?? '') === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                        </select>
                    </td>
                    <td>
                        <select name="employees[<?php echo $empId; ?>][category]">
                            <option value="Highly Skilled" <?php echo ($emp['category'] ?? '') === 'Highly Skilled' ? 'selected' : ''; ?>>Highly Skilled</option>
                            <option value="Skilled" <?php echo ($emp['category'] ?? '') === 'Skilled' ? 'selected' : ''; ?>>Skilled</option>
                            <option value="Semi Skilled" <?php echo ($emp['category'] ?? '') === 'Semi Skilled' ? 'selected' : ''; ?>>Semi Skilled</option>
                            <option value="Unskilled" <?php echo ($emp['category'] ?? '') === 'Unskilled' ? 'selected' : ''; ?>>Unskilled</option>
                        </select>
                    </td>
                    <td><?php echo ucfirst($emp['employment_status']); ?></td>
                    
                    <!-- Employer Structure -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][basic]" value="<?php echo $emp['basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][vda]" value="<?php echo $emp['vda'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][special_allowance]" value="<?php echo $emp['special_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][other_allowance]" value="<?php echo $emp['other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][hra]" value="<?php echo $emp['hra'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning]" value="<?php echo $emp['total_earning'] ?? 0; ?>" step="0.01" readonly style="background: #FFA500;"></td>
                    
                    <!-- Attendance -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][present]" value="<?php echo $emp['present'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][absent]" value="<?php echo $emp['absent'] ?? 0; ?>"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][weekly_off]" value="<?php echo $emp['weekly_off'] ?? 0; ?>"></td>
                    <td style="background: #90EE90;"><input type="number" name="employees[<?php echo $empId; ?>][pay_days]" value="<?php echo $emp['pay_days'] ?? 0; ?>" style="background: #90EE90;"></td>
                    
                    <!-- Earned Salary -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_basic]" value="<?php echo $emp['earned_basic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_hra]" value="<?php echo $emp['earned_hra'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][earned_other_allowance]" value="<?php echo $emp['earned_other_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][spl_allowance]" value="<?php echo $emp['spl_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_earning_earned]" value="<?php echo $emp['total_earning_earned'] ?? 0; ?>" step="0.01" style="background: #87CEEB;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pf]" value="<?php echo $emp['pf'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esi]" value="<?php echo $emp['esi'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][pt]" value="<?php echo $emp['pt'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][total_deduction]" value="<?php echo $emp['total_deduction'] ?? 0; ?>" step="0.01" readonly></td>
                    <td class="col-total" style="background: #4682B4; color: white;"><input type="number" name="employees[<?php echo $empId; ?>][net_salary]" value="<?php echo $emp['net_salary'] ?? 0; ?>" step="0.01" readonly style="background: #4682B4; color: white;"></td>
                    
                    <!-- Rebill -->
                    <td><input type="number" name="employees[<?php echo $empId; ?>][provident_fund]" value="<?php echo $emp['provident_fund'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][esic]" value="<?php echo $emp['esic'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][leave]" value="<?php echo $emp['leave_amount'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][holiday]" value="<?php echo $emp['holiday'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][bonus]" value="<?php echo $emp['bonus'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][uniform]" value="<?php echo $emp['uniform'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][gratuity]" value="<?php echo $emp['gratuity'] ?? 0; ?>" step="0.01"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][food_allowance]" value="<?php echo $emp['food_allowance'] ?? 0; ?>" step="0.01"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][total_rebill]" value="<?php echo $emp['total_rebill'] ?? 0; ?>" step="0.01" readonly style="background: #4169E1; color: white;"></td>
                    <td class="col-total"><input type="number" name="employees[<?php echo $empId; ?>][earned_ctc]" value="<?php echo $emp['earned_ctc'] ?? 0; ?>" step="0.01" readonly style="background: #00008B; color: white;"></td>
                    <td><input type="number" name="employees[<?php echo $empId; ?>][per_day_wages]" value="<?php echo $emp['per_day_wages'] ?? 0; ?>" step="0.01"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </form>
    
    <?php elseif ($periodExists && count($employees) == 0): ?>
        <div class="warning-box">
            <h3>⚠️ No Employees Found</h3>
            <p>There are no active employees for this period.</p>
        </div>
    <?php else: ?>
        <div class="warning-box">
            <h3>⚠️ Period Not Created</h3>
            <p>Please create a salary period for <strong><?php echo htmlspecialchars($selectedMonthFull); ?></strong> first.</p>
            <button type="button" class="btn btn-info" onclick="document.getElementById('newPeriodModal').style.display='block'" style="margin-top: 15px;">
                ➕ Create New Period
            </button>
        </div>
    <?php endif; ?>
    
    <!-- New Period Modal -->
    <div id="newPeriodModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">➕ Create New Salary Period</div>
            <form method="POST">
                <input type="hidden" name="create_new_period" value="1">
                
                <div class="form-group">
                    <label>Month:</label>
                    <select name="new_month" required>
                        <?php
                        $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                        foreach ($months as $month) {
                            echo "<option value='$month'>$month</option>";
                        }
                        ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Year:</label>
                    <input type="text" name="new_year" required placeholder="2025" maxlength="4" pattern="\d{4}">
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="document.getElementById('newPeriodModal').style.display='none'">Cancel</button>
                    <button type="submit" class="btn btn-success">✓ Create Period</button>
                </div>
            </form>
        </div>
    </div>
    
    <?php endif; // End of $tablesExist ?>
</div>

<script>
// Global export function
function exportSalaryData() {
    try {
        let month = '';
        const monthHidden = document.getElementById('selectedMonthFull');
        if (monthHidden && monthHidden.value) {
            month = monthHidden.value.trim();
        }
        if (!month) {
            const monthSelect = document.getElementById('monthSelect');
            const yearInput = document.getElementById('yearInput');
            if (monthSelect && yearInput) {
                let year = yearInput.value.trim();
                if (year.length === 2) year = '20' + year;
                if (year.length === 4) month = monthSelect.value + ' ' + year;
            }
        }
        if (!month) {
            alert('Unable to detect selected salary month. Please ensure a period is selected.');
            return;
        }
        let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('view_type')) url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
        if (urlParams.get('hr')) url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
        window.location.href = url;
    } catch (error) {
        alert('Export error: ' + error.message);
    }
}
function exportCSV() { exportSalaryData(); }

function updatePeriod() {
    const month = document.getElementById('monthSelect').value;
    let year = document.getElementById('yearInput').value.trim();
    
    // Convert 2-digit to 4-digit year
    if (year.length === 2) {
        year = '20' + year;
    } else if (year.length !== 4) {
        alert('Please enter a valid year (e.g., 25 or 2025)');
        return;
    }
    
    const yearShort = year.substr(-2);
    const monthShort = month.substr(0, 3);
    const period = monthShort + '-' + yearShort;
    
    window.location.href = '?m=' + encodeURIComponent(period) + '&y=' + yearShort;
}

// Auto-calculate totals
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('salary-form');
    if (!form) return;
    
    form.addEventListener('input', function(e) {
        const input = e.target;
        if (input.type === 'number') {
            const row = input.closest('tr');
            calculateRowTotals(row);
        }
    });
    
    function calculateRowTotals(row) {
        const inputs = row.querySelectorAll('input[type="number"]');
        const getName = (name) => {
            for (let input of inputs) {
                if (input.name.includes(name)) return input;
            }
            return null;
        };
        
        // Calculate Total Earning
        const basic = parseFloat(getName('basic')?.value || 0);
        const vda = parseFloat(getName('vda')?.value || 0);
        const special = parseFloat(getName('special_allowance')?.value || 0);
        const other = parseFloat(getName('other_allowance')?.value || 0);
        const hra = parseFloat(getName('hra')?.value || 0);
        
        const totalEarning = basic + vda + special + other + hra;
        const totalEarningInput = getName('total_earning');
        if (totalEarningInput) totalEarningInput.value = totalEarning.toFixed(2);
        
        // Calculate Total Deduction
        const pf = parseFloat(getName('pf')?.value || 0);
        const esi = parseFloat(getName('esi')?.value || 0);
        const pt = parseFloat(getName('pt')?.value || 0);
        
        const totalDeduction = pf + esi + pt;
        const totalDeductionInput = getName('total_deduction');
        if (totalDeductionInput) totalDeductionInput.value = totalDeduction.toFixed(2);
        
        // Calculate Net Salary
        const totalEarningEarned = parseFloat(getName('total_earning_earned')?.value || 0);
        const netSalary = totalEarningEarned - totalDeduction;
        const netSalaryInput = getName('net_salary');
        if (netSalaryInput) netSalaryInput.value = netSalary.toFixed(2);
        
        // Calculate Total Rebill
        const providentFund = parseFloat(getName('provident_fund')?.value || 0);
        const esicRebill = parseFloat(getName('esic')?.value || 0);
        const leave = parseFloat(getName('leave')?.value || 0);
        const holiday = parseFloat(getName('holiday')?.value || 0);
        const bonus = parseFloat(getName('bonus')?.value || 0);
        const uniform = parseFloat(getName('uniform')?.value || 0);
        const gratuity = parseFloat(getName('gratuity')?.value || 0);
        const foodAllowance = parseFloat(getName('food_allowance')?.value || 0);
        
        const totalRebill = providentFund + esicRebill + leave + holiday + bonus + uniform + gratuity + foodAllowance;
        const totalRebillInput = getName('total_rebill');
        if (totalRebillInput) totalRebillInput.value = totalRebill.toFixed(2);
        
        // Calculate Earned CTC
        const earnedCtc = totalEarningEarned + pf + esi + esicRebill + providentFund;
        const earnedCtcInput = getName('earned_ctc');
        if (earnedCtcInput) earnedCtcInput.value = earnedCtc.toFixed(2);
    }
    
    // Initial calculation
    document.querySelectorAll('.salary-table tbody tr').forEach(row => {
        calculateRowTotals(row);
    });
});

function exportCSV() {
    // Get month from hidden input (most reliable)
    let month = '';
    const monthHidden = document.getElementById('selectedMonthFull');
    if (monthHidden && monthHidden.value) {
        month = monthHidden.value.trim();
    }
    
    // Fallback 1: Try month header
    if (!month) {
        const monthLabelCell = document.querySelector('.month-header td:last-child');
        if (monthLabelCell) {
            month = monthLabelCell.textContent.trim();
        }
    }
    
    // Fallback 2: Try period status message
    if (!month) {
        const periodStatus = document.querySelector('.period-meta span, [style*="background: #e8f4fd"] span');
        if (periodStatus) {
            const text = periodStatus.textContent || '';
            const match = text.match(/(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}/);
            if (match) {
                month = match[0];
            }
        }
    }
    
    // Fallback 3: Try month + year controls
    if (!month) {
        const monthSelect = document.getElementById('monthSelect');
        const yearInput = document.getElementById('yearInput');
        if (monthSelect && yearInput) {
            let year = yearInput.value.trim();
            // Convert 2-digit to 4-digit year
            if (year.length === 2) {
                year = '20' + year;
            } else if (year.length !== 4) {
                alert('Invalid year format. Please enter a valid year.');
                return;
            }
            month = monthSelect.value + ' ' + year;
        }
    }
    
    if (!month) {
        alert('Unable to detect selected salary month to export. Please ensure a period is selected.');
        return;
    }
    
    // Build export URL
    let url = 'salary_export_excel.php?month=' + encodeURIComponent(month);
    
    // Pass view filters if present
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('view_type')) {
        url += '&view_type=' + encodeURIComponent(urlParams.get('view_type'));
    }
    if (urlParams.get('hr')) {
        url += '&hr=' + encodeURIComponent(urlParams.get('hr'));
    }
    
    // Navigate to export URL
    window.location.href = url;
}

// Close modal on outside click
window.onclick = function(event) {
    const modal = document.getElementById('newPeriodModal');
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>


