<?php
session_start();
include "classes/html.class.php";

$db = new db();

$index = 0;
$date = date('Y-m-d H:i', strtotime("+ 2hours"));
$inplode_text = '';
$triggers = '';
$trigger = 0;
while ($index <= $_POST['total_questions'] - 1) {

    if (strlen($_POST['question_' . $index]) < 1) {
    } else {


        if ($_POST["w_" . $index] != '0') {
            if ($_POST["w_" . $index] == substr($_POST['q_a_' . $index], 0, 1)) {
                $questions = $questions . $_POST['question_' . $index] . "(WARNING)" . '||';
                $triggers = $triggers . "{$_POST['question_' .$index]} {$_POST['q_a_' .$index]} <br><br>";
                $trigger = 1;
                $answers = $answers . $_POST['q_a_' . $index] . '||';
            } else if ($_POST["w_" . $index] == 'T' && strlen($_POST['q_a_' . $index]) > 1) {
                $questions = $questions . $_POST['question_' . $index] . "(WARNING)" . '||';
                $triggers = $triggers . "{$_POST['question_' .$index]} {$_POST['q_a_' .$index]} <br><br>";
                $trigger = 1;
                $answers = $answers . $_POST['q_a_' . $index] . '||';
            } else {
                $questions = $questions . $_POST['question_' . $index] . '||';
                $triggers = $triggers . "{$_POST['question_' .$index]} {$_POST['q_a_' .$index]} <br><br>";
                $answers = $answers . $_POST['q_a_' . $index] . '||';
            }
        } else {
            $questions = $questions . $_POST['question_' . $index] . '||';
            $triggers = $triggers . "{$_POST['question_' .$index]} {$_POST['q_a_' .$index]} <br><br>";
            $answers = $answers . $_POST['q_a_' . $index] . '||';
        }
    }
    $index++;
}

if ($trigger == 1) {
    $db->insert("INSERT INTO warning_events (`event_type`,`event_message`,`sent`,`asset_id`) VALUES ('WARNING','<h1>PLEASE NOTE!</h1><hr><h2> PRE INSPECTION WARNING(s) TRIGGERED : <br><br> ASSET : {$_POST['asset_id']} <br><br> DATE: $date</h2><h2>USER: {$_SESSION['username']}<br><hr><br></h2><h1>LIST DETAILS:</h1> <h3><br> $triggers </h3> <h2>Notes:</h2>{$_POST['notes']}',0,{$_POST['asset_record_id']})");
    echo "<script>alert('WARNING ASSET NOT FIT FOR USE');</script>";
} else {
    echo "<script>alert('ASSET FIT FOR USE');</script>";
}
$asset_record_id = $_POST['asset_record_id'];
$notes = $_POST['notes'];

$asset_res = $db->exec_query('assets',['*'],'','','','',"record_id = $asset_record_id");
$asset_info = $asset_res->fetch_assoc();

$db->Insert("INSERT INTO `inspections`(`inpection_id`, `questions`, `answers`, `asset_record_id`, `user_id`, `date_time`, `notes`,`farm_id`) VALUES ('{$_POST['inspection_id']}','$questions','$answers','$asset_record_id','{$_SESSION['user_id']}','$date','$notes',{$asset_info['farm_id']})");

echo "<script>window.location.href = 'pre_inspections.php'</script>";
