<?php

session_start();

require_once "config/database.php";

$printer = null;
$error = "";

if (!isset($_GET['printer']) || empty($_GET['printer'])) {

    die("Invalid Printer QR Code.");

}

$token = trim($_GET['printer']);

$_SESSION["printer_qr"] = [

    "printer_token" => $token,

];

try {

    $database = new Database();
    $db = $database->connect();

    $sql = "

        SELECT

            p.*,

            ps.status,
            ps.supports_color,
            ps.supports_duplex,
            ps.default_paper,

            qr.qr_token

        FROM printers p

        INNER JOIN printer_settings ps
            ON ps.printer_id = p.id

        INNER JOIN printer_qr qr
            ON qr.printer_id = p.id

        WHERE qr.qr_token = ?

        LIMIT 1

    ";

    $stmt = $db->prepare($sql);

    $stmt->execute([$token]);

    $printer = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($printer) {

        $_SESSION["print_job"]["printer"] = $token;

        $_SESSION["print_job"]["printer_id"] = $printer["id"];

    }

    if (!$printer) {

        $error = "Printer not found.";

    }

} catch (Exception $e) {

    $error = $e->getMessage();

}

?>
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
>

<title>SmartPrint Upload</title>

<link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css"
    rel="stylesheet"
>

<link
    href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.css"
    rel="stylesheet"
>

<link
    href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"
    rel="stylesheet"
>

<style>

/* =========================================================
   GLOBAL
   ========================================================= */

* {

    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

body {

    background: #0f172a;

    font-family: 'Inter', sans-serif;

    color: #ffffff;

    min-height: 100vh;

}

.main-container {

    max-width: 1100px;

    margin: auto;

    padding: 40px 15px;

}

.logo {

    font-size: 34px;

    font-weight: 700;

    margin-bottom: 5px;

}

.subtitle {

    color: #94a3b8;

    font-size: 15px;

    margin-bottom: 35px;

}


/* =========================================================
   CARDS
   ========================================================= */

.card-dark {

    background: #1e293b;

    border: 1px solid #334155;

    border-radius: 18px;

    box-shadow: 0 10px 30px rgba(0,0,0,.35);

}

.printer-title {

    font-size: 24px;

    font-weight: 700;

}

.info-label {

    color: #94a3b8;

    font-size: 13px;

}

.info-value {

    font-size: 16px;

    font-weight: 600;

    color: #ffffff;

}


/* =========================================================
   STATUS
   ========================================================= */

.online {

    color: #22c55e;

    font-weight: bold;

}

.offline {

    color: #ef4444;

    font-weight: bold;

}


/* =========================================================
   FEATURES
   ========================================================= */

.feature {

    padding: 10px;

    border-radius: 10px;

    background: #334155;

    margin-bottom: 10px;

}

.feature i {

    margin-right: 8px;

    color: #3b82f6;

}


/* =========================================================
   UPLOAD AREA
   ========================================================= */

.upload-area {

    background: #162033;

    border: 2px dashed #475569;

    border-radius: 18px;

    min-height: 360px;

    display: flex;

    justify-content: center;

    align-items: center;

    transition: .35s;

    cursor: pointer;

    overflow: hidden;

}

.upload-area:hover {

    border-color: #3b82f6;

    background: #1d2940;

    transform: translateY(-2px);

    box-shadow: 0 15px 40px rgba(59,130,246,.18);

}

.upload-area.dragover {

    background: #1e3a5f;

    border-color: #60a5fa;

    transform: scale(1.02);

}

.upload-content {

    text-align: center;

    padding: 40px;

}

.upload-icon {

    width: 110px;

    height: 110px;

    margin: auto;

    margin-bottom: 25px;

    border-radius: 50%;

    background: #2563eb;

    display: flex;

    justify-content: center;

    align-items: center;

    font-size: 48px;

    color: #fff;

    box-shadow: 0 10px 25px rgba(37,99,235,.35);

}

.upload-content h4 {

    font-weight: 700;

    margin-bottom: 12px;

    color: #ffffff;

}

.upload-content p {

    color: #94a3b8;

}


/* =========================================================
   BADGES
   ========================================================= */

.badge {

    font-size: 13px;

    padding: 8px 12px;

    border-radius: 20px;

    margin: 3px;

}


/* =========================================================
   BUTTONS
   ========================================================= */

.btn-primary {

    background: #2563eb;

    border: none;

    border-radius: 12px;

    padding: 12px 28px;

    font-weight: 600;

    transition: .3s;

}

.btn-primary:hover {

    background: #1d4ed8;

    transform: translateY(-2px);

}


/* =========================================================
   BLANK PAGE BUTTON
   ========================================================= */

.blank-page-button {

    width: 100%;

    min-height: 70px;

    margin-top: 20px;

    border: 1px solid #64748b;

    border-radius: 14px;

    background: #263449;

    color: #ffffff;

    font-size: 17px;

    font-weight: 700;

    transition: .3s;

    display: flex;

    align-items: center;

    justify-content: center;

    gap: 10px;

}

.blank-page-button:hover {

    background: #334155;

    border-color: #94a3b8;

    transform: translateY(-2px);

    box-shadow: 0 10px 25px rgba(0,0,0,.25);

}

.blank-page-button i {

    font-size: 24px;

    color: #f8fafc;

}


/* =========================================================
   DIVIDER
   ========================================================= */

.choice-divider {

    display: flex;

    align-items: center;

    gap: 12px;

    margin: 25px 0 10px 0;

    color: #64748b;

    font-size: 13px;

    font-weight: 600;

}

.choice-divider::before,
.choice-divider::after {

    content: "";

    flex: 1;

    height: 1px;

    background: #334155;

}


/* =========================================================
   PREVIEW
   ========================================================= */

#previewBox {

    animation: fadeIn .35s ease;

}

.progress {

    background: #334155;

    border-radius: 20px;

    overflow: hidden;

}

.progress-bar {

    background: #22c55e;

}

.card.bg-dark {

    background: #162033 !important;

    border-radius: 15px;

}

#fileName {

    color: #ffffff;

    font-weight: 600;

}

#fileSize {

    color: #94a3b8 !important;

}

#fileType {

    font-size: 13px;

    padding: 8px 15px;

}


/* =========================================================
   CONTINUE BUTTON
   ========================================================= */

#continueBtn {

    height: 58px;

    font-size: 18px;

    font-weight: 700;

}


/* =========================================================
   ALERT
   ========================================================= */

.alert {

    border: none;

    border-radius: 12px;

}


/* =========================================================
   HR
   ========================================================= */

hr {

    border-color: #334155;

}


/* =========================================================
   SCROLLBAR
   ========================================================= */

::-webkit-scrollbar {

    width: 10px;

}

::-webkit-scrollbar-track {

    background: #0f172a;

}

::-webkit-scrollbar-thumb {

    background: #334155;

    border-radius: 20px;

}

::-webkit-scrollbar-thumb:hover {

    background: #475569;

}


/* =========================================================
   ANIMATION
   ========================================================= */

@keyframes fadeIn {

    from {

        opacity: 0;

        transform: translateY(20px);

    }

    to {

        opacity: 1;

        transform: translateY(0);

    }

}


/* =========================================================
   MOBILE
   ========================================================= */

@media(max-width:992px) {

    .main-container {

        padding: 20px;

    }

    .upload-area {

        min-height: 280px;

    }

    .upload-icon {

        width: 85px;

        height: 85px;

        font-size: 38px;

    }

    .printer-title {

        font-size: 22px;

    }

}

@media(max-width:576px) {

    .upload-area {

        padding: 20px;

    }

    .upload-content {

        padding: 15px;

    }

    .logo {

        font-size: 28px;

    }

    .subtitle {

        font-size: 13px;

    }

    #continueBtn {

        font-size: 16px;

        height: 54px;

    }

    .blank-page-button {

        min-height: 64px;

        font-size: 15px;

    }

}

</style>

</head>

<body>


<div class="main-container">


<!-- =====================================================
     HEADER
     ===================================================== -->

<div class="text-center">

    <div class="logo">

        🖨 SmartPrint

    </div>

    <div class="subtitle">

        Fast • Secure • Automatic Printing

    </div>

</div>


<?php if ($error): ?>


<!-- =====================================================
     ERROR
     ===================================================== -->

<div class="alert alert-danger">

    <?= htmlspecialchars($error) ?>

</div>


<?php else: ?>


<div class="row g-4">


<!-- =====================================================
     LEFT SIDE
     PRINTER INFORMATION
     ===================================================== -->

<div class="col-lg-4">

<div class="card-dark p-4">


    <div class="printer-title">

        <?= htmlspecialchars($printer['printer_name']) ?>

    </div>


    <hr class="border-secondary">


    <!-- PRINTER CODE -->

    <div class="mb-3">

        <div class="info-label">

            Printer Code

        </div>

        <div class="info-value">

            <?= htmlspecialchars($printer['printer_code']) ?>

        </div>

    </div>


    <!-- LOCATION -->

    <div class="mb-3">

        <div class="info-label">

            Location

        </div>

        <div class="info-value">

            <?= htmlspecialchars($printer['location']) ?>

        </div>

    </div>


    <!-- STATUS -->

    <div class="mb-4">

        <div class="info-label">

            Status

        </div>

        <div class="info-value">

            <?php if ($printer['status'] == "ONLINE"): ?>

                <span class="online">

                    <i class="bi bi-circle-fill"></i>

                    ONLINE

                </span>

            <?php else: ?>

                <span class="offline">

                    <i class="bi bi-circle-fill"></i>

                    <?= htmlspecialchars($printer['status']) ?>

                </span>

            <?php endif; ?>

        </div>

    </div>


    <!-- FEATURES -->

    <div class="feature">

        <i class="bi bi-file-earmark-pdf-fill"></i>

        PDF Printing

    </div>


    <div class="feature">

        <i class="bi bi-file-earmark-word-fill"></i>

        Word Documents

    </div>


    <div class="feature">

        <i class="bi bi-image-fill"></i>

        Images

    </div>


    <div class="feature">

        <i class="bi bi-printer-fill"></i>

        <?=

        $printer['supports_color']

        ?

        "Color Printing"

        :

        "Black & White Only"

        ?>

    </div>


    <div class="feature">

        <i class="bi bi-files"></i>

        <?=

        $printer['supports_duplex']

        ?

        "Duplex Supported"

        :

        "Single Side Only"

        ?>

    </div>


    <!-- BLANK PAGE INFORMATION -->

    <div class="feature">

        <i class="bi bi-file-earmark"></i>

        Blank Page Available

    </div>


</div>

</div>


<!-- =====================================================
     RIGHT SIDE
     ===================================================== -->

<div class="col-lg-8">

<div class="card-dark p-4 h-100">


    <h3 class="mb-3">

        Select Printing Service

    </h3>


    <p class="text-secondary mb-4">

        Upload a document to print, or choose a blank page.

    </p>


    <!-- =================================================
         NORMAL DOCUMENT FORM
         ================================================= -->

    <form

        id="uploadForm"

        action="process_upload.php"

        method="POST"

        enctype="multipart/form-data">


        <!-- PRINTER ID -->

        <input

            type="hidden"

            name="printer_id"

            value="<?= htmlspecialchars($printer['id']) ?>"
        >


        <!-- PRINT MODE -->

        <input

            type="hidden"

            name="print_mode"

            value="DOCUMENT"
        >


        <!-- =================================================
             UPLOAD AREA
             ================================================= -->

        <div

            id="dropArea"

            class="upload-area">


            <div class="upload-content">


                <div class="upload-icon">

                    <i class="bi bi-cloud-arrow-up-fill"></i>

                </div>


                <h4>

                    Upload Your Document

                </h4>


                <p class="text-secondary">

                    Drag & Drop File Here

                </p>


                <p class="text-secondary">

                    or

                </p>


                <label

                    for="document"

                    class="btn btn-primary">


                    <i class="bi bi-folder2-open"></i>

                    Browse Files


                </label>


                <input

                    id="document"

                    type="file"

                    name="document"

                    accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"

                    hidden

                    required
                >


                <!-- SUPPORTED FORMATS -->

                <div class="mt-3">

                    <small>

                        Supported Formats

                    </small>

                    <br>


                    <span class="badge bg-danger">

                        PDF

                    </span>


                    <span class="badge bg-primary">

                        DOC

                    </span>


                    <span class="badge bg-primary">

                        DOCX

                    </span>


                    <span class="badge bg-success">

                        JPG

                    </span>


                    <span class="badge bg-success">

                        PNG

                    </span>

                </div>


            </div>

        </div>


        <!-- =================================================
             PREVIEW
             ================================================= -->

        <div

            id="previewBox"

            class="mt-4"

            style="display:none;">


            <div class="card bg-dark border-secondary">


                <div class="card-body">


                    <div

                        class="d-flex justify-content-between align-items-center">


                        <div>

                            <h5

                                id="fileName"

                                class="mb-1">

                            </h5>


                            <small

                                id="fileSize"

                                class="text-secondary">

                            </small>

                        </div>


                        <div>

                            <span

                                id="fileType"

                                class="badge bg-info">

                            </span>

                        </div>


                    </div>


                    <div

                        class="progress mt-3"

                        style="height:8px;">


                        <div

                            id="progressBar"

                            class="progress-bar progress-bar-striped progress-bar-animated"

                            style="width:0%;">

                        </div>


                    </div>


                </div>

            </div>

        </div>


        <!-- =================================================
             UPLOAD FEATURES
             ================================================= -->

        <div class="row mt-4">


            <div class="col-md-6">

                <div class="feature">

                    <i class="bi bi-shield-check"></i>

                    Secure Upload

                </div>

            </div>


            <div class="col-md-6">

                <div class="feature">

                    <i class="bi bi-speedometer2"></i>

                    Maximum 50 MB

                </div>

            </div>


        </div>


        <!-- =================================================
             CONTINUE
             ================================================= -->

        <button

            id="continueBtn"

            type="submit"

            class="btn btn-primary btn-lg w-100 mt-4">


            <i class="bi bi-arrow-right-circle-fill"></i>

            Continue

        </button>


    </form>


    <!-- =====================================================
         DIVIDER
         ===================================================== -->

    <div class="choice-divider">

        OR

    </div>


    <!-- =====================================================
         BLANK PAGE
         ===================================================== -->

    <form

        id="blankPageForm"

        action="price.php"

        method="GET">


        <input

            type="hidden"

            name="blank_page"

            value="1"
        >


        <input

            type="hidden"

            name="printer"

            value="<?= htmlspecialchars($token) ?>"
        >


        <button

            type="submit"

            id="blankPageBtn"

            class="blank-page-button">


            <i class="bi bi-file-earmark"></i>


            <span>

                Print Blank Page

            </span>


        </button>


    </form>


    <div class="text-center mt-2">

        <small class="text-secondary">

            Print a completely blank sheet without uploading a document.

        </small>

    </div>


</div>

</div>

</div>


<?php endif; ?>


<script>

/* =========================================================
   ELEMENTS
   ========================================================= */

const dropArea = document.getElementById("dropArea");

const fileInput = document.getElementById("document");

const previewBox = document.getElementById("previewBox");

const fileName = document.getElementById("fileName");

const fileSize = document.getElementById("fileSize");

const fileType = document.getElementById("fileType");

const progressBar = document.getElementById("progressBar");

const form = document.getElementById("uploadForm");

const blankPageForm = document.getElementById("blankPageForm");


/* =========================================================
   NORMAL UPLOAD ELEMENTS EXIST?
   ========================================================= */

if (dropArea && fileInput && form) {


    /* =====================================================
       OPEN FILE BROWSER
       ===================================================== */

    dropArea.addEventListener("click", function(e) {

        /*
         * Prevent clicking the label from opening
         * the browser twice.
         */

        if (e.target.closest("label")) {

            return;

        }

        fileInput.click();

    });


    /* =====================================================
       DRAG OVER
       ===================================================== */

    dropArea.addEventListener("dragover", function(e) {

        e.preventDefault();

        dropArea.classList.add("dragover");

    });


    /* =====================================================
       DRAG LEAVE
       ===================================================== */

    dropArea.addEventListener("dragleave", function() {

        dropArea.classList.remove("dragover");

    });


    /* =====================================================
       DROP
       ===================================================== */

    dropArea.addEventListener("drop", function(e) {

        e.preventDefault();

        dropArea.classList.remove("dragover");

        if (e.dataTransfer.files.length > 0) {

            fileInput.files = e.dataTransfer.files;

            previewSelectedFile();

        }

    });


    /* =====================================================
       FILE SELECTED
       ===================================================== */

    fileInput.addEventListener(

        "change",

        previewSelectedFile

    );


    /* =====================================================
       PREVIEW FUNCTION
       ===================================================== */

    function previewSelectedFile() {

        const file = fileInput.files[0];

        if (!file) {

            return;

        }


        /* ================================================
           MAX 50 MB
           ================================================ */

        if (file.size > (50 * 1024 * 1024)) {

            alert("Maximum upload size is 50 MB.");

            fileInput.value = "";

            previewBox.style.display = "none";

            return;

        }


        /* ================================================
           ALLOWED TYPES
           ================================================ */

        const allowed = [

            "application/pdf",

            "application/msword",

            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",

            "image/jpeg",

            "image/png"

        ];


        if (!allowed.includes(file.type)) {

            alert("Unsupported file type.");

            fileInput.value = "";

            previewBox.style.display = "none";

            return;

        }


        /* ================================================
           SHOW PREVIEW
           ================================================ */

        previewBox.style.display = "block";


        fileName.innerHTML = file.name;


        fileSize.innerHTML = formatBytes(

            file.size

        );


        fileType.innerHTML = file.name

            .split(".")

            .pop()

            .toUpperCase();


        animateProgress();

    }


    /* =====================================================
       FAKE PROGRESS
       ===================================================== */

    function animateProgress() {

        let width = 0;

        progressBar.style.width = "0%";


        const timer = setInterval(function() {

            width += 5;

            progressBar.style.width = width + "%";


            if (width >= 100) {

                clearInterval(timer);

            }

        }, 20);

    }


    /* =====================================================
       BYTES FORMATTER
       ===================================================== */

    function formatBytes(bytes) {

        if (bytes === 0) {

            return "0 Bytes";

        }


        const k = 1024;


        const sizes = [

            "Bytes",

            "KB",

            "MB",

            "GB"

        ];


        const i = Math.floor(

            Math.log(bytes) / Math.log(k)

        );


        return parseFloat(

            (

                bytes /

                Math.pow(k, i)

            ).toFixed(2)

        ) + " " + sizes[i];

    }


    /* =====================================================
       NORMAL UPLOAD VALIDATION
       ===================================================== */

    form.addEventListener("submit", function(e) {

        if (fileInput.files.length === 0) {

            e.preventDefault();

            alert("Please select a document.");

            return;

        }

    });

}


/* =========================================================
   BLANK PAGE FORM
   ========================================================= */

if (blankPageForm) {

    blankPageForm.addEventListener(

        "submit",

        function() {

            /*
             * Blank Page does NOT use the document upload.
             *
             * The following values are sent:
             *
             * blank_page=1
             * printer=<printer QR token>
             *
             * price.php will then recognize that this
             * is a BLANK printing request.
             */

        }

    );

}

</script>


</body>

</html>