<?php
/**
 * Lucas IT Services - Time Duration Calculator
 * Path: /var/www/html/tools/time-dur/index.php
 */

declare(strict_types=1);

session_start();

// Read theme preference directly from cookie for SSR consistency
$current_theme = $_COOKIE['theme'] ?? 'dark';
if (!in_array($current_theme, ['dark', 'light'], true)) {
    $current_theme = 'dark';
}

// Generate CSRF token if not present
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$output_json = "";
$json_data   = null;
$cmd_used    = "";
$error_msg   = "";

/**
 * Validates date/time string length and character safety.
 */
function validate_datetime_input(string $input): bool {
    $trimmed = trim($input);
    if (strlen($trimmed) < 1 || strlen($trimmed) > 64) {
        return false;
    }
    return (bool)preg_match('/^[a-zA-Z0-9\s\-\:\/\.\,\+\@]+$/', $trimmed);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. CSRF Token Verification
    $posted_token = $_POST['csrf_token'] ?? '';
    if (!hash_equals($_SESSION['csrf_token'], $posted_token)) {
        $error_msg = "Invalid session token. Please refresh the page and try again.";
    } else {
        $start_raw = $_POST['start'] ?? '';
        $end_raw   = $_POST['end'] ?? '';

        $start = trim((string)$start_raw);
        $end   = trim((string)$end_raw);

        // 2. Input Validation
        if (strlen($start) === 0 || strlen($end) === 0) {
            $error_msg = "Both Start and End date/time inputs are required.";
        } elseif (!validate_datetime_input($start) || !validate_datetime_input($end)) {
            $error_msg = "Invalid characters or length in date/time input.";
        } else {
            // 3. Binary Verification & Execution
            $script_path = "../cgi-bin/time-dur.py";
            if (!is_executable($script_path)) {
                $error_msg = "Backend calculation engine is unavailable or unexecutable.";
            } else {
                $cmd_used = sprintf(
                    '%s -start %s -end %s 2>/dev/null',
                    $script_path,
                    escapeshellarg($start),
                    escapeshellarg($end)
                );

                $output_json = shell_exec($cmd_used);

                if (!empty($output_json)) {
                    $json_data = json_decode((string)$output_json, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $error_msg = "Failed to parse JSON output from backend script.";
                        $json_data = null;
                    } elseif (isset($json_data['status']) && $json_data['status'] === 'error') {
                        $error_msg = $json_data['message'] ?? 'Error executing calculation.';
                        $json_data = null;
                    }
                } else {
                    $error_msg = "No output returned from calculation script.";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html data-theme="<?= htmlspecialchars($current_theme) ?>">
    <head>
        <title>Lucas IT Services - Time Duration Calculator</title>
        <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 50 50'><path fill='%230078d4' fill-rule='evenodd' d='M 25 0 A 24.999868 25.000025 0 0 0 0 25 A 24.999868 25.000025 0 0 0 25 50 A 24.999868 25.000025 0 0 0 50 25 A 24.999868 25.000025 0 0 0 25 0 z M 25 6.9960938 A 18.000229 18.000229 0 0 1 43 24.996094 A 18.000229 18.000229 0 0 1 25 42.996094 A 18.000229 18.000229 0 0 1 7 24.996094 A 18.000229 18.000229 0 0 1 25 6.9960938 z M 24 12 L 26 12 L 26 24.585938 L 33.292969 31.878906 L 31.878906 33.292969 L 24 25.414062 L 24 12 z'/></svg>">
        <link href="../css/style.css" rel="stylesheet" type="text/css">
        <meta charset="UTF-8" />
        <meta name="google" content="notranslate" />
        <meta http-equiv="Content-Language" content="en_US" />
        <style>
            body {
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            .header-bar {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                width: 100%;
                max-width: 1050px;
                box-sizing: border-box;
                position: relative;
                z-index: 10;
            }
            .page-header {
                display: flex;
                align-items: center;
                gap: 20px;
                margin-bottom: 20px;
            }
            .page-header svg {
                width: 64px;
                height: 64px;
                flex-shrink: 0;
            }
            .page-title {
                margin: 0;
                font-size: 2.25rem;
                font-weight: 700;
            }
            .content-wrapper {
                width: 100%;
                max-width: 1050px;
                box-sizing: border-box;
                position: relative;
                z-index: 1;
            }
            .control-row {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 10px;
                margin-bottom: 20px;
            }
            .input-group {
                display: flex;
                align-items: center;
                gap: 6px;
            }
            .meta-heading {
                margin: 25px 0 15px 0;
                font-size: 1.2rem;
                color: var(--text-main);
            }
            .duration-panel {
                background-color: var(--bg-panel);
                border: 1px solid var(--border-color);
                border-radius: 8px;
                padding: 20px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.2);
                box-sizing: border-box;
                margin-bottom: 20px;
            }
            .duration-panel table {
                border-collapse: collapse;
                width: 100%;
                table-layout: fixed;
                font-size: 14px;
            }
            .duration-panel th, .duration-panel td {
                padding: 10px 12px;
                text-align: left;
                vertical-align: middle;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                border-bottom: 1px solid var(--border-color);
            }
            .duration-panel th {
                background-color: #202024;
                color: #fff;
                font-weight: 600;
                border-bottom: 2px solid var(--border-color);
            }
            [data-theme="light"] .duration-panel th {
                background-color: var(--accent);
            }
            .duration-panel tr:last-child td {
                border-bottom: none;
            }
            .duration-panel tr:nth-child(even) td { 
                background-color: var(--table-stripe); 
            }
            .duration-panel tr:nth-child(odd) td { 
                background-color: var(--table-odd); 
            }
            .mono-cell {
                font-family: monospace;
                font-size: 13px;
            }
            .summary-box {
                font-size: 1.4rem;
                font-weight: 700;
                color: var(--accent);
                margin-bottom: 15px;
            }
            .footer-links {
                margin-top: 40px;
                font-size: 14px;
            }
            .footer-links a {
                color: var(--accent);
                text-decoration: none;
            }
            .footer-links a:hover {
                text-decoration: underline;
            }

            @media (max-width: 768px) {
                .header-bar {
                    flex-direction: column;
                    gap: 15px;
                }
                .control-row {
                    flex-direction: column;
                    align-items: stretch;
                }
                .input-group {
                    width: 100%;
                }
                .input-group .input-field {
                    flex-grow: 1;
                }
                .control-row > * {
                    width: 100% !important;
                }
            }
        </style>
    </head>
    <body>
        <div class="header-bar">
            <div class="page-header">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="100%" height="100%">
                    <path fill="var(--accent)" fill-rule="evenodd" d="M 25 0 A 24.999868 25.000025 0 0 0 0 25 A 24.999868 25.000025 0 0 0 25 50 A 24.999868 25.000025 0 0 0 50 25 A 24.999868 25.000025 0 0 0 25 0 z M 25 6.9960938 A 18.000229 18.000229 0 0 1 43 24.996094 A 18.000229 18.000229 0 0 1 25 42.996094 A 18.000229 18.000229 0 0 1 7 24.996094 A 18.000229 18.000229 0 0 1 25 6.9960938 z M 24 12 L 26 12 L 26 24.585938 L 33.292969 31.878906 L 31.878906 33.292969 L 24 25.414062 L 24 12 z" />
                </svg>
                <h1 class="page-title">Time Duration Calculator</h1>
            </div>
            <div style="margin-top: 15px;">
                <button class="button" id="theme-toggle" type="button" onclick="toggleTheme()">Toggle Theme</button>
            </div>
        </div>

        <div class="content-wrapper">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

                <div class="control-row">
                    <div class="input-group">
                        <input type="text" id="start-field" name="start" class="input-field" placeholder="Start Time / Date"
                            value="<?= htmlspecialchars($_POST['start'] ?? '') ?>"
                            style="width: 250px;" autocomplete="off">
                        <button type="button" class="button" onclick="setNow('start-field')">Now</button>
                    </div>

                    <div class="input-group">
                        <input type="text" id="end-field" name="end" class="input-field" placeholder="End Time / Date"
                            value="<?= htmlspecialchars($_POST['end'] ?? '') ?>"
                            style="width: 250px;" autocomplete="off">
                        <button type="button" class="button" onclick="setNow('end-field')">Now</button>
                    </div>

                    <input type="submit" value="Calculate" class="button">
                    <a href="./" class="button">Reset</a>
                </div>
            </form>

            <?php if (!empty($error_msg)): ?>
                <div class="redboxed"><?= htmlspecialchars($error_msg) ?></div>
            <?php endif; ?>

            <?php if ($json_data && isset($json_data['breakdown'])): ?>
                <h3 class="meta-heading">
                    <strong>Calculated Window:</strong> 
                    <?= htmlspecialchars($json_data['normalized']['start'] ?? '') ?> &rarr; 
                    <?= htmlspecialchars($json_data['normalized']['end'] ?? '') ?>
                </h3>

                <div class="duration-panel">
                    <div class="summary-box">
                        Duration: <?= htmlspecialchars($json_data['formatted'] ?? '') ?>
                    </div>

                    <table>
                        <colgroup>
                            <col style="width: 30%;">
                            <col style="width: 70%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th>Unit Breakdown</th>
                                <th>Value</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($json_data['breakdown']['years'])): ?>
                            <tr>
                                <td>Years</td>
                                <td class="mono-cell"><?= (int)$json_data['breakdown']['years'] ?></td>
                            </tr>
                            <?php endif; ?>
                            <?php if (!empty($json_data['breakdown']['days'])): ?>
                            <tr>
                                <td>Days</td>
                                <td class="mono-cell"><?= (int)$json_data['breakdown']['days'] ?></td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <td>Hours</td>
                                <td class="mono-cell"><?= (int)$json_data['breakdown']['hours'] ?></td>
                            </tr>
                            <tr>
                                <td>Minutes</td>
                                <td class="mono-cell"><?= (int)$json_data['breakdown']['minutes'] ?></td>
                            </tr>
                            <tr>
                                <td>Seconds</td>
                                <td class="mono-cell"><?= (int)$json_data['breakdown']['seconds'] ?></td>
                            </tr>
                            <tr>
                                <td><strong>Total Seconds</strong></td>
                                <td class="mono-cell"><strong><?= htmlspecialchars($json_data['total_seconds'] ?? 0) ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <p class="footer-links">
                <a href="index.phps">View Source</a> | <a href="../">Back to Tools</a>
            </p>
        </div>

        <script>
            function setNow(targetId) {
                const now = new Date();
                const pad = (n) => n.toString().padStart(2, '0');
                const formatted = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
                document.getElementById(targetId).value = formatted;
            }

            function setCookie(name, value, days = 365) {
                const d = new Date();
                d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = name + "=" + value + ";path=/;expires=" + d.toUTCString() + ";SameSite=Lax";
            }

            function toggleTheme() {
                const currentTheme = document.documentElement.getAttribute("data-theme") || "dark";
                const newTheme = currentTheme === "dark" ? "light" : "dark";
                document.documentElement.setAttribute("data-theme", newTheme);
                setCookie("theme", newTheme);
            }
        </script>
    </body>
</html>