<?php
// include('include/headscript.php');
// echo "<pre>";
// print_r($_POST);
// print_r($_REQUEST);

include('db-connect.php');

$input = filter_input_array(INPUT_POST);

$id_array = preg_split("/_/", $input['id']);

if ($_POST['action'] == 'edit') {

    $q_article = "article_identificationparts='{$input['article_identificationparts']}',";

    $q_material = "material_identificationparts='{$input['material_identificationparts']}',";

    $q_color = "color_identificationparts='{$input['color_identificationparts']}',";

    $q_reportno = "cmcreportnumber_identificationparts='{$input['cmcreportnumber_identificationparts']}',";
    $q_kindoftest = "kindoftest='{$input['kindoftest']}',";

    $q_reportdate = "cmcreportdate_identificationparts=null";

    if (isset($input['cmcreportdate_identificationparts'])) {

        if ($input['cmcreportdate_identificationparts'] <> '') {

            $report_date = date("Y-m-d", strtotime($input['cmcreportdate_identificationparts']));

            /* check if date is older than 5year */
            $currentDate = new DateTime();
            $dateToCheck = new DateTime($report_date);

            $diff = date_diff($dateToCheck, $currentDate);
            $yearsDifference = $diff->y;

            if ($yearsDifference >= 5) {
                $input['status'] = "error";
                $input['message'] = "Invalid Date. The date should not be older than 5 years.";
                echo json_encode($input);
                exit;
            }

            $q_reportdate = "cmcreportdate_identificationparts='{$report_date}'";
        }
    }

    $sql = "UPDATE identificationparts SET {$q_article} {$q_material} {$q_color} {$q_reportno} {$q_kindoftest} {$q_reportdate} WHERE partsidnumber='" . $id_array[0] . "' and ididentificationparts = '{$id_array[1]}'";

    $result = mysqli_query($con, $sql);

    if ($result === false) {

        $input['status'] = "error";
        $input['message'] = mysqli_error($con);
    } else {

        $input['status'] = "success";
    }
} else if ($_POST['action'] == 'delete') {

    $sql_delete = "delete from identificationparts where ididentificationparts = '{$id_array[1]}'";

    $result = mysqli_query($con, $sql_delete);

    if ($result === false) {

        $input['status'] = "error";
        $input['message'] = mysqli_error($con);
    } else {

        if (function_exists("rel2abs")) $DeleteGoTo = $DeleteGoTo ? rel2abs($DeleteGoTo, dirname(__FILE__)) : "";

        $input['status'] = "success";
    }
}

$input['id'] = $id_array[0];

echo json_encode($input);
