<?php

use api\classes\API;
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']}/api/classes/API.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_devices.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/pageNavbar.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API.php";

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

# Page functions
function showExtension($devicesLinked, $filter = false): void
{
    if (count($devicesLinked) > 0) {
        foreach ($devicesLinked as $extension) {
            if ($filter === false || $extension['device_type'] == $filter) { ?>
                <div class="col-sm-3 d-flex flex-column align-items-center">
                    <img src="data:image/png;base64, <?php echo $extension['device_image']; ?>" class="img-fluid pb-4" style="max-width: 100%; height: auto;" alt="...">
                    <a href="?view=<?php echo $extension['device_uuid'] ?>" class="btn btn-info btn-rounded align-items-center"><?php echo $extension['device_name'] ?></a>
                </div>
            <?php }
        }
    } else { ?>
        <p><?php echo __('no_device_found') ?></p>
    <?php }
}

function makeFileTables($API, $dataFolder, $device_slugify): void
{
    $device_data_dir = $_SERVER['DOCUMENT_ROOT'] . '/data/devices/' . $device_slugify . '/' . $dataFolder . '/';
    $documents = array_diff(scandir($device_data_dir), array('..', '.'));

    foreach ($documents as $document) {
        $full_path = $device_data_dir . $document;
        $fileSize = human_filesize(fileSize($full_path));
        $fileModified = date("Y-m-d H:i:s", filemtime($full_path));
        $urlPath = '/data/devices/' . $device_slugify . '/' . $dataFolder . '/' . $document;
        ?>
        <tr>
            <td>
                <a target="_blank" href="<?php echo $urlPath ?>"><i class="fas fa-external-link-alt"></i> <?php echo $document; ?>
                </a>
            </td>
            <td>
                <?php echo $fileSize ?>
            </td>
            <td>
                <?php echo $fileModified ?>
            </td>
            <td>
                <?php if ($API->checkPermissions('admin-devices-files', 'RW', true)) { ?>
                    <form action="/api/v1/autop/devices/files" method="post">
                        <input type="hidden" name="filePath" value="">
                        <input type="hidden" name="X-HTTP-Method-Override" value="DELETE">
                        <a href="#" class="btn btn-danger btn-sm btn-rounded delete-btn" data-item-uuid="<?php echo $urlPath ?>" data-api-url="/api/v1/autop/devices/files/" data-item-name="file_name"><i class="fas fa-trash-alt"></i></a>
                    </form>
                <?php } ?>
            </td>
        </tr>

    <?php }
}

function render_template_controls($template_uuid, $device_uuid, $default_template, $platform_uuid): void
{
    ?>
    <div class="d-flex align-items-center gap-2">
        <form id="add_<?php echo $default_template ?>_template" action="/api/v2/templates/add/" method="post" <?= $template_uuid ? 'style="display: none"' : '' ?>>
            <input type="hidden" name="template_device_uuid" value="<?= htmlspecialchars($device_uuid) ?>">
            <input type="hidden" name="template_name" value="<?php echo $default_template ?>">
            <input type="hidden" name="template_slugify" value="<?php echo $default_template ?>">
            <?php if ($platform_uuid) { ?>
                <input type="hidden" name="platform_uuid" value="<?php echo $platform_uuid ?>">
            <?php } ?>
            <button type="submit" class="btn btn-success btn-rounded mt-2" disabled>
                <i class="fas fa-magic"></i>
            </button>
        </form>

        <a id="edit_<?php echo $default_template ?>_template" class="btn btn-primary btn-rounded" href="/devices/?template=<?= htmlspecialchars($template_uuid) ?>" <?= !$template_uuid ? 'style="display: none"' : '' ?>><i class="fas fa-edit" disabled=""></i></a>

        <form id="del_<?php echo $default_template ?>_template" action="/api/v1/templates/del/" method="post" <?= !$template_uuid ? 'style="display: none"' : '' ?>>
            <input type="hidden" name="template_uuid" value="<?= htmlspecialchars($template_uuid) ?>">
            <a href="#" class="btn btn-danger btn-rounded delete-btn" data-item-uuid="<?= htmlspecialchars($template_uuid) ?>" data-api-url="/api/v2/templates/del/" data-delete-action='{"add_<?php echo $default_template ?>_template":"show", "edit_<?php echo $default_template ?>_template":"hide", "del_<?php echo $default_template ?>_template":"hide"}'><i class="fas fa-trash-alt"></i></a>
        </form>
    </div>
    <?php
}

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

# PageClasses Setup
$pageNavbar = new pageNavbar(true);
if ($API->checkPermissions('admin-devices', 'RW', true)) {
    $pageNavbar->AddHTMLButton('<button class="btn btn-danger" type="button" disabled><i class="fas fa-trash-alt"></i> ' . __('delete') . '</button>');
    $get_view = htmlspecialchars($_GET['view'], ENT_QUOTES, 'UTF-8');
    $pageNavbar->AddHTMLButton('<a class="btn btn-primary mx-3" type="button" href="?edit=' . $get_view . '"><i class="fas fa-edit"></i> ' . __('edit') . '</a>');
    $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>');
}

# Retrieve Information for the page
$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['view']);
$stmt->execute();
$device_data_result = $stmt->get_result();
if ($device_data_result->num_rows == 0) {
    echo "No Vendor found with uuid " . htmlspecialchars($_GET['edit'], ENT_QUOTES, 'UTF-8');
    exit;
} else {
    $device_data = $device_data_result->fetch_assoc();
}

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

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

<div class="row d-flex align-items-stretch pb-2">
    <div class="col-md-4 pb-4">
        <div class="card h-100">
            <div class="card-body">
                <h1 class="text-center"><?php echo $device_data['vendor_name'] . ' ' . $device_data['device_name'] ?></h1>
                <img src="data:image/png;base64, <?php echo $device_data['device_image']; ?>" class="img-fluid" style="max-width: 100%; height: auto;" alt="...">
            </div>
        </div>
    </div>
    <div class="col-md-8 pb-4">
        <div class="card h-100">
            <div class="card-body">
                <table>
                    <tr>
                        <td>vendor_name:</td>
                        <td><?php echo $device_data['vendor_name'] ?></td>
                    </tr>
                    <tr>
                        <td>device_uuid:</td>
                        <td><?php echo $device_data['device_uuid'] ?></td>
                    </tr>
                    <tr>
                        <td>device_type:</td>
                        <td><?php echo $device_data['device_type'] ?></td>
                    </tr>
                    <tr>
                        <td>device_name:</td>
                        <td><?php echo $device_data['device_name'] ?></td>
                    </tr>
                    <tr>
                        <td>device_slugify:</td>
                        <td><?php echo $device_data['device_slugify'] ?></td>
                    </tr>
                    <tr>
                        <td>device_enabled:</td>
                        <td><?php echo $device_data['device_enabled'] ?></td>
                    </tr>
                    <tr>
                        <td>device_eol:</td>
                        <td><?php echo showTime($device_data['device_eol']) ?></td>
                    </tr>
                    <tr>
                        <td>device_create_timestamp:</td>
                        <td><?php echo showTime($device_data['device_create_timestamp']) ?></td>
                    </tr>
                    <tr>
                        <td>device_modified_timestamp:&nbsp;&nbsp;</td>
                        <td><?php echo showTime($device_data['device_modified_timestamp']) ?></td>
                    </tr>
                    <tr>
                        <td class="align-top">device_notes:</td>
                        <td><?php echo $device_data['device_notes'] ?></td>
                    </tr>
                    <tr>
                        <td class="align-top">device_extra:</td>
                        <td class="w-100">
                            <label for="device_extra"></label>
                            <textarea class="form-control" id="device_extra" name="device_extra" rows="5" disabled><?php echo json_encode(json_decode($device_data['device_extra']), JSON_PRETTY_PRINT) ?></textarea>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header pt-2 pb-1">
                <h4>Uses</h4>
            </div>
            <div class="card-body">
                To be made. It's going to be visible where the device is used (organisation/site).
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <?php
        # Retrieve device extension data from the device
        $devicesLinked = array();
        if ($device_data['device_type'] == 'phone' || $device_data['device_type'] == 'base') {
            $device_extensions = json_decode($device_data['device_extensions']);
        } elseif ($device_data['device_type'] == 'module' || $device_data['device_type'] == 'handset') {
            $query = "SELECT device_extensions, device_uuid FROM autop_devices WHERE device_extensions LIKE ?";
            $stmt = $GLOBALS['conn']->prepare($query);
            if ($stmt) {
                $searchTerm = "%" . $device_data['device_uuid'] . "%"; // Add wildcards manually
                $stmt->bind_param('s', $searchTerm);
                $stmt->execute();
                $result = $stmt->get_result();

                $device_extensions = array();
                while ($row = $result->fetch_assoc()) {
                    $device_extensions[] = $row['device_uuid'];
                }
                $stmt->close();
            }
        }

        if (!empty($device_extensions)) {
            $placeholders = implode(' OR device_uuid = ', array_fill(0, count($device_extensions), '?'));
            $query = "SELECT * FROM autop_devices WHERE device_uuid = " . $placeholders;
            $stmt = $GLOBALS['conn']->prepare($query);
            if ($stmt) {
                $types = str_repeat('s', count($device_extensions));
                $stmt->bind_param($types, ...$device_extensions);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    $devicesLinked[] = $row;
                }
                $stmt->close();
            }
        }

        $connectedDeviceCards = [];
        if (in_array($device_data['device_type'], ['phone', 'base'])) {
            $connectedDeviceCards[] = [
                    'title' => __('extensions_available'),
                    'filter' => 'module'
            ];
        }

        if ($device_data['device_type'] == 'base') {
            $connectedDeviceCards[] = [
                    'title' => __('handsets_available'),
                    'filter' => 'handset'
            ];
        }

        if (in_array($device_data['device_type'], ['module', 'handset'])) {
            $connectedDeviceCards[] = [
                    'title' => __('parent_device'),
                    'filter' => false
            ];
        }

        foreach ($connectedDeviceCards as $card) { ?>
            <div class="card">
                <div class="card-header pt-2 pb-1">
                    <h4><?php echo $card['title']; ?></h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php showExtension($devicesLinked, $card['filter']); ?>
                    </div>
                </div>
            </div>
        <?php } ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-body pt-0">
                <ul class="nav nav-tabs nav-line nav-color-secondary" id="line-tab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="line-home-tab" data-bs-toggle="pill" href="#line-home" role="tab" aria-controls="pills-home" aria-selected="true">Documents</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="line-profile-tab" data-bs-toggle="pill" href="#line-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Firmware</a>
                    </li>
                </ul>
                <div class="tab-content mt-3 mb-3" id="line-tabContent">
                    <div class="tab-pane fade show active" id="line-home" role="tabpanel" aria-labelledby="line-home-tab">
                        <div class="table-responsive">
                            <table class="table table-borderless " data-table-type="documents">
                                <thead>
                                <tr>
                                    <th><?php echo __('document') ?></th>
                                    <th><?php echo __('filesize') ?></th>
                                    <th><?php echo __('file_last_modified') ?></th>
                                    <th></th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php makeFileTables($API, 'documents', $device_data['device_slugify']); ?>
                                </tbody>
                            </table>
                        </div>
                        <?php if ($API->checkPermissions('admin-devices-files', 'RW', true)) { ?>
                            <form action="/api/v1/autop/devices/files" class="dropzone p-0" data-form-type="documents">
                                <input type="hidden" name="device_slugify" value="<?php echo $device_data['device_slugify'] ?>">
                                <input type="hidden" name="filetype" value="documents">
                                <div class="dz-message mt-1 mb-0" data-dz-message>
                                    <div class="icon">
                                        <i class="icon-doc"></i>
                                    </div>
                                    <h4 class="message"><?php echo __('drag_and_drop_files_here') ?> </h4>
                                </div>
                                <div class="fallback">
                                    <input name="file" type="file" multiple/>
                                </div>
                            </form>
                        <?php } ?>
                    </div>
                    <div class="tab-pane fade" id="line-profile" role="tabpanel" aria-labelledby="line-profile-tab">
                        <div class="table-responsive">
                            <table class="table table-borderless" data-table-type="firmware">
                                <thead>
                                <tr>
                                    <th><?php echo __('filename') ?></th>
                                    <th><?php echo __('filesize') ?></th>
                                    <th><?php echo __('file_last_modified') ?></th>
                                    <th></th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php makeFileTables($API, 'firmware', $device_data['device_slugify']); ?>
                                </tbody>
                            </table>
                        </div>
                        <form action="/api/v1/autop/devices/files" class="dropzone p-0" data-form-type="firmware">
                            <input type="hidden" name="device_slugify" value="<?php echo $device_data['device_slugify'] ?>">
                            <input type="hidden" name="filetype" value="firmware">
                            <div class="dz-message mt-1 mb-0" data-dz-message>
                                <div class="icon">
                                    <i class="icon-doc"></i>
                                </div>
                                <h4 class="message"><?php echo __('drag_and_drop_files_here') ?> </h4>
                            </div>
                            <div class="fallback">
                                <input name="file" type="file" multiple/>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php


$device_uuid = $device_data['device_uuid'] ?? null;
$platforms_enabled = get_enabled_platforms($GLOBALS['conn']);
$default_template_uuid = 0 // to be made
?>
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header pt-2 pb-1">
                <h4><?= __('templates') ?></h4>
            </div>
            <div class="card-body pt-0">
                <div class="row">
                    <!-- Default Template -->
                    <div class="col-sm-3 d-flex">
                        <div class="card flex-fill d-flex flex-column">
                            <div class="card-body d-flex flex-column">
                                <h4><?= __('default') ?></h4>
                                <img src="/src/images/default-template-icon.png" alt="" class="img-fluid pb-3 flex-grow-1" style="object-fit: contain;">
                                <?php render_template_controls($default_template_uuid, $device_uuid, 'default', false); ?>
                            </div>
                        </div>
                    </div>

                    <!-- Platform Templates -->
                    <?php foreach ($platforms_enabled as $platform) { ?>
                        <div class="col-sm-3 d-flex">
                            <div class="card flex-fill d-flex flex-column">
                                <div class="card-body d-flex flex-column">
                                    <h4><?= htmlspecialchars($platform['data']['platform_name']) ?></h4>
                                    <img src="data:image/jpeg;base64, <?= htmlspecialchars($platform['data']['platform_image']) ?>" alt="" class="img-fluid pb-3 flex-grow-1" style="object-fit: contain;">
                                    <?php render_template_controls($platform['default_template_uuid'], $device_uuid, $platform['data']['platform_slugify'], $platform['data']['platform_uuid']); ?>
                                </div>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>