<?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'];
    $grossPay = $_POST['grossPay'];

    // Fetch phone number from employees table
    $phoneQuery = "SELECT `phone_number` FROM `employees` WHERE `employee_id` = ?";
    $phoneStmt = $conn->prepare($phoneQuery);
    if (!$phoneStmt) {
        // Handle prepare error
        die('Phone Query Prepare Error: ' . $conn->error);
    }

    $phoneStmt->bind_param("i", $employeeId);
    $phoneStmt->execute();
    $phoneResult = $phoneStmt->get_result();

    if (!$phoneResult) {
        // Handle execute error
        die('Phone Query Execute Error: ' . $phoneStmt->error);
    }

    $phoneRow = $phoneResult->fetch_assoc();
    $phoneNumber = $phoneRow['phone_number'];

    // Fetch additional data from employee_salary table
    $deductionQuery = "
        SELECT 
            `purpose` as `name`, 
            `salary` as `amount`
        FROM 
            `employee_salary` 
        WHERE 
            `phone_number` = ? 
            AND MONTH(`salary_date`) = MONTH(NOW())
    ";
    
    // Prepare and execute query
    $deductionStmt = $conn->prepare($deductionQuery);
    if (!$deductionStmt) {
        // Handle prepare error
        die('Deduction Query Prepare Error: ' . $conn->error);
    }

    $deductionStmt->bind_param("s", $phoneNumber);
    $deductionStmt->execute();
    $deductionResult = $deductionStmt->get_result();

    if (!$deductionResult) {
        // Handle execute error
        die('Deduction Query Execute Error: ' . $deductionStmt->error);
    }

    // Initialize an array to store deductions details
    $deductions = array();

    // Fetch deductions details
    while ($row = $deductionResult->fetch_assoc()) {
        $deductions[] = array(
            'name' => $row['name'],
            'amount' => (float) $row['amount']
        );
    }
    $deductionQuery = "SELECT SUM(salary) as totalDeduction FROM employee_salary WHERE phone_number= ? AND MONTH(salary_date) = MONTH(NOW())";
    
    // Prepare and execute query
    $deductionStmt = $conn->prepare($deductionQuery);
    if (!$deductionStmt) {
        // Handle prepare error
        die('Prepare Error: ' . $conn->error);
    }

    $deductionStmt->bind_param("i", $employeeId);
    $deductionStmt->execute();
    $deductionResult = $deductionStmt->get_result();

    if (!$deductionResult) {
        // Handle execute error
        die('Execute Error: ' . $deductionStmt->error);
    }

    $salaryDeductionRow = $deductionResult->fetch_assoc();
    $salaryDeductions = (float) $salaryDeductionRow['totalDeduction'];
    // Calculate NSSF Tier 1 (fixed amount)
    $nssfTier1 = 360; // Example NSSF Tier I deduction

    // Calculate NSSF Tier 2 based on rates
    $nssfTier2 = calculateNssfTier2($grossPay);

    // Calculate NHIF based on rates
    $nhif = calculateNhif($grossPay);

    // Calculate Housing Levy based on rate
    $housingLevy = calculateHousingLevy($grossPay);

    // Calculate PAYE before relief
    $payeBeforeRelief = calculatePayeBeforeRelief($grossPay);

    // Calculate dynamic relief (if any)
    $dynamicRelief = calculateDynamicRelief($grossPay);

    // Calculate PAYE after relief
    $payeAfterRelief = calculatePayeAfterRelief($payeBeforeRelief, $dynamicRelief);

    // Calculate total deductions
    $totalDeductions = $nssfTier1 + $nssfTier2 + $nhif + $housingLevy + $payeAfterRelief;

    // Calculate net pay
    $netPay = $grossPay - $totalDeductions -   $salaryDeductions;

    // Prepare response data
    $response = array(
        'grossPay' => $grossPay,
        'nssfTier1' => $nssfTier1,
        'nssfTier2' => $nssfTier2,
        'nhif' => $nhif,
        'housingLevy' => $housingLevy,
        'payeBeforeRelief' => $payeBeforeRelief,
        'dynamicRelief' => $dynamicRelief,
        'payeAfterRelief' => $payeAfterRelief,
        'totalDeductions' => $totalDeductions,
        'netPay' => $netPay,
        'name' => $_POST['name'],
        'deductions' => $deductions // Include deductions details in the response
    );

    // Return JSON response
    echo json_encode($response);
} else {
    // Return error for invalid request method
    http_response_code(405);
    echo json_encode(array('error' => 'Method Not Allowed'));
}

// Function definitions for calculations (example functions, implement as per your requirements)

function calculateNssfTier2($grossPay) {
    // Example function to calculate NSSF Tier 2
    return $grossPay * 0.06; // Example calculation
}

function calculateNhif($grossPay) {
    // Example function to calculate NHIF
    return 500; // Example NHIF amount
}

function calculateHousingLevy($grossPay) {
    // Example function to calculate Housing Levy
    return $grossPay * 0.01; // Example calculation
}

function calculatePayeBeforeRelief($grossPay) {
    // Example function to calculate PAYE before relief
    return $grossPay * 0.3; // Example calculation
}

function calculateDynamicRelief($grossPay) {
    // Example function to calculate dynamic relief
    return 2000; // Example dynamic relief amount
}

function calculatePayeAfterRelief($payeBeforeRelief, $dynamicRelief) {
    // Example function to calculate PAYE after relief
    return $payeBeforeRelief - $dynamicRelief; // Example calculation
}
?>
