<?php

use api\classes\API;
use bin\php\Classes\formBuilder;
use bin\php\Classes\pageNavbar;

if (!defined('APP_INIT')) {
    exit;
}
# IDE Section

# Includes Section
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/pageNavbar.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/formBuilder.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_devices.php";

# Check permissions
$API = new API();
if (!$API->checkPermissions('admin-devices', 'RW', true)) {
    echo 'error 401 unauthorized';
    exit;
}

# Page functions

# JS Scripts to load for this page
$jsScriptLoadData['form'][] = true;
$jsScriptLoadData['datepicker'] = true;
$jsScriptLoadData['/src/js/sentri/multiple_select.js'] = true;
$jsScriptLoadData['/src/js/sentri/validateJson.js'] = true;
$jsScriptLoadData['/src/js/sentri/breadCrumbs.js'] = true;

# PageClasses Setup
$pageNavbar = new pageNavbar(true);
$pageNavbar->AddHTMLButton('<div class="btn-group dropdown">
            <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="fas fa-plus text-success"></i>' . __('add_device') . '</button>
            <ul class="dropdown-menu bg-black2" role="menu">
                <li>
                    <a class="dropdown-item text-white-50 bg-black2" href="?add=phone">Phone</a>
                    <a class="dropdown-item text-white-50 bg-black2" href="?add=module">Module</a>
                    <a class="dropdown-item text-white-50 bg-black2" href="?add=base">Base</a>
                    <a class="dropdown-item text-white-50 bg-black2" href="?add=handset">Handset</a>
                </li>
            </ul>
        </div>');
$formBuilder = new formBuilder('edit_device', '<i class="fas fa-edit"></i>', '/devices/');
$get_edit = htmlspecialchars($_GET['edit'], ENT_QUOTES, 'UTF-8');
$formBuilder->addExtraButtons(array(0 => array('buttonText' => __('view'), 'buttonIcon' => '<i class="far fa-eye"></i>', 'buttonHref' => '?view=' . $get_edit, 'buttonColor' => 'info')));

# Retrieve Information for the page
$device_found = false;
$stmt = $GLOBALS['conn']->prepare("SELECT * FROM autop_devices INNER JOIN autop_vendors ON autop_devices.device_vendor_uuid = autop_vendors.vendor_uuid WHERE device_uuid = ?");
$stmt->bind_param("s", $_GET['edit']);
$stmt->execute();
$device_data_result = $stmt->get_result();
$device_data = $device_data_result->fetch_assoc();

if ($device_data_result->num_rows > 0) {
    $device_found = true;
}

$formInputs = ['device_vendor_uuid', 'device_name', 'device_slugify', 'device_enabled', 'device_image', 'device_notes'];
if ($device_data['device_type'] == 'phone' || $device_data['device_type'] == 'base') {
    $formInputs[] = 'device_eol';
    $formInputs[] = 'device_extensions';
}
$formInputs[] = 'device_extra';

# Set breadcrumb data
$_SESSION['breadCrumbArray'][] = ['display' => $device_data['vendor_name'] . ' ' . $device_data['device_name'], 'href' => '?view=' . $device_data['device_uuid']];
$_SESSION['breadCrumbArray'][] = ['display' => __('edit'), 'href' => '?view=' . $device_data['device_uuid']];
$_SESSION['breadCrumbArray'][] = ['display' => __('devices'), 'href' => '/devices/'];

# Start page output
$pageNavbar->outPutNavbar();

if ($device_found) {
    $formBuilder->startForm();
    ?>
    <form id="FormValidation" enctype="multipart/form-data" method="post" action="/api/v1/devices">
        <input type="hidden" name="X-HTTP-Method-Override" value="PUT">
        <input type="hidden" name="_return" value="/devices/?edit=<?php echo $device_data['device_uuid']; ?>">
        <input type="hidden" name="device_uuid" value="<?php echo $device_data['device_uuid'] ?>">
        <div class="card-body">
            <?php foreach ($formInputs as $input) {
                if ($input == 'device_vendor_uuid') { ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_vendor_uuid" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_vendor') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <div class="select2-input">
                                <select id="device_vendor_uuid" name="device_vendor_uuid" class="form-control" required>
                                    <?php
                                    $data = $GLOBALS['conn']->query("SELECT vendor_uuid, vendor_name FROM autop_vendors WHERE vendor_enabled = 1");
                                    if ($data->num_rows == 0) { ?>
                                        <option value=""><?php echo __('no_vendor_found') ?></option>
                                    <?php } else {
                                        while ($row = $data->fetch_assoc()) { ?>
                                            <option value="<?php echo $row['vendor_uuid'] ?>" <?php echo(($row['vendor_uuid'] == $device_data['device_vendor_uuid']) ? 'selected' : '') ?>><?php echo $row['vendor_name'] ?></option>
                                        <?php }
                                    } ?>
                                </select>
                            </div>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_name') {
                    ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_name" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_name') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <input type="text" class="form-control" id="device_name" name="device_name" value="<?php echo $device_data['device_name'] ?>" placeholder="" required/>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_slugify') { ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_slugify" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_slugify') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <input type="text" class="form-control" id="device_slugify" name="device_slugify" value="<?php echo $device_data['device_slugify'] ?>" placeholder="" disabled/>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_enabled') { ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_enabled" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_enabled') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <div class="select2-input">
                                <select id="device_enabled" name="device_enabled" class="form-control" required>
                                    <option value="1" <?php echo(($device_data['device_enabled'] == 1) ? 'selected' : '') ?>><?php echo __('enabled') ?></option>
                                    <option value="0" <?php echo(($device_data['device_enabled'] == 0) ? 'selected' : '') ?>><?php echo __('disabled') ?></option>
                                </select>
                            </div>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_notes') { ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_notes" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_notes') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <textarea class="form-control" id="device_notes" name="device_notes" rows="5"><?php echo $device_data['device_notes'] ?></textarea>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_eol') { ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_eol" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('eol') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <div class="input-group">
                                <input type="text" class="form-control" id="device_eol" value="<?php echo !empty($device_data['device_eol']) ? date('d/m/Y', $device_data['device_eol']) : ''; ?>" name="device_eol" placeholder="" data-datepicker="true"/>
                                <span class="input-group-text"><i class="fa fa-calendar-check"></i></span>
                            </div>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_image') { ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_image" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_image') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <div class="input-file input-file-image">
                                <img class="img-upload-preview" width="200" src="<?php echo(($device_data['device_image'] != null) ? 'data:image/png;base64, ' . $device_data['device_image'] : '/src/images/placeholder500x500.png') ?>" alt="device_image">
                                <input type="file" class="form-control form-control-file" id="device_image" name="device_image" accept="image/png">
                                <label for="device_image" class="label-input-file btn btn-black btn-round">
                                    <span class="btn-label"><i class="fa fa-file-image"></i></span>
                                    <?php echo __('upload_image') ?>
                                </label>
                            </div>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_extensions') {
                    $device_extensions = json_decode($device_data['device_extensions']);
                    ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_extensions" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_extensions') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <div class="select2-input">
                                <select id="device_extensions" name="device_extensions[]" class="form-control" multiple="multiple" data-multiple-select="true">
                                    <?php
                                    if ($device_data['device_type'] == 'base') {
                                        $data = $GLOBALS['conn']->query("SELECT device_uuid, device_name, device_vendor_uuid FROM autop_devices WHERE device_type = 'module' OR device_type = 'handset'");
                                    } else {
                                        $data = $GLOBALS['conn']->query("SELECT device_uuid, device_name, device_vendor_uuid FROM autop_devices WHERE device_type = 'module'");
                                    }

                                    if ($data->num_rows == 0) { ?>
                                        <option value=""><?php echo __('no_device_found') ?></option>
                                    <?php } else {
                                        while ($row = $data->fetch_assoc()) { ?>
                                            <option <?php echo(in_array($row['device_uuid'], $device_extensions) ? 'selected' : '') ?> value="<?php echo $row['device_uuid'] ?>" data-vendor="<?php echo $row['device_vendor_uuid'] ?>">
                                                <?php echo $row['device_name'] ?>
                                            </option>
                                        <?php }
                                    } ?>
                                </select>
                            </div>
                        </div>
                    </div>
                <?php }
                if ($input == 'device_extra') {
                    $json_device_extra = json_encode(json_decode($device_data['device_extra']), JSON_PRETTY_PRINT); ?>
                    <div class="form-group form-show-validation row">
                        <label for="device_extra" class="col-lg-3 col-md-3 col-sm-4 mt-sm-2"><?php echo __('device_extra') ?></label>
                        <div class="col-lg-9 col-md-12 col-sm-10">
                            <textarea class="form-control" id="device_extra" name="device_extra" rows="5" data-validate-json="true"><?php echo $json_device_extra ?></textarea>
                            <small id="device_extra_help" class="form-text text-muted">
                                <?php echo __('json_enter') ?>
                            </small>
                        </div>
                    </div>
                <?php }
            } ?>
        </div>
        <?php $formBuilder->formFooter(); ?>
    </form>
    <?php $formBuilder->endForm();
} else {
    echo "No Vendor found with uuid " . $_GET['edit'];

}