<?php
// admin/edit-salary.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

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

$id = intval($_GET['id'] ?? 0);
if (!$id) {
    header('Location: employee-salaries.php');
    exit;
}

// Get salary record
$stmt = $pdo->prepare("SELECT s.*, e.first_name, e.last_name 
                       FROM employee_salaries s 
                       LEFT JOIN employees e ON s.employee_id = e.id 
                       WHERE s.id = ?");
$stmt->execute([$id]);
$salary = $stmt->fetch();

if (!$salary) {
    header('Location: employee-salaries.php');
    exit;
}

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

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_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 {
            $month_date = $month . '-01';
            
            $stmt = $pdo->prepare("UPDATE employee_salaries SET 
                employee_id = ?, month = ?, base_salary = ?, allowance = ?, bonus = ?, 
                deduction = ?, net_salary = ?, payment_date = ?, payment_method = ?, 
                transaction_no = ?, status = ?, note = ? 
                WHERE id = ?");
            $stmt->execute([
                $employee_id, $month_date, $base_salary, $allowance, $bonus, 
                $deduction, $net_salary, $payment_date, $payment_method, 
                $transaction_no, $status, $note, $id
            ]);

            $_SESSION['success_msg'] = 'Salary record updated successfully!';
            header('Location: employee-salaries.php');
            exit;
        } catch (Exception $e) {
            $error = 'Error: ' . $e->getMessage();
        }
    } else {
        $error = 'Please select an employee';
    }
}

include 'header.php';
?>

<style>
.edit-salary-card {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.edit-salary-card .card-title {
    font-weight: 600;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #e2e8f0;
}

.salary-info-box {
    background: #f8fafc;
    border-radius: 8px;
    padding: 12px 15px;
    margin-bottom: 20px;
}

.salary-info-box .label {
    color: #64748b;
    font-weight: 500;
    font-size: 13px;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-edit me-2"></i> Edit Salary Record</h2>
        <div>
            <a href="employee-salaries.php" class="btn btn-secondary">
                <i class="fa-solid fa-arrow-left"></i> Back
            </a>
        </div>
    </div>

    <?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <div class="edit-salary-card">
        <h5 class="card-title">
            <i class="fa-solid fa-money-bill-wave me-2"></i> 
            Edit Salary - <?php echo htmlspecialchars($salary['first_name'] . ' ' . $salary['last_name']); ?>
        </h5>

        <!-- Current Info -->
        <div class="salary-info-box">
            <div class="row">
                <div class="col-md-3">
                    <span class="label">Salary ID:</span> #<?php echo $salary['id']; ?>
                </div>
                <div class="col-md-3">
                    <span class="label">Created:</span> <?php echo date('d M Y', strtotime($salary['created_at'])); ?>
                </div>
                <div class="col-md-3">
                    <span class="label">Current Status:</span> 
                    <span class="badge bg-<?php echo $salary['status'] == 'paid' ? 'success' : ($salary['status'] == 'pending' ? 'warning' : 'secondary'); ?>">
                        <?php echo ucfirst($salary['status']); ?>
                    </span>
                </div>
                <div class="col-md-3">
                    <span class="label">Net Salary:</span> 
                    <strong class="text-success"><?php echo number_format($salary['net_salary']); ?> TK</strong>
                </div>
            </div>
        </div>

        <form method="POST">
            <input type="hidden" name="edit_salary" value="1">
            <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 $emp['id'] == $salary['employee_id'] ? 'selected' : ''; ?>>
                                <?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', strtotime($salary['month'])); ?>" 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="<?php echo $salary['base_salary']; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Allowance</label>
                        <input type="number" name="allowance" class="form-control" step="0.01" value="<?php echo $salary['allowance']; ?>">
                    </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="<?php echo $salary['bonus']; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Deduction</label>
                        <input type="number" name="deduction" class="form-control" step="0.01" value="<?php echo $salary['deduction']; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Net Salary</label>
                        <input type="text" class="form-control" value="<?php echo number_format($salary['net_salary']); ?> TK" disabled>
                        <small class="text-muted">Calculated automatically: Base + Allowance + Bonus - Deduction</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Payment Date</label>
                        <input type="date" name="payment_date" class="form-control" value="<?php echo $salary['payment_date']; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <option value="cash" <?php echo $salary['payment_method'] == 'cash' ? 'selected' : ''; ?>>Cash</option>
                            <option value="bank" <?php echo $salary['payment_method'] == 'bank' ? 'selected' : ''; ?>>Bank Transfer</option>
                            <option value="mobile_banking" <?php echo $salary['payment_method'] == 'mobile_banking' ? 'selected' : ''; ?>>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" value="<?php echo htmlspecialchars($salary['transaction_no']); ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="draft" <?php echo $salary['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                            <option value="pending" <?php echo $salary['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="paid" <?php echo $salary['status'] == 'paid' ? 'selected' : ''; ?>>Paid</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"><?php echo htmlspecialchars($salary['note']); ?></textarea>
                    </div>
                </div>
            </div>

            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="fa-solid fa-save"></i> Update Salary
                </button>
                <a href="employee-salaries.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
// Auto calculate net salary
document.addEventListener('DOMContentLoaded', function() {
    var baseInput = document.querySelector('input[name="base_salary"]');
    var allowanceInput = document.querySelector('input[name="allowance"]');
    var bonusInput = document.querySelector('input[name="bonus"]');
    var deductionInput = document.querySelector('input[name="deduction"]');
    var netDisplay = document.querySelector('input[value*="TK"]');
    
    function calculateNet() {
        var base = parseFloat(baseInput.value) || 0;
        var allowance = parseFloat(allowanceInput.value) || 0;
        var bonus = parseFloat(bonusInput.value) || 0;
        var deduction = parseFloat(deductionInput.value) || 0;
        var net = base + allowance + bonus - deduction;
        
        if (netDisplay) {
            netDisplay.value = net.toFixed(2) + ' TK';
        }
    }
    
    if (baseInput && allowanceInput && bonusInput && deductionInput) {
        [baseInput, allowanceInput, bonusInput, deductionInput].forEach(function(input) {
            input.addEventListener('input', calculateNet);
        });
    }
});
</script>

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