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

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

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

// Validate parameters
if ($month < 1 || $month > 12) {
    $month = date('m');
}
if ($year < 2000 || $year > 2100) {
    $year = date('Y');
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 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);
    $check_result = mysqli_stmt_get_result($check_stmt);
    $record_exists = mysqli_fetch_assoc($check_result);
    mysqli_stmt_close($check_stmt);

    if ($record_exists) {
        // Update existing record
        $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);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "sdddddddddddddddiiiiii", 
                $_POST['employee_name'],
                $_POST['basic_salary'],
                $_POST['hra'],
                $_POST['other_allowance'],
                $_POST['total_gross_salary'],
                $_POST['it'],
                $_POST['pt'],
                $_POST['pf'],
                $_POST['vpf'],
                $_POST['esi'],
                $_POST['loan_principal'],
                $_POST['loan_interest'],
                $_POST['salary_advance'],
                $_POST['late_hours'],
                $_POST['unpaid_leave'],
                $_POST['other_deductions'],
                $_POST['total_deductions'],
                $_POST['net_earnings'],
                $_POST['office_working_days'],
                $_POST['no_of_absent'],
                $_POST['no_of_present'],
                $_POST['unpaid_leave_difference'],
                $_POST['released'],
                $emp_id,
                $month,
                $year
            );

            if (mysqli_stmt_execute($stmt)) {
                header("Location: payroll_dashboard.php?month=$month&year=$year");
                exit();
            } else {
                echo "Error updating payroll: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "Prepare failed: " . mysqli_error($conn);
        }
    } else {
        // Insert new record
        $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);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "isdddddddddddddddiiiiii", 
                $emp_id,
                $_POST['employee_name'],
                $_POST['basic_salary'],
                $_POST['hra'],
                $_POST['other_allowance'],
                $_POST['total_gross_salary'],
                $_POST['it'],
                $_POST['pt'],
                $_POST['pf'],
                $_POST['vpf'],
                $_POST['esi'],
                $_POST['loan_principal'],
                $_POST['loan_interest'],
                $_POST['salary_advance'],
                $_POST['late_hours'],
                $_POST['unpaid_leave'],
                $_POST['other_deductions'],
                $_POST['total_deductions'],
                $_POST['net_earnings'],
                $_POST['office_working_days'],
                $_POST['no_of_absent'],
                $_POST['no_of_present'],
                $_POST['unpaid_leave_difference'],
                $month,
                $year,
                $_POST['released']
            );

            if (mysqli_stmt_execute($stmt)) {
                header("Location: payroll_dashboard.php?month=$month&year=$year");
                exit();
            } else {
                echo "Error inserting payroll: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "Prepare failed: " . mysqli_error($conn);
        }
    }
}

// Fetch existing payroll data
$query = "SELECT * FROM payroll_records WHERE employee_id = ? AND month = ? AND year = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "iii", $emp_id, $month, $year);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$payroll = mysqli_fetch_assoc($result) ?: [];
mysqli_stmt_close($stmt);

// Fetch employee details
$emp_query = "SELECT first_name, last_name FROM users WHERE id = ?";
$emp_stmt = mysqli_prepare($conn, $emp_query);
mysqli_stmt_bind_param($emp_stmt, "i", $emp_id);
mysqli_stmt_execute($emp_stmt);
$emp_result = mysqli_stmt_get_result($emp_stmt);
$employee = mysqli_fetch_assoc($emp_result) ?: ['first_name' => '', 'last_name' => ''];
mysqli_stmt_close($emp_stmt);

// Set employee name
$employee_name = $employee['first_name'] . ' ' . $employee['last_name'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Payroll</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h1>Edit Payroll for <?php echo htmlspecialchars($employee_name); ?></h1>
        <form method="POST" action="">
            <input type="hidden" name="month" value="<?php echo $month; ?>">
            <input type="hidden" name="year" value="<?php echo $year; ?>">
            <div class="mb-3">
                <label for="employee_name" class="form-label">Employee Name</label>
                <input type="text" name="employee_name" class="form-control" value="<?php echo htmlspecialchars($payroll['employee_name'] ?? $employee_name); ?>">
            </div>
            <div class="mb-3">
                <label for="basic_salary" class="form-label">Basic Salary</label>
                <input type="number" step="0.01" name="basic_salary" class="form-control" value="<?php echo htmlspecialchars($payroll['basic_salary'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="hra" class="form-label">HRA</label>
                <input type="number" step="0.01" name="hra" class="form-control" value="<?php echo htmlspecialchars($payroll['hra'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="other_allowance" class="form-label">Other Allowance</label>
                <input type="number" step="0.01" name="other_allowance" class="form-control" value="<?php echo htmlspecialchars($payroll['other_allowance'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="total_gross_salary" class="form-label">Total Gross Salary</label>
                <input type="number" step="0.01" name="total_gross_salary" class="form-control" value="<?php echo htmlspecialchars($payroll['total_gross_salary'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="it" class="form-label">Income Tax (IT)</label>
                <input type="number" step="0.01" name="it" class="form-control" value="<?php echo htmlspecialchars($payroll['it'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="pt" class="form-label">Professional Tax (PT)</label>
                <input type="number" step="0.01" name="pt" class="form-control" value="<?php echo htmlspecialchars($payroll['pt'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="pf" class="form-label">Provident Fund (PF)</label>
                <input type="number" step="0.01" name="pf" class="form-control" value="<?php echo htmlspecialchars($payroll['pf'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="vpf" class="form-label">Voluntary Provident Fund (VPF)</label>
                <input type="number" step="0.01" name="vpf" class="form-control" value="<?php echo htmlspecialchars($payroll['vpf'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="esi" class="form-label">ESI</label>
                <input type="number" step="0.01" name="esi" class="form-control" value="<?php echo htmlspecialchars($payroll['esi'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="loan_principal" class="form-label">Loan Principal</label>
                <input type="number" step="0.01" name="loan_principal" class="form-control" value="<?php echo htmlspecialchars($payroll['loan_principal'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="loan_interest" class="form-label">Loan Interest</label>
                <input type="number" step="0.01" name="loan_interest" class="form-control" value="<?php echo htmlspecialchars($payroll['loan_interest'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="salary_advance" class="form-label">Salary Advance</label>
                <input type="number" step="0.01" name="salary_advance" class="form-control" value="<?php echo htmlspecialchars($payroll['salary_advance'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="late_hours" class="form-label">Late Hours</label>
                <input type="number" step="0.01" name="late_hours" class="form-control" value="<?php echo htmlspecialchars($payroll['late_hours'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="unpaid_leave" class="form-label">Unpaid Leave</label>
                <input type="number" step="0.01" name="unpaid_leave" class="form-control" value="<?php echo htmlspecialchars($payroll['unpaid_leave'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="other_deductions" class="form-label">Other Deductions</label>
                <input type="number" step="0.01" name="other_deductions" class="form-control" value="<?php echo htmlspecialchars($payroll['other_deductions'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="total_deductions" class="form-label">Total Deductions</label>
                <input type="number" step="0.01" name="total_deductions" class="form-control" value="<?php echo htmlspecialchars($payroll['total_deductions'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="net_earnings" class="form-label">Net Earnings</label>
                <input type="number" step="0.01" name="net_earnings" class="form-control" value="<?php echo htmlspecialchars($payroll['net_earnings'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="office_working_days" class="form-label">Office Working Days</label>
                <input type="number" name="office_working_days" class="form-control" value="<?php echo htmlspecialchars($payroll['office_working_days'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="no_of_absent" class="form-label">Number of Days Absent</label>
                <input type="number" name="no_of_absent" class="form-control" value="<?php echo htmlspecialchars($payroll['no_of_absent'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="no_of_present" class="form-label">Number of Days Present</label>
                <input type="number" name="no_of_present" class="form-control" value="<?php echo htmlspecialchars($payroll['no_of_present'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="unpaid_leave_difference" class="form-label">Unpaid Leave Difference</label>
                <input type="number" step="0.01" name="unpaid_leave_difference" class="form-control" value="<?php echo htmlspecialchars($payroll['unpaid_leave_difference'] ?? 0); ?>">
            </div>
            <div class="mb-3">
                <label for="released" class="form-label">Released</label>
                <select name="released" class="form-control">
                    <option value="0" <?php echo (isset($payroll['released']) && $payroll['released'] == 0) ? 'selected' : ''; ?>>No</option>
                    <option value="1" <?php echo (isset($payroll['released']) && $payroll['released'] == 1) ? 'selected' : ''; ?>>Yes</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
            <a href="payroll_dashboard.php?month=<?php echo $month; ?>&year=<?php echo $year; ?>" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>