<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_monir_final";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get data from form
$employee_id = $_POST['employee_id'];
$month = $_POST['month'];
$paid_salary = $_POST['paid_salary'];

// Fetch the full salary of the employee
$sql_salary = "SELECT full_salary FROM employee_details WHERE EmployeeId = $employee_id";
$result = $conn->query($sql_salary);
$full_salary = 0;
if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();
    $full_salary = $data['full_salary'];
}

// Check if record exists
$sql_check = "SELECT * FROM salaries WHERE employee_id = $employee_id AND month = '$month'";
$result = $conn->query($sql_check);

if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();
    echo $paid_s = $data['paid_salary']+$paid_salary;
    // Update existing record
    $sql = "UPDATE salaries SET paid_salary = '$paid_s' 
            WHERE employee_id = $employee_id AND month = '$month'";
                    $dddd = date("Y-m-d");
                    mysqli_query($conn,"INSERT INTO transactions (date, description, credit, debit, balance, EmployeeId) 
                    VALUES ('$dddd', 'Teach. salary pay', '0', '$paid_salary', '$paid_salary', '$employee_id')");
		 
    //echo "Salary updated successfully!";
} else {
    // Insert new record
    $sql = "INSERT INTO salaries (employee_id, month, full_salary, paid_salary) 
            VALUES ($employee_id, '$month', $full_salary, $paid_salary)";
    $dddd = date("Y-m-d");
    mysqli_query($conn,"INSERT INTO transactions (date, description, credit, debit, balance, EmployeeId) 
    VALUES ('$dddd', 'Teach. salary pay', '0', '$paid_salary', '$paid_salary', '$employee_id')");
		 
    //echo "Salary added successfully!";
}

if ($conn->query($sql) === TRUE) {
    echo "";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
