<?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 ALL active employees (not just those with salary records)
    $employees = [];
    if ($periodExists) {
        // First, get all active employees
        $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.employment_type,
                e.employee_category,
                ess.basic_salary,
                ess.vda,
                ess.special_allowance,
                ess.other_allowance,
                ess.hra
            FROM employees e
            LEFT JOIN designations d ON e.designation_id = d.designation_id
            LEFT JOIN employee_salary_structure ess ON e.employee_id = ess.employee_id AND ess.structure_status = 'active'
            WHERE e.site_id = ? AND e.employment_status = 'active'
            ORDER BY e.employee_code
        ");
        $stmt->execute([$siteId]);
        $allEmployees = $stmt->fetchAll();
        
        // Get existing salary register data
        $salaryStmt = $db->prepare("
            SELECT * FROM salary_register 
            WHERE salary_month = ? AND site_id = ?
        ");
        $salaryStmt->execute([$selectedMonthFull, $siteId]);
        $salaryData = $salaryStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Create a map of employee_id => salary_data
        $salaryMap = [];
        foreach ($salaryData as $sal) {
            $salaryMap[$sal['employee_id']] = $sal;
        }
        
        // Merge employee data with salary data, auto-creating records if needed
        foreach ($allEmployees as $emp) {
            $empId = $emp['employee_id'];
            
            if (isset($salaryMap[$empId])) {
                // Merge existing salary data
                $employees[] = array_merge($emp, $salaryMap[$empId]);
            } else {
                // Create new salary record structure with default values from employee_salary_structure
                $employees[] = array_merge($emp, [
                    'basic' => $emp['basic_salary'] ?? 0,
                    'vda' => $emp['vda'] ?? 0,
                    'special_allowance' => $emp['special_allowance'] ?? 0,
                    'other_allowance' => $emp['other_allowance'] ?? 0,
                    'hra' => $emp['hra'] ?? 0,
                    'total_earning' => ($emp['basic_salary'] ?? 0) + ($emp['vda'] ?? 0) + ($emp['special_allowance'] ?? 0) + ($emp['other_allowance'] ?? 0) + ($emp['hra'] ?? 0),
                    'present' => 0,
                    'absent' => 0,
                    'weekly_off' => 0,
                    'pay_days' => 0,
                    'earned_basic' => 0,
                    'earned_hra' => 0,
                    'earned_other_allowance' => 0,
                    'spl_allowance' => 0,
                    'total_earning_earned' => 0,
                    'pf' => 0,
                    'esi' => 0,
                    'pt' => 0,
                    'total_deduction' => 0,
                    'net_salary' => 0,
                    'provident_fund' => 0,
                    'esic' => 0,
                    'leave_amount' => 0,
                    'holiday' => 0,
                    'bonus' => 0,
                    'uniform' => 0,
                    'gratuity' => 0,
                    'food_allowance' => 0,
                    'total_rebill' => 0,
                    'earned_ctc' => 0,
                    'per_day_wages' => 0,
                    'employee_type' => $emp['employment_type'] ?? 'FTC',
                    'category' => $emp['employee_category'] ?? 'Skilled'
                ]);
                
                // Auto-create salary_register record in database
                try {
                    $insertStmt = $db->prepare("
                        INSERT INTO salary_register 
                        (site_id, employee_id, salary_month, employee_type, category,
                         basic, vda, special_allowance, other_allowance, hra, total_earning)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $insertStmt->execute([
                        $siteId, $empId, $selectedMonthFull,
                        $emp['employment_type'] ?? 'FTC',
                        $emp['employee_category'] ?? 'Skilled',
                        $emp['basic_salary'] ?? 0,
                        $emp['vda'] ?? 0,
                        $emp['special_allowance'] ?? 0,
                        $emp['other_allowance'] ?? 0,
                        $emp['hra'] ?? 0,
                        ($emp['basic_salary'] ?? 0) + ($emp['vda'] ?? 0) + ($emp['special_allowance'] ?? 0) + ($emp['other_allowance'] ?? 0) + ($emp['hra'] ?? 0)
                    ]);
                } catch (Exception $e) {
                    // Record might already exist, continue
                    error_log("Auto-create salary record error: " . $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: 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="exportCSV()">
                📥 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>
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() {
    alert('CSV export feature coming soon!');
}

// 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'; ?>
