<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
require_once "../config.php";

$emp_id = $_SESSION['emp_id'];
$user_name = $_SESSION['user_name'];
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'];



// for internship data
if(isset($_POST['basicSalaryTitle'])){

    $employee_id = mysqli_real_escape_string($db, !empty($_POST['employee_id']) ? $_POST['employee_id'] : $_POST['ex_employee_id']);
    $joining_date = mysqli_real_escape_string($db, $_POST['salary_joining_date']);
    $revisionDate = !empty($_POST['revisionDate']) ? mysqli_real_escape_string($db, $_POST['revisionDate']) : '';

    $ctcYearly = 0;
    $netPayableYearly = 0;

    $basicSalaryTitle = $_POST['basicSalaryTitle'];
    $basicSalaryYearly = $_POST['basicSalaryYearly'];
    foreach ($_POST['basicSalaryTitle'] as $key => $value) {

        $title = mysqli_real_escape_string($db, $value);
        $yearly_amount = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['basicSalaryYearly'][$key]));

        $fixedJson = json_encode([['title' => $title, 'yearly_amount' => $yearly_amount]]);
        $add_onJson = json_encode([]);
        $deductionJson = json_encode([]);
        $ctcYearly = $yearly_amount;
        $netPayableYearly = $yearly_amount;

        $od = mysqli_query($db, "UPDATE employee_salary set revision_end_date='$revisionDate' where employee_id='$employee_id' order by id desc limit 1");
        if (!$od) {
            echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
            exit();
        }

        // store this in employee_salary and also store revision date as joining date incremented by 1 month
        $q = mysqli_query($db, "INSERT INTO employee_salary (employee_id, ctc, net_payable, fixed, add_on, deduction, revision_start_date, revision_end_date) VALUES ('$employee_id', '$ctcYearly', '$netPayableYearly', '$fixedJson', '$add_onJson', '$deductionJson', '$revisionDate', '')");
        $revisionDate = date('Y-m-d', strtotime(($revisionDate==''?$joining_date:$revisionDate) . ' +1 month'));
        if(!$q) {
            echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
            exit();
        }
    }
    echo json_encode(["status" => 200, 'message' => 'Internship Salary Added Successfully !']);
    exit();
}



// from addSalary.php
if (isset($_POST['addSalary'])) {

    $employee_id = mysqli_real_escape_string($db, $_POST['employee_id']);

    $ctcYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['ctcYearly']));
    $netPayableYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['netPayableYearly']));

    $revisionDate = mysqli_real_escape_string($db, $_POST['revisionDate']);


    $fixedTitle = $_POST['fixedTitle'];
    $fixedYearly = $_POST['fixedYearly'];
    $fixedJson = [];
    if (is_array($_POST['fixedTitle']) && is_array($_POST['fixedYearly'])) {
        foreach ($_POST['fixedTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['fixedYearly'][$key]) && $_POST['fixedYearly'][$key] != '') {
                $fixedJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['fixedYearly'][$key])];
                
                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Fixed' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Fixed', '$value') ");
                }
            }
        }
    }
    $fixedJson = mysqli_real_escape_string($db, json_encode($fixedJson));

    $addOnTitle = $_POST['addOnTitle'];
    $addOnYearly = $_POST['addOnYearly'];
    $addOnJson = [];
    if (is_array($_POST['addOnTitle']) && is_array($_POST['addOnYearly'])) {
        foreach ($_POST['addOnTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['addOnYearly'][$key]) && $_POST['addOnYearly'][$key] != '') {
                $addOnJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['addOnYearly'][$key])];

                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Add On' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Add On', '$value') ");
                }
            }
        }
    }
    $addOnJson = mysqli_real_escape_string($db, json_encode($addOnJson));

    $deductionTitle = $_POST['deductionTitle'];
    $deductionYearly = $_POST['deductionYearly'];
    $deductionJson = [];
    if (is_array($_POST['deductionTitle']) && is_array($_POST['deductionYearly'])) {
        foreach ($_POST['deductionTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['deductionYearly'][$key]) && $_POST['deductionYearly'][$key] != '') {
                $deductionJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['deductionYearly'][$key])];

                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Deduction' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Deduction', '$value') ");
                }
            }
        }
    }
    $deductionJson = mysqli_real_escape_string($db, json_encode($deductionJson));


    $salaryCount = mysqli_num_rows(mysqli_query($db, "SELECT * from employee_salary where employee_id='$employee_id' "));
    if ($salaryCount > 0 && $revisionDate == '') {
        echo json_encode(["status" => 500, 'message' => "$employee_id This employee salary already exist. if you want to add Salary please fill revision date !"]);
    } else if ($salaryCount == 0 && $revisionDate != '') {
        echo json_encode(["status" => 500, 'message' => "$employee_id This employee salary add first time so please, leave the revision date empty !"]);
    } else {

        $od = mysqli_query($db, "UPDATE employee_salary set revision_end_date='$revisionDate' where employee_id='$employee_id' order by id desc limit 1");

        if ($od) {

            $q = mysqli_query($db, "INSERT INTO `employee_salary` (`employee_id`, `ctc`, `net_payable`, `fixed`, `add_on`, `deduction`, `revision_start_date`, `revision_end_date`) VALUES ('$employee_id', '$ctcYearly', '$netPayableYearly', '$fixedJson', '$addOnJson', '$deductionJson', '$revisionDate', '') ");

            if ($q) {
                echo json_encode(["status" => 200, 'message' => 'Salary Added Successfully !']);
            } else {
                echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
            }
        } else {
            echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
        }
    }
    exit();
}

// from addSalary.php
if (isset($_POST['updateSalary'])) {

    $edit_id = mysqli_real_escape_string($db, $_POST['edit_id']);
    $employee_id = mysqli_real_escape_string($db, $_POST['ex_employee_id']);
    
    $ctcYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['ctcYearly']));
    $netPayableYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['netPayableYearly']));

    $revisionDate = mysqli_real_escape_string($db, $_POST['revisionDate']);
    
    $revisionOldDate = mysqli_real_escape_string($db, $_POST['revisionOldDate']);


    $fixedTitle = $_POST['fixedTitle'];
    $fixedYearly = $_POST['fixedYearly'];
    $fixedJson = [];
    if (is_array($_POST['fixedTitle']) && is_array($_POST['fixedYearly'])) {
        foreach ($_POST['fixedTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['fixedYearly'][$key]) && $_POST['fixedYearly'][$key] != '') {
                $fixedJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['fixedYearly'][$key])];
                
                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Fixed' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Fixed', '$value') ");
                }
            }
        }
    }
    $fixedJson = mysqli_real_escape_string($db, json_encode($fixedJson));

    $addOnTitle = $_POST['addOnTitle'];
    $addOnYearly = $_POST['addOnYearly'];
    $addOnJson = [];
    if (is_array($_POST['addOnTitle']) && is_array($_POST['addOnYearly'])) {
        foreach ($_POST['addOnTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['addOnYearly'][$key]) && $_POST['addOnYearly'][$key] != '') {
                $addOnJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['addOnYearly'][$key])];

                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Add On' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Add On', '$value') ");
                }
            }
        }
    }
    $addOnJson = mysqli_real_escape_string($db, json_encode($addOnJson));

    $deductionTitle = $_POST['deductionTitle'];
    $deductionYearly = $_POST['deductionYearly'];
    $deductionJson = [];
    if (is_array($_POST['deductionTitle']) && is_array($_POST['deductionYearly'])) {
        foreach ($_POST['deductionTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['deductionYearly'][$key]) && $_POST['deductionYearly'][$key] != '') {
                $deductionJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['deductionYearly'][$key])];

                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Deduction' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Deduction', '$value') ");
                }
            }
        }
    }
    $deductionJson = mysqli_real_escape_string($db, json_encode($deductionJson));


    $od = mysqli_query($db, "UPDATE employee_salary set revision_end_date='$revisionDate' where employee_id='$employee_id' and revision_end_date='$revisionOldDate' ");
    if ($od) {

        $q = mysqli_query($db, "UPDATE `employee_salary` SET `employee_id`='$employee_id', `ctc`='$ctcYearly', `net_payable`='$netPayableYearly', `fixed`='$fixedJson', `add_on`='$addOnJson', `deduction`='$deductionJson', `revision_start_date`='$revisionDate' WHERE `id`='$edit_id' ");

        if ($q) {
            echo json_encode(["status" => 200, 'message' => 'Salary Updated Successfully !']);
        } else {
            echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
        }
    } else {
        echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
    }
}

// from addSalary.php
if (isset($_POST['ReviseSalary'])) {

    $edit_id = mysqli_real_escape_string($db, $_POST['edit_id']);
    $employee_id = mysqli_real_escape_string($db, $_POST['ex_employee_id']);
    
    $basicSalaryYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['basicSalaryYearly']));
    $hraYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['hraYearly']));
    $booksPerYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['booksPerYearly']));
    $specialAllowanceYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['specialAllowanceYearly']));

    $ctcYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['ctcYearly']));
    $netPayableYearly = mysqli_real_escape_string($db, preg_replace('/[^\d]/', '', $_POST['netPayableYearly']));

    $revisionDate = mysqli_real_escape_string($db, $_POST['revisionDate']);


    $fixedTitle = $_POST['fixedTitle'];
    $fixedYearly = $_POST['fixedYearly'];
    $fixedJson = [];
    if (is_array($_POST['fixedTitle']) && is_array($_POST['fixedYearly'])) {
        foreach ($_POST['fixedTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['fixedYearly'][$key]) && $_POST['fixedYearly'][$key] != '') {
                $fixedJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['fixedYearly'][$key])];
                
                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Fixed' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Fixed', '$value') ");
                }
            }
        }
    }
    $fixedJson = mysqli_real_escape_string($db, json_encode($fixedJson));

    $addOnTitle = $_POST['addOnTitle'];
    $addOnYearly = $_POST['addOnYearly'];
    $addOnJson = [];
    if (is_array($_POST['addOnTitle']) && is_array($_POST['addOnYearly'])) {
        foreach ($_POST['addOnTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['addOnYearly'][$key]) && $_POST['addOnYearly'][$key] != '') {
                $addOnJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['addOnYearly'][$key])];

                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Add On' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Add On', '$value') ");
                }
            }
        }
    }
    $addOnJson = mysqli_real_escape_string($db, json_encode($addOnJson));

    $deductionTitle = $_POST['deductionTitle'];
    $deductionYearly = $_POST['deductionYearly'];
    $deductionJson = [];
    if (is_array($_POST['deductionTitle']) && is_array($_POST['deductionYearly'])) {
        foreach ($_POST['deductionTitle'] as $key => $value) {
            if ($value != '' && isset($_POST['deductionYearly'][$key]) && $_POST['deductionYearly'][$key] != '') {
                $deductionJson[] = ['title' => $value, 'yearly_amount' => preg_replace('/[^\d]/', '', $_POST['deductionYearly'][$key])];

                // store this title in suggestions if not exist
                $title_check = mysqli_query($db, "SELECT * from suggestions where sug_for='Deduction' AND title='$value' ");
                if (mysqli_num_rows($title_check) == 0) {
                    mysqli_query($db, "INSERT into suggestions (sug_for, title) values ('Deduction', '$value') ");
                }
            }
        }
    }
    $deductionJson = mysqli_real_escape_string($db, json_encode($deductionJson));


    $salaryCount = mysqli_num_rows(mysqli_query($db, "SELECT * from employee_salary where employee_id='$employee_id' "));
    if ($salaryCount > 0 && $revisionDate == '') {
        echo json_encode(["status" => 500, 'message' => "$employee_id This employee salary already exist. if you want to add Salary please fill revision date !"]);
    } else if ($salaryCount == 0 && $revisionDate != '') {
        echo json_encode(["status" => 500, 'message' => "$employee_id This employee salary add first time so please, leave the revision date empty !"]);
    } else {

        $od = mysqli_query($db, "UPDATE employee_salary set revision_end_date='$revisionDate' where employee_id='$employee_id' order by id desc limit 1");
        if ($od) {

            $q = mysqli_query($db, "INSERT INTO `employee_salary` (`employee_id`, `ctc`, `net_payable`, `fixed`, `add_on`, `deduction`, `revision_start_date`, `revision_end_date`) VALUES ('$employee_id', '$ctcYearly', '$netPayableYearly', '$fixedJson', '$addOnJson', '$deductionJson', '$revisionDate', '') ");

            if ($q) {
                echo json_encode(["status" => 200, 'message' => 'Salary Revised Successfully !']);
            } else {
                echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
                exit();
            }
        } else {
            echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
            exit();
        }
    }
}
