<?php
//header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);

include_once( dirname(dirname(__FILE__)) . '/../classes/check.class.php');
include_once __DIR__ . '/../classes/functions.php';
protect('admin');

$_POST = filter_var_array($_POST, FILTER_SANITIZE_STRING);
$_POST['latest_request'] = json_encode($_POST);
$postId = $_POST['invoice_id'];

if ( !empty($_POST['javascript_object']) ) {
    $_POST['javascript_object'] = json_encode($_POST['javascript_object']);
}
if ( !empty($_POST['javascript_object2']) ) {
    $_POST['javascript_object2'] = json_encode($_POST['javascript_object2']);
}
$_POST['rental_car'] = intval($_POST['rental_car']);
unset($_POST['invoice_id']);

$db = DB::getInstance();

$db->update('invoice', $_POST, $postId);
$invoiceId = $db->lastId();
if ( isset($_POST['confirm_invoice']) && $_POST['confirm_invoice'] ) {
    flashInvoiceSession();
}

if ( !empty($_POST['reclamation']) ) {
    createReclamationIfNotExists( $_POST['reclamation'], array(
        'client_id' => $_POST['client_id'],
        'reclamation' => $_POST['reclamation'],
        'insurer' => $_POST['insurer'],
        'vin' => $_POST['vin'],
        'brand' => $_POST['brand'],
        'model' => $_POST['model'],
        'year' => $_POST['year'],
        'inventory' => $_POST['inventory'],
        'color' => $_POST['color'],
        'brake_type' => $_POST['brake_type'],
        'particular_area' => $_POST['particular_area'],
        'millage' => $_POST['millage'],
        'creation_style' => 'invoice',
    ) );
}

echo json_encode(array(
    'message' => 'Data saved!',
    'invoice' => $invoiceId,
));

exit();
