<?php
include('../../Connections/repnew.php');
header('Content-Type: application/json');
// Database connection
$host = $servername;
$db = $database;
$user = $username;
$pass = $password; 

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
// method validation
if (!isset($_POST['method'])) {
    $query = "SELECT * FROM temp_json_queue WHERE processed = 0";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $jsonEntries = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
    $method = $_POST['method'];
    if($method == 'intervention'){
        $id = $_POST['id'];
        $query = "SELECT * FROM temp_json_queue WHERE processed = 2 AND id = $id";
        $stmt = $pdo->prepare($query);
        $stmt->execute();
        $jsonEntries = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

foreach ($jsonEntries as $entry) {
    $data = json_decode($entry['json_data'], true);
    $uuid = $entry['uuid'];
    $analysisArr = array();
    $compoundsArr = array(); 

    // check for result_TestName
    foreach ($data['product']['reports'] as $report) {
        foreach ($report['parts'] as $part) {
            foreach ($part['analyses'] as $analysis) {
                $analysisgroupcode = $analysis['analysisgroupcode'];
                $result_TestName = $analysis['result_TestName'];
                // groupcode validation 
                if ($analysisgroupcode == '-' || $analysisgroupcode == '' || $analysisgroupcode == ' ') {
                    $analysisgroupcode = 'NO_GROUPCODE';
                }
                // check in vocabulary
                $query = "SELECT idanalysisvocabulary FROM analysisvocabulary WHERE analysiscode LIKE '$analysisgroupcode'";
                $stmt = $pdo->prepare($query);
                $result = $stmt->execute();
                $result = $stmt->fetchColumn();
                if (!$result) {
                    // check for result_TestName
                    $query = "SELECT idanalysisvocabulary FROM analysisvocabulary WHERE nameanalysisvoc LIKE '$result_TestName'";
                    $stmt = $pdo->prepare($query);
                    $result = $stmt->execute();
                    $result = $stmt->fetchColumn();
                    if (!$result) {
                        // add 0 to analysis array
                        array_push($analysisArr, 0);
                    } else {
                        // add 1 to analysis array
                        array_push($analysisArr, 1);
                    }
                } else {
                    // add 1 to analysis array
                    array_push($analysisArr, 1);
                }
            }
        }
    }

    // check for result_AnalytsName
    foreach ($data['product']['reports'] as $report) {
        foreach ($report['parts'] as $part) {
            foreach ($part['analyses'] as $analysis) {
                foreach ($analysis['results'] as $result) {
                    $result_AnalytsName = $result['result_AnalytsName'];
                    $cas = $result['cas'];

                    // cas validation
                    if ($cas == '-' || $cas == '' || $cas == ' ') {
                        $cas = 'NO_CAS';
                    }

                    // check in vocabulary
                    $query = "SELECT idcompoundsvocabulary FROM compundsvocabulary WHERE cascompoundvocabulary LIKE '%$cas%'";
                    $stmt = $pdo->prepare($query);
                    $result = $stmt->execute();
                    $result = $stmt->fetchColumn();
                    if (!$result) {
                        // check for result_AnalytsName
                        $query = "SELECT idcompoundsvocabulary FROM compundsvocabulary WHERE namecompoundsvocabulary LIKE '$result_AnalytsName'";
                        $stmt = $pdo->prepare($query);
                        $result = $stmt->execute();
                        $result = $stmt->fetchColumn();
                        if (!$result) {
                            // add 0 to compounds array
                            array_push($compoundsArr, 0);
                        } else {
                            // add 1 to compounds array
                            array_push($compoundsArr, 1);
                        }
                    } else {
                        // add 1 to compounds array
                        array_push($compoundsArr, 1);
                    }
                }
            }
        }
    }

    // Validate lab reference
    $labId = getLaboratoryId($data['reflab'], $pdo);
    if (!$labId) {
        markForIntervention($entry['id'], $pdo);
        continue;
    }

    if (validateJson($data) && !in_array(0, $analysisArr) && !in_array(0, $compoundsArr)) {
        // Validate and insert product
        $productId = insertProduct($data['product'], $pdo, $uuid);

        if ($productId) {
            // Insert reports, parts, analyses, and results
            foreach ($data['product']['reports'] as $report) {
                $reportId = insertReport($report, $productId, $labId, $pdo, $uuid);

                foreach ($report['parts'] as $part) {
                    $partId = insertPart($part, $reportId, $productId, $pdo, $uuid);

                    foreach ($part['analyses'] as $analysis) {
                        $result_TestName = $analysis['result_TestName'];
                        $analysisgroupcode = $analysis['analysisgroupcode'];

                        // groupcode validation
                        if ($analysisgroupcode == '-' || $analysisgroupcode == '' || $analysisgroupcode == ' ') {
                            $analysisgroupcode = 'NO_GROUPCODE';
                        }

                        $query = "SELECT idanalysisvocabulary, refid FROM analysisvocabulary WHERE analysiscode LIKE '$analysisgroupcode'";
                        $stmt = $pdo->prepare($query);
                        $res = $stmt->execute();
                        $res = $stmt->fetchAll();
                        if ($res) {
                            if($res[0]['refid'] == $res[0]['idanalysisvocabulary'] || $res[0]['refid'] == 0 || $res[0]['refid'] == NULL){
                                $analysisCodeId = $res[0]['idanalysisvocabulary'];
                            }else{
                                $analysisCodeId = $res[0]['refid'];
                            }
                        } else {
                            $query = "SELECT idanalysisvocabulary, refid FROM analysisvocabulary WHERE nameanalysisvoc LIKE '$result_TestName'";
                            $stmt = $pdo->prepare($query);
                            $res = $stmt->execute();
                            $res = $stmt->fetchAll();
                            if ($res) {
                                if($res[0]['refid'] == $res[0]['idanalysisvocabulary'] || $res[0]['refid'] == 0 || $res[0]['refid'] == NULL){
                                    $analysisCodeId = $res[0]['idanalysisvocabulary'];
                                }else{
                                    $analysisCodeId = $res[0]['refid'];
                                }
                            } else {
                                $analysisCodeId = 'NO ANALYSIS ID FOUND';
                            }
                        }

                        $analysisId = insertAnalysis($analysis, $partId, $productId, $reportId, $pdo, $uuid, $analysisCodeId);

                        foreach ($analysis['results'] as $result) {
                            $result_AnalytsName = $result['result_AnalytsName'];
                            $cas = $result['cas'];

                            // cas validation
                            if ($cas == '-' || $cas == '' || $cas == ' ') {
                                $cas = 'NO_CAS';
                            }

                            $query = "SELECT idcompoundsvocabulary, refid FROM compundsvocabulary WHERE cascompoundvocabulary LIKE '%$cas%'";
                            $stmt = $pdo->prepare($query);
                            $res = $stmt->execute();
                            $res = $stmt->fetchAll();
                            if ($res) {
                                if($res[0]['refid'] == $res[0]['idcompoundsvocabulary'] || $res[0]['refid'] == 0 || $res[0]['refid'] == NULL){
                                    $compoundId = $res[0]['idcompoundsvocabulary'];
                                }else{
                                    $compoundId = $res[0]['refid'];
                                }
                            } else {
                                $query = "SELECT idcompoundsvocabulary, refid FROM compundsvocabulary WHERE namecompoundsvocabulary LIKE '$result_AnalytsName'";
                                $stmt = $pdo->prepare($query);
                                $res = $stmt->execute();
                                $res = $stmt->fetchAll();
                                if ($res) {
                                    if($res[0]['refid'] == $res[0]['idcompoundsvocabulary'] || $res[0]['refid'] == 0 || $res[0]['refid'] == NULL){
                                        $compoundId = $res[0]['idcompoundsvocabulary'];
                                    }else{
                                        $compoundId = $res[0]['refid'];
                                    }
                                } else {
                                    $compoundId = 'NO COMPOUND ID FOUND';
                                }
                            }
                            insertResult($result, $analysisId, $partId, $productId, $reportId, $pdo, $uuid, $compoundId);
                        }
                    }
                }
            }

            markAsProcessed($entry['id'], $pdo);
            importHistory($pdo, $uuid);
            die(json_encode(['code' => 'success']));
        } else {
            markForIntervention($entry['id'], $pdo);
            importHistory($pdo, $uuid);
            die(json_encode(['code' => 'success', 'message' => 'Intervention']));
        }
    } else {
        markForIntervention($entry['id'], $pdo);
        importHistory($pdo, $uuid);
        die(json_encode(['code' => 'success', 'message' => 'Intervention']));
    }
}



// Function definitions

function importHistory($pdo, $uuid)
{
    $query = "INSERT INTO template_import_his (created_at, importcode, f_status, user_id, importfilename) VALUES (:created_at, :importcode, :f_status, :user_id, :importfilename)";
    $stmt = $pdo->prepare($query);
    $stmt->execute([
        'created_at' => date("Y-m-d H:i:s"),
        'importcode' => $uuid,
        'f_status' => 1,
        'user_id' => 2,
        'importfilename' => 'JSON API'
    ]);
}

function validateJson($json)
{
    $checkData = json_encode($json);
    if (json_decode($checkData) !== null) {
        return true;
    } else {
        return false;
    }
}

function getLaboratoryId($reflab, $pdo)
{
    $query = "SELECT idlab FROM laboratories WHERE reflab = :reflab";
    $stmt = $pdo->prepare($query);
    $stmt->execute(['reflab' => $reflab]);
    return $stmt->fetchColumn();
}

function insertProduct($product, $pdo, $uuid)
{
    $query = "SELECT idproducts FROM products WHERE products_refnumber = :refnumber";
    $stmt = $pdo->prepare($query);
    $stmt->execute(['refnumber' => $product['products_refnumber']]);
    $productId = $stmt->fetchColumn();

    if (!$productId) {
        $query = "INSERT INTO products (products_refnumber, products_description, products_style, products_sku, products_color, products_season, products_market, products_order, product_buyer, product_claimedfiber, products_fibercontentresult, dateprod, namesupplier, agerange, products_billto, products_billtocde, products_codeanddesc, products_division, products_phase, products_country, products_region, importcode) 
                  VALUES (:refnumber, :description, :style, :sku, :color, :season, :market, :order, :buyer, :claimedfiber, :fibercontentresult, :dateprod, :supplier, :agerange, :billto, :billtocde, :codeanddesc, :division, :phase, :country, :region, :importcode)";
        $stmt = $pdo->prepare($query);
        $stmt->execute([
            'refnumber' => $product['products_refnumber'],
            'description' => $product['products_description'],
            'style' => $product['products_style'],
            'sku' => $product['products_sku'],
            'color' => $product['products_color'],
            'season' => $product['products_season'],
            'market' => $product['products_market'],
            'order' => $product['products_order'],
            'buyer' => $product['product_buyer'],
            'claimedfiber' => $product['product_claimedfiber'],
            'fibercontentresult' => $product['products_fibercontentresult'],
            'dateprod' => $product['dateprod'],
            'supplier' => $product['namesupplier'],
            'agerange' => $product['agerange'],
            'billto' => $product['products_billto'],
            'billtocde' => $product['products_billtocde'],
            'codeanddesc' => $product['products_codeanddesc'],
            'division' => $product['products_division'],
            'phase' => $product['products_phase'],
            'country' => $product['products_country'],
            'region' => $product['products_region'],
            'importcode' => $uuid
        ]);
        return $pdo->lastInsertId();
    }
    return $productId; // Return existing product ID
}

function insertReport($report, $productId, $labId, $pdo, $uuid)
{
    // Check if the report already exists
    $query = "SELECT idreports FROM reports WHERE reportsNumberLab = :reportsNumberLab AND idLabs = :idlaboratories";
    $stmt = $pdo->prepare($query);
    $stmt->execute([
        'reportsNumberLab' => $report['reportsNumberLab'],
        'idlaboratories' => $labId
    ]);
    $reportId = $stmt->fetchColumn();

    if ($reportId) {
        // Report already exists, return the existing ID
        return $reportId;
    } else {
        // Insert new report
        $query = "INSERT INTO reports (reportsNumberLab, reportDateIn, reportsDateOut, reportsDateDue, reportsRating, reportsRating2, pdffilename, reports_LabName, reports_testype, reports_invoicenumber, reports_invoiceamount, reports_invoiceadate, idproducts, idLabs, importcode) 
                  VALUES (:reportsNumberLab, :reportDateIn, :reportsDateOut, :reportsDateDue, :reportsRating, :reportsRating2, :pdffilename, :reports_LabName, :reports_testype, :reports_invoicenumber, :reports_invoiceamount, :reports_invoiceadate, :idproducts, :idlaboratories, :importcode)";

        $stmt = $pdo->prepare($query);
        $stmt->execute([
            'reportsNumberLab' => $report['reportsNumberLab'],
            'reportDateIn' => $report['reportDateIn'],
            'reportsDateOut' => $report['reportsDateOut'],
            'reportsDateDue' => $report['reportsDateDue'],
            'reportsRating' => $report['reportsRating'],
            'reportsRating2' => $report['reportsRating2'],
            'pdffilename' => $report['pdffilename'],
            'reports_LabName' => $report['reports_LabName'],
            'reports_testype' => $report['reports_testype'],
            'reports_invoicenumber' => $report['reports_invoicenumber'],
            'reports_invoiceamount' => $report['reports_invoiceamount'],
            'reports_invoiceadate' => $report['reports_invoiceadate'],
            'idproducts' => $productId,
            'idlaboratories' => $labId,
            'importcode' => $uuid
        ]);
        return $pdo->lastInsertId();
    }
}

function insertPart($part, $reportId, $productId, $pdo, $uuid)
{
    // Check if the part already exists
    $query = "SELECT idparts FROM parts WHERE partsCode = :partsCode AND idreports = :idreports";
    $stmt = $pdo->prepare($query);
    $stmt->execute([
        'partsCode' => $part['partsCode'],
        'idreports' => $reportId
    ]);
    $partId = $stmt->fetchColumn();

    if ($partId) {
        // Part already exists, return the existing ID
        return $partId;
    } else {
        // Insert new part
        $query = "INSERT INTO parts (partsCode, partsDescription, partsColor, partsMaterial, idreports, idproducts, importcode) 
                  VALUES (:partsCode, :partsDescription, :partsColor, :partsMaterial, :idreports, :idproducts, :importcode)";

        $stmt = $pdo->prepare($query);
        $stmt->execute([
            'idproducts' => $productId,
            'partsCode' => $part['partsCode'],
            'partsDescription' => $part['partsDescription'],
            'partsColor' => $part['partsColor'],
            'partsMaterial' => $part['partsMaterial'],
            'idreports' => $reportId,
            'importcode' => $uuid
        ]);
        return $pdo->lastInsertId();
    }
}


function insertAnalysis($analysis, $partId, $productId, $reportId, $pdo, $uuid, $analysisCodeId)
{
    $query = "INSERT INTO analysis_project (result_TestName, test_Rating, test_Rating2, requirements, reference, analysisgroupcode, idpart, idproducts, idreports, importcode) 
              VALUES (:result_TestName, :test_Rating, :test_Rating2, :requirements, :reference, :analysisgroupcode, :idpart , :idproducts, :idreports, :importcode)";

    $stmt = $pdo->prepare($query);
    $stmt->execute([
        'idproducts' => $productId,
        'idreports' => $reportId,
        'result_TestName' => $analysisCodeId,
        'test_Rating' => $analysis['test_Rating'],
        'test_Rating2' => $analysis['test_Rating2'],
        'requirements' => $analysis['requirements'],
        'reference' => $analysis['reference'],
        'analysisgroupcode' => $analysis['analysisgroupcode'],
        'idpart' => $partId,
        'importcode' => $uuid
    ]);
    return $pdo->lastInsertId();
}

function insertResult($result, $analysisId, $partId, $productId, $reportId, $pdo, $uuid, $compoundId)
{
    $query = "INSERT INTO result_project (result_AnalytsName, result_AnalytsRating, result_Value, result_Comment, test_Rating, test_Rating2, result_UnitofMeasure, cas, requirements, reference, idanalysis_project, idpart, idproducts, idreports, importcode) 
              VALUES (:result_AnalytsName, :result_AnalytsRating, :result_Value, :result_Comment, :test_Rating, :test_Rating2, :result_UnitofMeasure, :cas, :requirements, :reference, :idanalysis_project, :idpart, :idproducts, :idreports, :importcode)";

    $stmt = $pdo->prepare($query);
    $stmt->execute([
        'result_AnalytsName' => $compoundId,
        'result_AnalytsRating' => $result['result_AnalytsRating'],
        'result_Value' => $result['result_Value'],
        'result_Comment' => $result['result_Comment'],
        'test_Rating' => $result['test_Rating'],
        'test_Rating2' => $result['test_Rating2'],
        'result_UnitofMeasure' => $result['result_UnitofMeasure'],
        'cas' => $result['cas'],
        'requirements' => $result['requirements'],
        'reference' => $result['reference'],
        'idanalysis_project' => $analysisId,
        'idpart' => $partId,
        'idproducts' => $productId,
        'idreports' => $reportId,
        'importcode' => $uuid
    ]);
}

function markAsProcessed($id, $pdo)
{
    $query = "UPDATE temp_json_queue SET processed = 1 WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->execute(['id' => $id]);
}

function markForIntervention($id, $pdo)
{
    $query = "UPDATE temp_json_queue SET processed = 2 WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->execute(['id' => $id]);

    $query = "INSERT INTO notifications (`title`,`description`) VALUES ('Intervention Required', 'Intervention required for JSON entry with ID $id')";
    $stmt = $pdo->prepare($query);
    $stmt->execute();

}
