<?php
session_start();
include 'config.php';

// Check login
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// Get and validate month/year
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

if ($month < 1 || $month > 12) $month = date('m');
if ($year < 2000 || $year > 2100) $year = date('Y');

// Handle form submission (bulk update/insert)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $employee_data = $_POST['employees'] ?? [];

    foreach ($employee_data as $emp_id => $data) {
        $emp_id = (int)$emp_id;

        // Sanitize and cast
        $employee_name = trim($data['employee_name']);
        $basic_salary = (float)$data['basic_salary'];
        $hra = (float)$data['hra'];
        $other_allowance = (float)$data['other_allowance'];
        $total_gross_salary = (float)$data['total_gross_salary'];
        $it = (float)$data['it'];
        $pt = (float)$data['pt'];
        $pf = (float)$data['pf'];
        $vpf = (float)$data['vpf'];
        $esi = (float)$data['esi'];
        $loan_principal = (float)$data['loan_principal'];
        $loan_interest = (float)$data['loan_interest'];
        $salary_advance = (float)$data['salary_advance'];
        $late_hours = (float)$data['late_hours'];
        $unpaid_leave = (float)$data['unpaid_leave'];
        $other_deductions = (float)$data['other_deductions'];
        $total_deductions = (float)$data['total_deductions'];
        $net_earnings = (float)$data['net_earnings'];
        $office_working_days = (int)$data['office_working_days'];
        $no_of_absent = (int)$data['no_of_absent'];
        $no_of_present = (int)$data['no_of_present'];
        $unpaid_leave_difference = (float)$data['unpaid_leave_difference'];
        $released = (int)$data['released'];

        // Check if record exists
        $check_query = "SELECT payroll_id FROM payroll_records WHERE employee_id = ? AND month = ? AND year = ?";
        $check_stmt = mysqli_prepare($conn, $check_query);
        mysqli_stmt_bind_param($check_stmt, "iii", $emp_id, $month, $year);
        mysqli_stmt_execute($check_stmt);
        $exists = mysqli_stmt_get_result($check_stmt);
        $record_exists = mysqli_fetch_assoc($exists);
        mysqli_stmt_close($check_stmt);

        if ($record_exists) {
            // Update
            $update_query = "UPDATE payroll_records SET
                employee_name = ?, basic_salary = ?, hra = ?, other_allowance = ?, total_gross_salary = ?,
                it = ?, pt = ?, pf = ?, vpf = ?, esi = ?, loan_principal = ?, loan_interest = ?,
                salary_advance = ?, late_hours = ?, unpaid_leave = ?, other_deductions = ?,
                total_deductions = ?, net_earnings = ?, office_working_days = ?, no_of_absent = ?,
                no_of_present = ?, unpaid_leave_difference = ?, released = ?, updated_at = CURRENT_TIMESTAMP
                WHERE employee_id = ? AND month = ? AND year = ?";

            $stmt = mysqli_prepare($conn, $update_query);
            mysqli_stmt_bind_param($stmt, "sddddddddddddddddiiiiii",
                $employee_name, $basic_salary, $hra, $other_allowance, $total_gross_salary,
                $it, $pt, $pf, $vpf, $esi, $loan_principal, $loan_interest,
                $salary_advance, $late_hours, $unpaid_leave, $other_deductions,
                $total_deductions, $net_earnings, $office_working_days, $no_of_absent,
                $no_of_present, $unpaid_leave_difference, $released,
                $emp_id, $month, $year
            );
        } else {
            // Insert
            $insert_query = "INSERT INTO payroll_records (
                employee_id, employee_name, basic_salary, hra, other_allowance, total_gross_salary,
                it, pt, pf, vpf, esi, loan_principal, loan_interest, salary_advance, late_hours,
                unpaid_leave, other_deductions, total_deductions, net_earnings, office_working_days,
                no_of_absent, no_of_present, unpaid_leave_difference, month, year, released, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";

            $stmt = mysqli_prepare($conn, $insert_query);
            mysqli_stmt_bind_param($stmt, "isdddddddddddddddiiiiiii",
                $emp_id, $employee_name, $basic_salary, $hra, $other_allowance, $total_gross_salary,
                $it, $pt, $pf, $vpf, $esi, $loan_principal, $loan_interest,
                $salary_advance, $late_hours, $unpaid_leave, $other_deductions,
                $total_deductions, $net_earnings, $office_working_days, $no_of_absent,
                $no_of_present, $unpaid_leave_difference, $month, $year, $released
            );
        }

        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
    }

    // Redirect after save
    header("Location: payroll_dashboard.php?month=$month&year=$year&success=1");
    exit();
}

// Fetch all employees
$users_query = "SELECT id, first_name, last_name FROM users WHERE role = 'employee' ORDER BY first_name";
$users_result = mysqli_query($conn, $users_query);

// Fetch existing payroll records for this month/year
$payroll_records = [];
$payroll_query = "SELECT * FROM payroll_records WHERE month = ? AND year = ?";
$payroll_stmt = mysqli_prepare($conn, $payroll_query);
mysqli_stmt_bind_param($payroll_stmt, "ii", $month, $year);
mysqli_stmt_execute($payroll_stmt);
$payroll_result = mysqli_stmt_get_result($payroll_stmt);
while ($row = mysqli_fetch_assoc($payroll_result)) {
    $payroll_records[$row['employee_id']] = $row;
}
mysqli_stmt_close($payroll_stmt);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bulk Edit Payroll - <?= date('F Y', mktime(0,0,0,$month,1,$year)) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .table input, .table select { font-size: 0.9rem; }
        .table th { font-size: 0.85rem; vertical-align: middle; }
        .table td { padding: 0.4rem; }
        .sticky-col { position: sticky; left: 0; background: #f8f9fa; z-index: 1; }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2>Bulk Edit Payroll - <?= date('F Y', mktime(0,0,0,$month,1,$year)) ?></h2>
        <form method="POST" action="">
            <div class="table-responsive">
                <table class="table table-bordered table-sm align-middle">
                    <thead class="table-light">
                        <tr>
                            <th class="sticky-col">Employee</th>
                            <th>Basic</th>
                            <th>HRA</th>
                            <th>Other Allow.</th>
                            <th>Gross</th>
                            <th>IT</th>
                            <th>PT</th>
                            <th>PF</th>
                            <th>VPF</th>
                            <th>ESI</th>
                            <th>Loan P.</th>
                            <th>Loan I.</th>
                            <th>Adv.</th>
                            <th>Late Hrs</th>
                            <th>Unpaid Lv</th>
                            <th>Other Ded.</th>
                            <th>Total Ded.</th>
                            <th>Net</th>
                            <th>Work Days</th>
                            <th>Absent</th>
                            <th>Present</th>
                            <th>Unpaid Diff</th>
                            <th>Released</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($user = mysqli_fetch_assoc($users_result)): 
                            $emp_id = $user['id'];
                            $name = $user['first_name'] . ' ' . $user['last_name'];
                            $pr = $payroll_records[$emp_id] ?? [];
                        ?>
                        <tr>
                            <td class="sticky-col fw-bold">
                                <input type="hidden" name="employees[<?= $emp_id ?>][employee_name]" value="<?= htmlspecialchars($name) ?>">
                                <?= htmlspecialchars($name) ?>
                            </td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][basic_salary]" value="<?= $pr['basic_salary'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][hra]" value="<?= $pr['hra'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][other_allowance]" value="<?= $pr['other_allowance'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][total_gross_salary]" value="<?= $pr['total_gross_salary'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][it]" value="<?= $pr['it'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][pt]" value="<?= $pr['pt'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][pf]" value="<?= $pr['pf'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][vpf]" value="<?= $pr['vpf'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][esi]" value="<?= $pr['esi'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][loan_principal]" value="<?= $pr['loan_principal'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][loan_interest]" value="<?= $pr['loan_interest'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][salary_advance]" value="<?= $pr['salary_advance'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][late_hours]" value="<?= $pr['late_hours'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][unpaid_leave]" value="<?= $pr['unpaid_leave'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][other_deductions]" value="<?= $pr['other_deductions'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][total_deductions]" value="<?= $pr['total_deductions'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][net_earnings]" value="<?= $pr['net_earnings'] ?? 0 ?>"></td>
                            <td><input type="number" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][office_working_days]" value="<?= $pr['office_working_days'] ?? 0 ?>"></td>
                            <td><input type="number" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][no_of_absent]" value="<?= $pr['no_of_absent'] ?? 0 ?>"></td>
                            <td><input type="number" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][no_of_present]" value="<?= $pr['no_of_present'] ?? 0 ?>"></td>
                            <td><input type="number" step="0.01" class="form-control form-control-sm" name="employees[<?= $emp_id ?>][unpaid_leave_difference]" value="<?= $pr['unpaid_leave_difference'] ?? 0 ?>"></td>
                            <td>
                                <select class="form-select form-select-sm" name="employees[<?= $emp_id ?>][released]">
                                    <option value="0" <?= (!isset($pr['released']) || $pr['released'] == 0) ? 'selected' : '' ?>>No</option>
                                    <option value="1" <?= (isset($pr['released']) && $pr['released'] == 1) ? 'selected' : '' ?>>Yes</option>
                                </select>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
            <div class="mt-3">
                <button type="submit" class="btn btn-success btn-lg">Save All Payroll Records</button>
                <a href="payroll_dashboard.php?month=<?= $month ?>&year=<?= $year ?>" class="btn btn-secondary btn-lg">Cancel</a>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>