<?php
// deductions.kts.php

// Include your database connection code
require 'shikanisha.kts.php';



header('Content-Type: application/json'); // Set content type to JSON


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve posted data
    $employeeId = $_POST['employeeId'];
    $name = $_POST['name'];
    $grossPay = $_POST['grossPay'];
    $nssfTier1 = $_POST['nssfTier1'];
    $nssfTier2 = $_POST['nssfTier2'];
    $nhif = $_POST['nhif'];
    $housingLevy = $_POST['housingLevy'];
    $payeBeforeRelief = $_POST['payeBeforeRelief'];
    $dynamicRelief = $_POST['dynamicRelief'];
    $payeAfterRelief = $_POST['payeAfterRelief'];
    $totalDeductions = $_POST['totalDeductions'];
    $netPay = $_POST['netPay'];
    $date = date('Y-m-d');
    // Retrieve other data as needed


    // Check if a record for the given $employeeId already exists in the same month
    $checkQuery = "SELECT COUNT(*) as recordCount FROM table_payslip WHERE employeeId = ? AND MONTH(date) = MONTH(NOW())";

    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bind_param("d", $employeeId);
    $checkStmt->execute();

    $result = $checkStmt->get_result();
    $recordCount = $result->fetch_assoc()['recordCount'];

 
  // If a record already exists, send an error response
    if ($recordCount > 0) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'A payslip for the current month has already been created for this employee']);
        exit;
    }

    // Insert data into the table
    $insertQuery = "INSERT INTO table_payslip (employeeId, name, grossPay, nssfTier1, nssfTier2, nhif, housingLevy, payeBeforeRelief, dynamicRelief, payeAfterRelief, totalDeductions, netPay, date) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

   

    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param("dsdddddddddds", $employeeId, $name, $grossPay, $nssfTier1, $nssfTier2, $nhif, $housingLevy, $payeBeforeRelief, $dynamicRelief, $payeAfterRelief, $totalDeductions, $netPay, $date);

    // Execute the statement
    $stmt->execute();

    // Close the statement
    $stmt->close();

    // Send a success response
    echo json_encode(['success' => true]);
} else {
    // Invalid request method
    http_response_code(405); // Method Not Allowed
    echo json_encode(['error' => 'Invalid request method']);
}

// Close the database connection
$conn->close();
?>
