<?php
session_start();

if (!isset($_SESSION["user_id"]) || !in_array($_SESSION["role"], ["customer","company_admin"])) {
    header("Location: ../auth/login.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Scan Customer QR</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://unpkg.com/html5-qrcode"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 12px;
        }

        .container {
            max-width: 520px;
            margin: auto;
        }

        .card {
            background: white;
            border-radius: 16px;
            padding: 16px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.08);
        }

        h1 {
            margin: 0 0 8px;
            color: #111827;
            font-size: 24px;
            text-align: center;
        }

        .subtitle {
            color: #6b7280;
            margin: 0 0 12px;
            text-align: center;
            font-size: 14px;
        }

        #reader {
            width: 100%;
            margin: 0 auto 14px;
            border-radius: 14px;
            overflow: hidden;
            background: #000;
        }

        .success-box {
            display: none;
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            text-align: center;
        }

        .error-box {
            display: none;
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            text-align: center;
        }

        .actions {
            display: flex;
            gap: 10px;
            margin-top: 12px;
        }

        .btn {
            flex: 1;
            padding: 12px;
            border-radius: 8px;
            text-decoration: none;
            text-align: center;
            font-size: 14px;
        }

        .btn-primary {
            background: #2563eb;
            color: white;
        }

        .btn-gray {
            background: #6b7280;
            color: white;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="card">

        <h1>Scan Customer QR</h1>
        <p class="subtitle">Point camera at receiver QR code.</p>

        <div id="successMessage" class="success-box">
            QR detected. Redirecting...
        </div>

        <div id="errorMessage" class="error-box">
            Camera could not open. Please allow camera permission.
        </div>

        <div id="reader"></div>

        <div class="actions">
            <a class="btn btn-gray" href="dashboard.php">Back</a>
            <a class="btn btn-primary" href="transfer.php">Enter Code</a>
        </div>

    </div>
</div>

<script>
let html5QrCode = new Html5Qrcode("reader");
let scanned = false;

function onScanSuccess(decodedText) {
    if (scanned) return;
    scanned = true;

    let raw = (decodedText || "").trim();
    let customerCode = "";
    let shopCode = "";

    /* 1) If the QR is a URL, read its ?to= (customer) or ?code= (shop) parameter */
    try {
        const url = new URL(raw);
        customerCode = url.searchParams.get("to")   || "";
        shopCode     = url.searchParams.get("code") || "";
    } catch (e) {
        /* not a URL — treat the whole string as a raw code */
        customerCode = raw;
    }

    /* 2) Fallback: detect a CUS… or SHOP… code anywhere in the scanned text */
    if (!customerCode && !shopCode) {
        const m = raw.toUpperCase().match(/\b(CUS|SHOP)[A-Z0-9]+\b/);
        if (m) {
            if (m[1] === "SHOP") shopCode = m[0];
            else                 customerCode = m[0];
        }
    }

    /* 3) Clean the codes: keep letters/digits only, uppercase */
    if (customerCode) customerCode = customerCode.replace(/[^A-Za-z0-9]/g, "").toUpperCase();
    if (shopCode)     shopCode     = shopCode.replace(/[^A-Za-z0-9]/g, "").toUpperCase();

    /* 4) Ignore the generic app link (login QR) — it has no code */
    if (!customerCode && !shopCode) {
        scanned = false;
        alert("This isn't a customer or shop QR code. Ask them to open \"My QR\" first.");
        startCamera();
        return;
    }

    document.getElementById("successMessage").style.display = "block";

    html5QrCode.stop().then(function () {
        if (shopCode) {
            window.location.href = "pay_shop.php?code=" + encodeURIComponent(shopCode);
            return;
        }
        if (customerCode) {
            window.location.href = "transfer.php?to=" + encodeURIComponent(customerCode);
            return;
        }
    }).catch(function () {
        /* even if stopping the camera fails, still navigate */
        if (shopCode)         window.location.href = "pay_shop.php?code=" + encodeURIComponent(shopCode);
        else if (customerCode) window.location.href = "transfer.php?to=" + encodeURIComponent(customerCode);
    });
}

function startCamera() {
    html5QrCode.start(
        { facingMode: "environment" },
        {
            fps: 10,
            qrbox: { width: 260, height: 260 }
        },
        onScanSuccess
    ).catch(function () {
        document.getElementById("errorMessage").style.display = "block";
    });
}

window.onload = startCamera;
</script>

</body>
</html>