<?php

require_once __DIR__ . '/../init_cloud.php';

$response = [
    'data'   => [],
    'status' => 'failed'
];

http_response_code(422);

$inputRules = [
    "title"      => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    'members'    => ["required" => true],
    'datepicker' => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "priority"   => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "reminder"   => ["required" => false],
];

$failed = false;

$error = [];

function validateIntPos($id)
{
    return !(empty($id) || !is_numeric($id) || $id < 1);
}

if (__RB_validateInput($inputRules, 'set_meeting', $error)) {

    $objCreate = [];

    foreach ($inputRules as $key => $val) {
        if ($key == 'datepicker') {
            $date = (explode(" - ", $_POST[$key]));
            $objCreate['start'] = $date[0];
            $objCreate['end'] = $date[1];
        } else if ($key == 'members') {
            $customers = [];
            $employees = [];
            if (!empty($_POST[$key])) {
                foreach ($_POST[$key] as $member) {
                    $m = (explode("-", $member));
                    if ($m[0] == 'c') {
                        $customers[] = $m[1];
                    }

                    if ($m[0] == 'e') {
                        $employees[] = $m[1];
                    }
                }
            }
            $objCreate['customers'] = $customers;
            $objCreate['employees'] = $employees;
        } else {
            $objCreate[$key] = ($_POST[$key] ?? '');
        }
    }

    $data = [
        'id' => $_POST['id'],
        'id_customer' => $_SESSION['id'],
        'data' => $objCreate
    ];

    __RB_api_cloud('setMeeting', $data, $json);

    http_response_code(200);

    $response = ["status" => 'success'];

    echo json_encode($response);

    exit;
} else {
    $response = [
        'status' => 'failed',
        'errors' => $error
    ];

    echo json_encode($response);

    exit;
}
