<?php
include('../config/dbcon.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $salaryActuals = $_POST["salaryActuals"];
    $salaryBudgeted = $_POST["salaryBudgeted"];
    $fixedCostActuals = $_POST["fixedCostActuals"];
    $fixedCostBudgeted = $_POST["fixedCostBudgeted"];

    // Validate and sanitize the input if needed

    // Calculate the 1st day of the previous month
    $firstDayOfPreviousMonth = date('Y-m-d', strtotime('first day of last month'));

    // Check if records already exist for the given date
    $checkExistingRecordsQuery = "SELECT COUNT(*) AS recordCount FROM salaries WHERE month = '$firstDayOfPreviousMonth'";
    $existingRecordsResult = mysqli_query($conn, $checkExistingRecordsQuery);

    if (!$existingRecordsResult) {
        die("Query failed: " . mysqli_error($conn));
    }

    $existingRecordsCount = mysqli_fetch_assoc($existingRecordsResult)['recordCount'];

    if ($existingRecordsCount > 0) {
        // Records already exist for the given date, update instead of insert
        $updateSalaryQuery = "UPDATE salaries SET";
        $updateFixedCostQuery = "UPDATE fixed_cost SET";

        // Check and include non-empty values in the update queries
        if (!empty($salaryActuals)) {
            $updateSalaryQuery .= " cum_salary = $salaryActuals,";
        }
        if (!empty($salaryBudgeted)) {
            $updateSalaryQuery .= " budget_salary = $salaryBudgeted,";
        }
        if (!empty($fixedCostActuals)) {
            $updateFixedCostQuery .= " cum_fixed_cost = $fixedCostActuals,";
        }
        if (!empty($fixedCostBudgeted)) {
            $updateFixedCostQuery .= " budget_fixed_cost = $fixedCostBudgeted,";
        }

        // Remove trailing commas
        $updateSalaryQuery = rtrim($updateSalaryQuery, ',');
        $updateFixedCostQuery = rtrim($updateFixedCostQuery, ',');

        // Complete the WHERE clause
        $updateSalaryQuery .= " WHERE month = '$firstDayOfPreviousMonth'";
        $updateFixedCostQuery .= " WHERE month = '$firstDayOfPreviousMonth'";

        $resultUpdateSalary = mysqli_query($conn, $updateSalaryQuery);
        $resultUpdateFixedCost = mysqli_query($conn, $updateFixedCostQuery);

        // Check if the update queries were successful
        if ($resultUpdateSalary && $resultUpdateFixedCost) {
            // Redirect back to the costing page
            header("Location: costing.php");
            exit();
        } else {
            echo "Error updating records: " . mysqli_error($conn);
        }
    } else {
        // Records do not exist, insert new records
        $insertSalaryQuery = "INSERT INTO salaries (month";
        $insertFixedCostQuery = "INSERT INTO fixed_cost (month";

        // Include non-empty values in the insert queries
        if (!empty($salaryActuals)) {
            $insertSalaryQuery .= ", cum_salary";
        }
        if (!empty($salaryBudgeted)) {
            $insertSalaryQuery .= ", budget_salary";
        }
        if (!empty($fixedCostActuals)) {
            $insertFixedCostQuery .= ", cum_fixed_cost";
        }
        if (!empty($fixedCostBudgeted)) {
            $insertFixedCostQuery .= ", budget_fixed_cost";
        }

        // Complete the column list
        $insertSalaryQuery .= ") VALUES ('$firstDayOfPreviousMonth'";
        $insertFixedCostQuery .= ") VALUES ('$firstDayOfPreviousMonth'";

        // Include non-empty values in the values part of the insert queries
        if (!empty($salaryActuals)) {
            $insertSalaryQuery .= ", $salaryActuals";
        }
        if (!empty($salaryBudgeted)) {
            $insertSalaryQuery .= ", $salaryBudgeted";
        }
        if (!empty($fixedCostActuals)) {
            $insertFixedCostQuery .= ", $fixedCostActuals";
        }
        if (!empty($fixedCostBudgeted)) {
            $insertFixedCostQuery .= ", $fixedCostBudgeted";
        }

        $insertSalaryQuery .= ")";
        $insertFixedCostQuery .= ")";

        $resultInsertSalary = mysqli_query($conn, $insertSalaryQuery);
        $resultInsertFixedCost = mysqli_query($conn, $insertFixedCostQuery);

        // Check if the insert queries were successful
        if ($resultInsertSalary && $resultInsertFixedCost) {
            // Redirect back to the costing page
            header("Location: costing.php");
            exit();
        } else {
            echo "Error inserting records: " . mysqli_error($conn);
        }
    }

    // Close the database connection if needed
    mysqli_close($conn);
} else {
    // Redirect or handle the case where the form was not submitted via POST
    echo "Invalid request method.";
}
?>