<?php
// admin/employee-salaries.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$emp_filter = isset($_GET['emp']) ? intval($_GET['emp']) : 0;
$month_filter = isset($_GET['month']) ? $_GET['month'] : date('Y-m');

// Get employees for dropdown
$employees = $pdo->query("SELECT id, first_name, last_name, base_salary, allowance, bonus 
                          FROM employees WHERE status = 1 ORDER BY first_name")->fetchAll();

// Handle Add Salary
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_salary'])) {
    $employee_id = intval($_POST['employee_id'] ?? 0);
    $month = $_POST['month'] ?? date('Y-m');
    $base_salary = floatval($_POST['base_salary'] ?? 0);
    $allowance = floatval($_POST['allowance'] ?? 0);
    $bonus = floatval($_POST['bonus'] ?? 0);
    $deduction = floatval($_POST['deduction'] ?? 0);
    $net_salary = $base_salary + $allowance + $bonus - $deduction;
    $payment_date = $_POST['payment_date'] ?? null;
    $payment_method = sanitize($_POST['payment_method'] ?? 'cash');
    $transaction_no = sanitize($_POST['transaction_no'] ?? '');
    $status = sanitize($_POST['status'] ?? 'draft');
    $note = sanitize($_POST['note'] ?? '');

    if ($employee_id > 0) {
        try {
            // Convert month to first day of month for storage
            $month_date = $month . '-01';
            
            $stmt = $pdo->prepare("INSERT INTO employee_salaries 
                (employee_id, month, base_salary, allowance, bonus, deduction, net_salary, 
                 payment_date, payment_method, transaction_no, status, note, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $employee_id, $month_date, $base_salary, $allowance, $bonus, $deduction, $net_salary,
                $payment_date, $payment_method, $transaction_no, $status, $note, $_SESSION['admin_id']
            ]);

            $_SESSION['success_msg'] = 'Salary record added successfully!';
            header('Location: employee-salaries.php');
            exit;
        } catch (Exception $e) {
            $_SESSION['error_msg'] = 'Error: ' . $e->getMessage();
        }
    }
}

// Get all salaries (no filter first to check if data exists)
$stmt_all = $pdo->query("SELECT s.*, e.first_name, e.last_name 
                         FROM employee_salaries s 
                         LEFT JOIN employees e ON s.employee_id = e.id 
                         ORDER BY s.created_at DESC");
$all_salaries = $stmt_all->fetchAll();

// Build the query for salaries with filters
$sql = "SELECT s.*, e.first_name, e.last_name 
        FROM employee_salaries s 
        LEFT JOIN employees e ON s.employee_id = e.id 
        WHERE 1=1";
$params = [];

if ($emp_filter > 0) {
    $sql .= " AND s.employee_id = ?";
    $params[] = $emp_filter;
}

if (!empty($month_filter)) {
    $sql .= " AND DATE_FORMAT(s.month, '%Y-%m') = ?";
    $params[] = $month_filter;
}

$sql .= " ORDER BY s.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$filtered_salaries = $stmt->fetchAll();

// Use filtered or all salaries for display
$salaries = !empty($filtered_salaries) ? $filtered_salaries : $all_salaries;

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include 'header.php';
?>

<style>
.salary-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.stat-box {
    background: #fff;
    border-radius: 10px;
    padding: 15px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.stat-box .stat-number {
    font-size: 24px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 12px;
    color: #64748b;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.draft { background: #e2e8f0; color: #475569; }
.status-badge.paid { background: #86efac; color: #166534; }
.status-badge.pending { background: #fcd34d; color: #92400e; }

.salary-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.salary-card .card-title {
    font-weight: 600;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f5f9;
}

.alert-container {
    margin-bottom: 20px;
}

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.employee-avatar-sm {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #047dc3;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 12px;
    flex-shrink: 0;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-money-bill-wave me-2"></i> Employee Salaries</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#salaryModal">
            <i class="fa-solid fa-plus"></i> Add Salary
        </button>
    </div>

    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>

    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo $success_msg; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo $error_msg; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Filter -->
    <div class="salary-card">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Employee</label>
                <select name="emp" class="form-control" onchange="this.form.submit()">
                    <option value="">All Employees</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['id']; ?>" <?php echo $emp['id'] == $emp_filter ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Month</label>
                <input type="month" name="month" class="form-control" value="<?php echo $month_filter; ?>" onchange="this.form.submit()">
            </div>
            <div class="col-md-5 d-flex align-items-end">
                <a href="employee-salaries.php" class="btn btn-secondary">Clear Filter</a>
            </div>
        </form>
    </div>

    <!-- Stats -->
    <?php
    $total_salary = 0; 
    $paid_salary = 0; 
    $pending_salary = 0;
    $total_records = count($salaries);
    
    foreach ($salaries as $s) {
        $total_salary += $s['net_salary'];
        if ($s['status'] == 'paid') {
            $paid_salary += $s['net_salary'];
        } else {
            $pending_salary += $s['net_salary'];
        }
    }
    ?>
    <div class="salary-stats">
        <div class="stat-box">
            <div class="stat-number text-primary"><?php echo number_format($total_salary); ?> TK</div>
            <div class="stat-label">Total Salary</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-success"><?php echo number_format($paid_salary); ?> TK</div>
            <div class="stat-label">Paid</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-warning"><?php echo number_format($pending_salary); ?> TK</div>
            <div class="stat-label">Pending</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-info"><?php echo $total_records; ?></div>
            <div class="stat-label">Total Records</div>
        </div>
    </div>

    <!-- Salary Table -->
    <div class="salary-card">
        <h5 class="card-title">Salary Records (<?php echo $total_records; ?>)</h5>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Employee</th>
                        <th>Month</th>
                        <th>Base Salary</th>
                        <th>Allowance</th>
                        <th>Bonus</th>
                        <th>Deduction</th>
                        <th>Net Salary</th>
                        <th>Payment Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($salaries)): ?>
                    <tr>
                        <td colspan="10" class="text-center py-4">
                            <i class="fa-regular fa-money-bill-1 fa-2x text-muted d-block mb-2"></i>
                            No salary records found
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($salaries as $salary): ?>
                    <tr id="salaryRow_<?php echo $salary['id']; ?>">
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <div class="employee-avatar-sm">
                                    <?php echo strtoupper(substr($salary['first_name'] ?? 'U', 0, 1)); ?>
                                </div>
                                <strong><?php echo htmlspecialchars($salary['first_name'] . ' ' . $salary['last_name']); ?></strong>
                            </div>
                        </td>
                        <td><?php echo date('M Y', strtotime($salary['month'])); ?></td>
                        <td><?php echo number_format($salary['base_salary']); ?> TK</td>
                        <td><?php echo number_format($salary['allowance']); ?> TK</td>
                        <td><?php echo number_format($salary['bonus']); ?> TK</td>
                        <td class="text-danger"><?php echo number_format($salary['deduction']); ?> TK</td>
                        <td class="fw-bold text-success"><?php echo number_format($salary['net_salary']); ?> TK</td>
                        <td><?php echo $salary['payment_date'] ? date('d M Y', strtotime($salary['payment_date'])) : '-'; ?></td>
                        <td>
                            <span class="status-badge <?php echo $salary['status']; ?>">
                                <?php echo ucfirst($salary['status']); ?>
                            </span>
                        </td>
                        <td>
    <div class="action-btns">
        <a href="edit-salary.php?id=<?php echo $salary['id']; ?>" class="btn btn-sm btn-warning">
            <i class="fa-solid fa-edit"></i>
        </a>
        <button onclick="deleteSalary(<?php echo $salary['id']; ?>)" class="btn btn-sm btn-danger">
            <i class="fa-solid fa-trash"></i>
        </button>
    </div>
</td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Salary Modal -->
<!-- In admin/employee-salaries.php - Update the Add Salary Modal -->
<div class="modal fade" id="salaryModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-plus-circle me-2"></i> Add Salary Record</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="salaryForm">
                <input type="hidden" name="add_salary" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Employee <span class="text-danger">*</span></label>
                                <select name="employee_id" class="form-control" required>
                                    <option value="">Select Employee</option>
                                    <?php foreach ($employees as $emp): ?>
                                    <option value="<?php echo $emp['id']; ?>">
                                        <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Month <span class="text-danger">*</span></label>
                                <input type="month" name="month" class="form-control" value="<?php echo date('Y-m'); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Base Salary</label>
                                <input type="number" name="base_salary" class="form-control" step="0.01" value="0">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Allowance</label>
                                <input type="number" name="allowance" class="form-control" step="0.01" value="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Bonus</label>
                                <input type="number" name="bonus" class="form-control" step="0.01" value="0">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Deduction <span class="text-danger">*</span></label>
                                <input type="number" name="deduction" id="deductionInput" class="form-control" step="0.01" value="0" required>
                                <small class="text-muted text-danger">
                                    <i class="fa-solid fa-info-circle"></i> 
                                    Auto-calculated from unexcused absences and unapproved leaves
                                </small>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Date</label>
                                <input type="date" name="payment_date" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Method</label>
                                <select name="payment_method" class="form-control">
                                    <option value="cash">Cash</option>
                                    <option value="bank">Bank Transfer</option>
                                    <option value="mobile_banking">Mobile Banking</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Transaction No</label>
                                <input type="text" name="transaction_no" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-control">
                                    <option value="draft">Draft</option>
                                    <option value="pending">Pending</option>
                                    <option value="paid">Paid</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Note</label>
                                <textarea name="note" class="form-control" rows="2"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa-solid fa-save"></i> Save Salary
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ========================================
// DELETE SALARY
// ========================================
function deleteSalary(id) {
    if (!confirm('Are you sure you want to delete this salary record?')) return;
    
    var formData = new FormData();
    formData.append('delete_id', id);
    
    fetch('delete-salary.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('salaryRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() { row.remove(); }, 500);
            }
            showAlert('success', 'Salary record deleted successfully!');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showAlert('danger', data.message || 'Failed to delete');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', 'Something went wrong');
    });
}

// ========================================
// EDIT SALARY (Placeholder)
// ========================================
function editSalary(id) {
    showAlert('info', 'Edit functionality coming soon!');
}

// ========================================
// SHOW ALERT
// ========================================
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : (type === 'info' ? 'alert-info' : 'alert-danger');
    var icon = type === 'success' ? 'fa-check-circle' : (type === 'info' ? 'fa-info-circle' : 'fa-exclamation-circle');
    
    alertContainer.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() { alert.remove(); }, 500);
        }
    }, 5000);
}

// ========================================
// AUTO HIDE ALERTS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
    
    // Add CSS animation
    var style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0%); opacity: 1; }
        }
    `;
    document.head.appendChild(style);
});

// ========================================
// FORM SUBMIT - Auto calculate net salary
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var form = document.getElementById('salaryForm');
    if (form) {
        var inputs = form.querySelectorAll('input[name="base_salary"], input[name="allowance"], input[name="bonus"], input[name="deduction"]');
        inputs.forEach(function(input) {
            input.addEventListener('input', function() {
                // Optional: Auto calculate net salary
                var base = parseFloat(form.querySelector('input[name="base_salary"]').value) || 0;
                var allowance = parseFloat(form.querySelector('input[name="allowance"]').value) || 0;
                var bonus = parseFloat(form.querySelector('input[name="bonus"]').value) || 0;
                var deduction = parseFloat(form.querySelector('input[name="deduction"]').value) || 0;
                var net = base + allowance + bonus - deduction;
                // You can display net salary in a label if needed
            });
        });
    }
});


// ========================================
// AUTO CALCULATE DEDUCTION FROM ATTENDANCE
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var employeeSelect = document.querySelector('select[name="employee_id"]');
    var monthInput = document.querySelector('input[name="month"]');
    var deductionInput = document.querySelector('input[name="deduction"]');
    var baseSalaryInput = document.querySelector('input[name="base_salary"]');
    var allowanceInput = document.querySelector('input[name="allowance"]');
    var bonusInput = document.querySelector('input[name="bonus"]');
    
    function fetchDeduction() {
        var employeeId = employeeSelect ? employeeSelect.value : 0;
        var month = monthInput ? monthInput.value : '';
        
        if (employeeId > 0 && month) {
            // Show loading
            if (deductionInput) {
                deductionInput.disabled = true;
                deductionInput.placeholder = 'Calculating...';
            }
            
            fetch('get-salary-deduction.php?employee_id=' + employeeId + '&month=' + month)
                .then(response => response.json())
                .then(data => {
                    console.log('Deduction Data:', data);
                    
                    if (deductionInput) {
                        deductionInput.disabled = false;
                        if (data.deduction_amount !== undefined) {
                            deductionInput.value = data.deduction_amount;
                            // Show deduction details
                            showDeductionDetails(data);
                        } else if (data.error) {
                            deductionInput.value = 0;
                            showDeductionError(data.error);
                        }
                    }
                    
                    // Auto set base salary if available
                    if (baseSalaryInput && data.base_salary) {
                        baseSalaryInput.value = data.base_salary;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    if (deductionInput) {
                        deductionInput.disabled = false;
                        deductionInput.value = 0;
                    }
                });
        } else {
            if (deductionInput) {
                deductionInput.value = 0;
                deductionInput.disabled = false;
                hideDeductionDetails();
            }
        }
    }
    
    function showDeductionDetails(data) {
        // Remove existing details
        hideDeductionDetails();
        
        if (data.deduction_amount > 0 || data.unexcused_absences > 0) {
            var detailsHtml = `
                <div id="deductionDetails" class="mt-2 p-3 bg-light rounded">
                    <h6 class="mb-2">Attendance Summary for ${data.month}</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <small><strong>Working Days:</strong> ${data.working_days}</small><br>
                            <small><strong>Present Days:</strong> ${data.present_days}</small><br>
                            <small><strong>Leave Days:</strong> ${data.leave_days}</small>
                        </div>
                        <div class="col-md-6">
                            <small><strong>Unexcused Absences:</strong> <span class="text-danger">${data.unexcused_absences}</span></small><br>
                            <small><strong>Unapproved Leaves:</strong> <span class="text-danger">${data.unapproved_leaves}</span></small><br>
                            <small><strong>Daily Salary:</strong> ${data.daily_salary.toFixed(2)} TK</small>
                        </div>
                    </div>
                    <hr class="my-2">
                    <div class="d-flex justify-content-between">
                        <strong>Total Deduction:</strong>
                        <strong class="text-danger">${data.deduction_amount.toFixed(2)} TK</strong>
                    </div>
                    ${data.absence_details && data.absence_details.length > 0 ? `
                        <small class="text-muted d-block mt-2">
                            <i class="fa-solid fa-info-circle"></i> 
                            Deducted for: ${data.absence_details.map(a => a.date).join(', ')}
                        </small>
                    ` : ''}
                </div>
            `;
            
            var formGroup = document.querySelector('.col-md-6 .mb-3:last-child');
            if (formGroup) {
                formGroup.insertAdjacentHTML('afterend', detailsHtml);
            }
        }
    }
    
    function hideDeductionDetails() {
        var details = document.getElementById('deductionDetails');
        if (details) {
            details.remove();
        }
    }
    
    function showDeductionError(message) {
        hideDeductionDetails();
        var formGroup = document.querySelector('.col-md-6 .mb-3:last-child');
        if (formGroup) {
            var errorHtml = `
                <div id="deductionDetails" class="mt-2 p-2 bg-danger bg-opacity-10 text-danger rounded">
                    <small><i class="fa-solid fa-exclamation-triangle"></i> ${message}</small>
                </div>
            `;
            formGroup.insertAdjacentHTML('afterend', errorHtml);
        }
    }
    
    // Event listeners
    if (employeeSelect) {
        employeeSelect.addEventListener('change', fetchDeduction);
    }
    if (monthInput) {
        monthInput.addEventListener('change', fetchDeduction);
    }
    
    // Initial load if both values are set
    if (employeeSelect && monthInput && employeeSelect.value && monthInput.value) {
        setTimeout(fetchDeduction, 500);
    }
    
    // Also trigger on modal show
    var modalElement = document.getElementById('salaryModal');
    if (modalElement) {
        modalElement.addEventListener('shown.bs.modal', function() {
            if (employeeSelect && monthInput && employeeSelect.value && monthInput.value) {
                fetchDeduction();
            }
        });
    }
});
</script>

<?php include 'footer.php'; ?>