<?php
// Check permission - only admins and managers can update salaries
$user_role = $_SESSION['role'] ?? 'employee';
$user_id = $_SESSION['user_id'] ?? null;

// Admin සහ Manager ට පමණක් access ලබා දෙන්න
if ($user_role !== 'admin' && !hasPermission('manage_salary')) {
    echo "<div class='alert alert-danger'><i class='bi bi-shield-exclamation'></i> Access Denied</div>";
    exit();
}

// Handle form submissions
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_salary'])) {
    $employee_id = $_POST['employee_id'];
    $new_salary = $_POST['new_salary'];
    $new_allowance = $_POST['new_allowance'] ?? 0;
    $effective_date = $_POST['effective_date'] ?? date('Y-m-d');
    $reason = $_POST['reason'] ?? '';
    $changed_by = $_SESSION['user_id'];
    
    try {
        $pdo->beginTransaction();
        
        // Get current salary and allowance
        $stmt = $pdo->prepare("SELECT salary, allowance, full_name FROM employees WHERE id = ?");
        $stmt->execute([$employee_id]);
        $employee = $stmt->fetch();
        
        if (!$employee) {
            throw new Exception("Employee not found!");
        }
        
        // Update salary and allowance
        $stmt = $pdo->prepare("UPDATE employees SET salary = ?, allowance = ? WHERE id = ?");
        $stmt->execute([$new_salary, $new_allowance, $employee_id]);
        
        // Record salary change history
        $stmt = $pdo->prepare("
            INSERT INTO salary_history 
            (employee_id, old_salary, new_salary, old_allowance, new_allowance, 
             changed_by, change_reason, effective_date) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $employee_id,
            $employee['salary'],
            $new_salary,
            $employee['allowance'],
            $new_allowance,
            $changed_by,
            $reason,
            $effective_date
        ]);
        
        $pdo->commit();
        
        $success = "Salary updated successfully for " . htmlspecialchars($employee['full_name']) . "!";
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Error updating salary: " . $e->getMessage();
    }
}

// Handle bulk salary update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_update'])) {
    $department = $_POST['department'];
    $salary_increase_type = $_POST['salary_increase_type'];
    $increase_value = $_POST['increase_value'];
    $effective_date = $_POST['effective_date'] ?? date('Y-m-d');
    $reason = $_POST['reason'] ?? 'Bulk salary adjustment';
    $changed_by = $_SESSION['user_id'];
    
    try {
        $pdo->beginTransaction();
        
        // Get employees based on department
        $sql = "SELECT id, salary, allowance, full_name FROM employees WHERE 1=1";
        $params = [];
        
        if ($department != 'all') {
            $sql .= " AND department = ?";
            $params[] = $department;
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $employees = $stmt->fetchAll();
        
        $updated_count = 0;
        
        foreach ($employees as $employee) {
            $old_salary = $employee['salary'];
            $old_allowance = $employee['allowance'];
            
            // Calculate new salary based on increase type
            if ($salary_increase_type == 'percentage') {
                $new_salary = $old_salary + ($old_salary * ($increase_value / 100));
                $new_allowance = $old_allowance + ($old_allowance * ($increase_value / 100));
            } else { // fixed amount
                $new_salary = $old_salary + $increase_value;
                $new_allowance = $old_allowance;
            }
            
            // Update employee
            $stmt = $pdo->prepare("UPDATE employees SET salary = ?, allowance = ? WHERE id = ?");
            $stmt->execute([$new_salary, $new_allowance, $employee['id']]);
            
            // Record history
            $stmt = $pdo->prepare("
                INSERT INTO salary_history 
                (employee_id, old_salary, new_salary, old_allowance, new_allowance, 
                 changed_by, change_reason, effective_date) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $employee['id'],
                $old_salary,
                $new_salary,
                $old_allowance,
                $new_allowance,
                $changed_by,
                $reason,
                $effective_date
            ]);
            
            $updated_count++;
        }
        
        $pdo->commit();
        
        $success = "Bulk update successful! Updated $updated_count employees.";
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Error in bulk update: " . $e->getMessage();
    }
}

// Get all employees for dropdown
$stmt = $pdo->query("SELECT id, full_name, department, salary, allowance FROM employees ORDER BY full_name");
$employees = $stmt->fetchAll();

// Get departments for filter
$dept_stmt = $pdo->query("SELECT DISTINCT department FROM employees WHERE department IS NOT NULL ORDER BY department");
$departments = $dept_stmt->fetchAll();

// Get salary history
$history_stmt = $pdo->prepare("
    SELECT sh.*, e.full_name as employee_name, u.username as changed_by_name 
    FROM salary_history sh
    JOIN employees e ON sh.employee_id = e.id
    JOIN users u ON sh.changed_by = u.id
    ORDER BY sh.changed_at DESC 
    LIMIT 20
");
$history_stmt->execute();
$salary_history = $history_stmt->fetchAll();

// Calculate salary statistics
$stats_stmt = $pdo->query("
    SELECT 
        COUNT(*) as total_employees,
        AVG(salary) as avg_salary,
        MIN(salary) as min_salary,
        MAX(salary) as max_salary,
        SUM(salary) as total_salary,
        AVG(allowance) as avg_allowance,
        SUM(allowance) as total_allowance
    FROM employees
");
$stats = $stats_stmt->fetch();
?>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-cash-coin me-2"></i>Salary Management</h5>
            </div>
            <div class="card-body">
                <?php if($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="bi bi-check-circle"></i> <?php echo $success; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="bi bi-exclamation-triangle"></i> <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <!-- Salary Statistics -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center">
                                <h6>Total Salary</h6>
                                <h4>Rs. <?php echo number_format($stats['total_salary'], 2); ?></h4>
                                <small>Monthly</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body text-center">
                                <h6>Average Salary</h6>
                                <h4>Rs. <?php echo number_format($stats['avg_salary'], 2); ?></h4>
                                <small>Per Employee</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body text-center">
                                <h6>Total Allowance</h6>
                                <h4>Rs. <?php echo number_format($stats['total_allowance'], 2); ?></h4>
                                <small>Monthly</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body text-center">
                                <h6>Total Employees</h6>
                                <h4><?php echo $stats['total_employees']; ?></h4>
                                <small>Active</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Tabs for Salary Management -->
                <ul class="nav nav-tabs mb-4" id="salaryTabs">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="tab" href="#individual">
                            <i class="bi bi-person"></i> Individual Update
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#bulk">
                            <i class="bi bi-people"></i> Bulk Update
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#history">
                            <i class="bi bi-clock-history"></i> Salary History
                        </a>
                    </li>
                </ul>
                
                <div class="tab-content">
                    <!-- Individual Salary Update Tab -->
                    <div class="tab-pane fade show active" id="individual">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0">Update Individual Salary</h6>
                                    </div>
                                    <div class="card-body">
                                        <form method="POST">
                                            <div class="mb-3">
                                                <label>Select Employee</label>
                                                <select name="employee_id" class="form-control select2" required 
                                                        onchange="loadEmployeeSalary(this.value)">
                                                    <option value="">Select Employee</option>
                                                    <?php foreach($employees as $emp): ?>
                                                    <option value="<?php echo $emp['id']; ?>" 
                                                            data-salary="<?php echo $emp['salary']; ?>"
                                                            data-allowance="<?php echo $emp['allowance']; ?>">
                                                        <?php echo htmlspecialchars($emp['full_name']) . ' - ' . $emp['department']; ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label>Current Salary (Rs.)</label>
                                                    <input type="text" id="current_salary" class="form-control" readonly>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label>Current Allowance (Rs.)</label>
                                                    <input type="text" id="current_allowance" class="form-control" readonly>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label>New Salary (Rs.) *</label>
                                                    <input type="number" name="new_salary" class="form-control" 
                                                           step="0.01" min="0" required placeholder="Enter new salary">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label>New Allowance (Rs.)</label>
                                                    <input type="number" name="new_allowance" class="form-control" 
                                                           step="0.01" min="0" placeholder="Enter new allowance">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label>Effective Date</label>
                                                    <input type="date" name="effective_date" class="form-control" 
                                                           value="<?php echo date('Y-m-d'); ?>">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label>Change Percentage</label>
                                                    <input type="text" id="change_percentage" class="form-control" readonly>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label>Reason for Change</label>
                                                <textarea name="reason" class="form-control" rows="3" 
                                                          placeholder="Enter reason for salary change..."></textarea>
                                            </div>
                                            
                                            <button type="submit" name="update_salary" class="btn btn-primary">
                                                <i class="bi bi-save"></i> Update Salary
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0">Salary Summary</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Employee</th>
                                                        <th>Department</th>
                                                        <th>Salary</th>
                                                        <th>Allowance</th>
                                                        <th>Total</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach($employees as $emp): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($emp['full_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($emp['department']); ?></td>
                                                        <td>Rs. <?php echo number_format($emp['salary'], 2); ?></td>
                                                        <td>Rs. <?php echo number_format($emp['allowance'], 2); ?></td>
                                                        <td>Rs. <?php echo number_format($emp['salary'] + $emp['allowance'], 2); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bulk Salary Update Tab -->
                    <div class="tab-pane fade" id="bulk">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">Bulk Salary Update</h6>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label>Select Department</label>
                                            <select name="department" class="form-control">
                                                <option value="all">All Departments</option>
                                                <?php foreach($departments as $dept): ?>
                                                <option value="<?php echo htmlspecialchars($dept['department']); ?>">
                                                    <?php echo htmlspecialchars($dept['department']); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Increase Type</label>
                                            <select name="salary_increase_type" class="form-control" id="increaseType">
                                                <option value="percentage">Percentage Increase</option>
                                                <option value="fixed">Fixed Amount Increase</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Increase Value</label>
                                            <div class="input-group">
                                                <input type="number" name="increase_value" class="form-control" 
                                                       step="0.01" min="0" required placeholder="Enter value">
                                                <span class="input-group-text" id="valueSuffix">%</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label>Effective Date</label>
                                            <input type="date" name="effective_date" class="form-control" 
                                                   value="<?php echo date('Y-m-d'); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label>Estimated Impact</label>
                                            <div class="alert alert-info p-2" id="estimatedImpact">
                                                Select department to see impact
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label>Reason for Bulk Update</label>
                                        <textarea name="reason" class="form-control" rows="3" required 
                                                  placeholder="Enter reason for bulk salary update..."></textarea>
                                    </div>
                                    
                                    <button type="submit" name="bulk_update" class="btn btn-warning"
                                            onclick="return confirm('Are you sure you want to update salaries for all selected employees?')">
                                        <i class="bi bi-arrow-up"></i> Apply Bulk Update
                                    </button>
                                </form>
                                
                                <hr class="my-4">
                                
                                <h6>Preview of Selected Employees</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm" id="bulkPreview">
                                        <thead>
                                            <tr>
                                                <th>Employee</th>
                                                <th>Department</th>
                                                <th>Current Salary</th>
                                                <th>New Salary</th>
                                                <th>Increase</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Will be populated by JavaScript -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Salary History Tab -->
                    <div class="tab-pane fade" id="history">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">Salary Change History</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Employee</th>
                                                <th>Old Salary</th>
                                                <th>New Salary</th>
                                                <th>Change</th>
                                                <th>Changed By</th>
                                                <th>Reason</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if(empty($salary_history)): ?>
                                            <tr>
                                                <td colspan="7" class="text-center">No salary history found</td>
                                            </tr>
                                            <?php else: ?>
                                            <?php foreach($salary_history as $history): 
                                                $salary_change = $history['new_salary'] - $history['old_salary'];
                                                $percentage = $history['old_salary'] > 0 ? 
                                                    round(($salary_change / $history['old_salary']) * 100, 2) : 0;
                                            ?>
                                            <tr>
                                                <td><?php echo date('Y-m-d', strtotime($history['changed_at'])); ?></td>
                                                <td><?php echo htmlspecialchars($history['employee_name']); ?></td>
                                                <td>Rs. <?php echo number_format($history['old_salary'], 2); ?></td>
                                                <td>Rs. <?php echo number_format($history['new_salary'], 2); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $salary_change >= 0 ? 'success' : 'danger'; ?>">
                                                        Rs. <?php echo number_format($salary_change, 2); ?>
                                                        (<?php echo $percentage; ?>%)
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars($history['changed_by_name']); ?></td>
                                                <td><?php echo htmlspecialchars($history['change_reason']); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Include Select2 for better dropdowns -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
// Initialize Select2
$(document).ready(function() {
    $('.select2').select2({
        width: '100%'
    });
});

// Load employee salary when selected
function loadEmployeeSalary(employeeId) {
    if (!employeeId) return;
    
    const selectedOption = document.querySelector(`option[value="${employeeId}"]`);
    if (selectedOption) {
        const currentSalary = selectedOption.getAttribute('data-salary') || '0';
        const currentAllowance = selectedOption.getAttribute('data-allowance') || '0';
        
        document.getElementById('current_salary').value = 'Rs. ' + parseFloat(currentSalary).toFixed(2);
        document.getElementById('current_allowance').value = 'Rs. ' + parseFloat(currentAllowance).toFixed(2);
        
        // Calculate percentage change when new salary is entered
        const newSalaryInput = document.querySelector('input[name="new_salary"]');
        newSalaryInput.addEventListener('input', function() {
            const newSalary = parseFloat(this.value) || 0;
            const oldSalary = parseFloat(currentSalary) || 0;
            
            if (oldSalary > 0) {
                const percentage = ((newSalary - oldSalary) / oldSalary) * 100;
                document.getElementById('change_percentage').value = percentage.toFixed(2) + '%';
            }
        });
    }
}

// Handle bulk update preview
document.addEventListener('DOMContentLoaded', function() {
    const increaseType = document.getElementById('increaseType');
    const valueSuffix = document.getElementById('valueSuffix');
    const departmentSelect = document.querySelector('select[name="department"]');
    const increaseValue = document.querySelector('input[name="increase_value"]');
    
    // Update suffix based on increase type
    increaseType.addEventListener('change', function() {
        valueSuffix.textContent = this.value === 'percentage' ? '%' : 'Rs.';
        updateBulkPreview();
    });
    
    // Update preview when department or value changes
    departmentSelect.addEventListener('change', updateBulkPreview);
    increaseValue.addEventListener('input', updateBulkPreview);
    
    // Initial preview update
    updateBulkPreview();
});

function updateBulkPreview() {
    const department = document.querySelector('select[name="department"]').value;
    const increaseType = document.getElementById('increaseType').value;
    const increaseValue = parseFloat(document.querySelector('input[name="increase_value"]').value) || 0;
    
    // Get employees for selected department
    fetch('ajax/get_employees_by_department.php?department=' + encodeURIComponent(department))
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const tableBody = document.querySelector('#bulkPreview tbody');
                tableBody.innerHTML = '';
                
                let totalIncrease = 0;
                
                data.employees.forEach(employee => {
                    const oldSalary = parseFloat(employee.salary);
                    let newSalary;
                    
                    if (increaseType === 'percentage') {
                        newSalary = oldSalary + (oldSalary * (increaseValue / 100));
                    } else {
                        newSalary = oldSalary + increaseValue;
                    }
                    
                    const increaseAmount = newSalary - oldSalary;
                    totalIncrease += increaseAmount;
                    
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${employee.full_name}</td>
                        <td>${employee.department}</td>
                        <td>Rs. ${oldSalary.toFixed(2)}</td>
                        <td>Rs. ${newSalary.toFixed(2)}</td>
                        <td class="${increaseAmount >= 0 ? 'text-success' : 'text-danger'}">
                            Rs. ${increaseAmount.toFixed(2)}
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
                
                // Update estimated impact
                const impactDiv = document.getElementById('estimatedImpact');
                impactDiv.innerHTML = `
                    <strong>Estimated Monthly Impact:</strong><br>
                    Total Increase: Rs. ${totalIncrease.toFixed(2)}<br>
                    Affected Employees: ${data.employees.length}
                `;
            }
        });
}
</script>