<?php
session_start();
$password = "error404"; // Set your password here

// Handle logout
if (isset($_GET['logout']) && $_GET['logout'] == '1') {
    session_unset();
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['password']) && $_POST['password'] === $password) {
        $_SESSION['authenticated'] = true;
        header("Location: " . $_SERVER['PHP_SELF']); // Prevent resubmission on refresh
        exit;
    } else {
        $error = "Incorrect password.";
    }
}

// If not authenticated, show login form only
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true): ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login Required</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <script src="plotly-min.js"></script>
    <style>
        :root{
            --bg:#0f1115;
            --panel:#15181c;
            --muted:#9aa3b2;
            --text:#e6eef6;
            --accent:#0d6efd;
            --danger:#dc3545;
        }
        html,body{ background:var(--bg); color:var(--text); }
        .form-control{ background:transparent; color:var(--text); border:1px solid rgba(255,255,255,0.06); }
        .bg-white{ background:transparent !important; }
        .border{ border-color: rgba(255,255,255,0.06) !important; }
        .alert{ background: rgba(255,255,255,0.02); color:var(--text); border:1px solid rgba(255,255,255,0.03); }
        .btn-primary{ background:var(--accent); border-color:var(--accent); color:#fff; }
        .btn-danger{ background:var(--danger); border-color:var(--danger); color:#fff; }
        a{ color:var(--accent); }
    </style>
</head>
<body class="d-flex align-items-center justify-content-center vh-100">
    <form method="POST" class="p-4 border rounded bg-white shadow-sm" style="width:320px;">
        <h4 class="mb-3">Enter Password</h4>
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <div class="mb-3">
            <input type="password" name="password" class="form-control" placeholder="Password" required autofocus>
        </div>
        <button type="submit" class="btn btn-primary w-100">Login</button>
    </form>
</body>
</html>
<?php exit; endif; ?>

<!-- Authenticated content starts here -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conor Home</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <script src="plotly-min.js"></script>
    <style>
        :root{
            --bg:#0f1115;
            --panel:#15181c;
            --muted:#9aa3b2;
            --text:#e6eef6;
            --accent:#0d6efd;
            --danger:#dc3545;
        }
        html,body{ background:var(--bg); color:var(--text); }
        .sidebar { min-height: 100vh; background:var(--panel); color:var(--text); }
        /* Override Bootstrap utilities that would apply a light background */
        .sidebar.bg-light,
        .bg-light.sidebar { background:var(--panel) !important; color:var(--text) !important; }
        .sidebar.border-end { border-right: 1px solid rgba(255,255,255,0.06) !important; }
        .sidebar h4{ color:var(--text) !important; }
        .sidebar .btn{ color:#fff !important; }
        .form-control{ background:transparent; color:var(--text); border:1px solid rgba(255,255,255,0.06); }

        /* Modern dark table styles */
        .table{ color:var(--text); }
        .table-modern{
            width:100%;
            border-collapse:separate;
            border-spacing:0;
            background: var(--panel) !important;
            border-radius:8px;
            overflow:hidden;
            box-shadow: 0 6px 18px rgba(0,0,0,0.6);
        }
        .table-modern thead th{
            background: linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0.01));
            color:var(--text) !important;
            font-weight:600;
            border-bottom:1px solid rgba(255,255,255,0.06);
            padding:12px 16px;
            text-align:left;
        }
        .table-modern tbody td{
            padding:12px 16px;
            border-bottom:1px solid rgba(255,255,255,0.02);
            color:var(--text) !important;
            background: transparent !important;
        }
        /* Ensure no white backgrounds from Bootstrap leak in */
        .table, .table th, .table td, .table-modern tr{ background: transparent !important; }
        .table-modern{ background: var(--panel) !important; }
        .table-modern tbody tr:hover{ background: rgba(255,255,255,0.02); }
        .table-modern th:first-child{ border-top-left-radius:8px; }
        .table-modern th:last-child{ border-top-right-radius:8px; }
        .table-modern tr:last-child td:first-child{ border-bottom-left-radius:8px; }
        .table-modern tr:last-child td:last-child{ border-bottom-right-radius:8px; }
        .table-striped>tbody>tr:nth-of-type(odd){ background: rgba(255,255,255,0.02); }
        .table-striped>tbody>tr:nth-of-type(even){ background: rgba(255,255,255,0.01); }
        .btn-primary{ background:var(--accent); border-color:var(--accent); color:#fff; }
        .btn-danger{ background:var(--danger); border-color:var(--danger); color:#fff; }
        
        /* Time range button styling */
        .view-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        .view-buttons button {
            background: rgba(255,255,255,0.03);
            border: 1px solid rgba(255,255,255,0.1);
            color: var(--text);
            padding: 8px 20px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .view-buttons button:hover {
            background: rgba(255,255,255,0.06);
            border-color: rgba(255,255,255,0.2);
            transform: translateY(-1px);
        }
        .view-buttons button.active {
            background: var(--accent);
            border-color: var(--accent);
            color: #fff;
            box-shadow: 0 4px 12px rgba(13,110,253,0.3);
        }
        
        /* Market chart full width */
        #c-market {
            width: 100%;
            max-width: 100%;
        }
        #market-chart {
            width: 100% !important;
            max-width: 100%;
        }
    </style>
</head>
<body>

<div class="container-fluid">
    <div class="row">
        <aside class="col-12 col-md-3 col-lg-2 bg-light sidebar border-end p-3">
            <h4>Menu</h4>
            <div class="d-grid gap-2">
                <button type="button" class="btn btn-primary" data-to-show="c-dashboard">Dashboard</button>
                <button type="button" class="btn btn-primary" data-to-show="c-space">Space</button>
                    <button type="button" class="btn btn-primary" data-to-show="c-market">Market Data Analytics</button>
                <a href="?logout=1" class="btn btn-danger">Log Out</a>
            </div>
        </aside>

        <main class="col p-4">
            <div class="container c-item" id="c-dashboard">
                <h2>Dashboard</h2>
                <p>Welcome — select a view from the left.</p>
            </div>

            <div class="container d-none c-item" id="c-space">
<?php
// Function to get disk usage for a specific directory
function getDiskUsage($directory) {
    $totalSpace = @disk_total_space($directory);
    $freeSpace = @disk_free_space($directory);
    $usedSpace = $totalSpace - $freeSpace;

    return [
        'total' => $totalSpace,
        'free' => $freeSpace,
        'used' => $usedSpace
    ];
}

// Function to format bytes into a more readable format
function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1024, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
}

// Define the specific directories to check
$directories = [
    '/',
    '/mnt/drives/10c',
    '/mnt/drives/10tb_new',
    '/mnt/drives/4tb',
    '/mnt/drives/10tb'
];

// Create an array to hold the results
$diskUsages = [];

// Check each directory
foreach ($directories as $directory) {
    $usage = getDiskUsage($directory);
    if ($usage['total'] !== false && $usage['free'] !== false) {
        $diskUsages[$directory] = $usage;
    }
}
?>
                <h3>Disk Usage</h3>
                <table class="table table-striped table-modern">
                    <thead>
                        <tr>
                            <th>Directory</th>
                            <th>Total Space</th>
                            <th>Used Space</th>
                            <th>Free Space</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($diskUsages as $directory => $usage): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($directory); ?></td>
                            <td><?php echo formatBytes($usage['total']); ?></td>
                            <td><?php echo formatBytes($usage['used']); ?></td>
                            <td><?php echo formatBytes($usage['free']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>

                <h2 class="mt-4">10TB</h2>
                <ul>
                    <li>Audiobooks</li>
                    <li>Backup</li>
                    <li>logs</li>
                    <li>Music</li>
                    <li>Sync</li>
                    <li>Sync2</li>
                    <li>TV</li>
                    <li>Videos</li>
                    <li>web_servers</li>
                </ul>

                <h2 class="mt-4">10TB New</h2>
                <ul>
                    <li>ciaras folder</li>
                    <li>conor's stuff</li>
                    <li>software storage</li>
                    <li>the archive</li>
                    <li>tv2</li>
                    <li>videos2</li>
                </ul>

                <h2 class="mt-4">4TB</h2>
                <ul>
                    <li>Educational</li>
                    <li>Movies</li>
                </ul>

                <h2 class="mt-4">4TB Old</h2>
                <ul>
                    <li>Anime</li>
                </ul>
            </div>

            <?php
            // Database connection for page views
            $db_host = 'localhost';
            $db_port = 3303;
            $db_name = 'trading_dashboard';
            $db_user = 'asx_trading_dashboard_user';
            $db_pass = 'VFBG87CDHJNU65H097JNKM8L';

            // Market data analytics: prepare hourly counts and IP list
            $selected_range = isset($_GET['range']) ? $_GET['range'] : '24h';
            $valid_ranges = array('24h', '3d', '5d', '7d', '30d');
            if (!in_array($selected_range, $valid_ranges)) {
                $selected_range = '24h';
            }

            $days_back = 1;
            if ($selected_range === '3d') $days_back = 3;
            elseif ($selected_range === '5d') $days_back = 5;
            elseif ($selected_range === '7d') $days_back = 7;
            elseif ($selected_range === '30d') $days_back = 30;

            $cutoff_time = strtotime("-$days_back days");

            $log_file = '/var/log/apache2/marketdata-access.log';
            $request_counts = array();
            $hour_labels = array();
            $ip_counts = array();
            $excluded_ip = '103.81.124.5';

            if (file_exists($log_file)) {
                $lines = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                foreach ($lines as $line) {
                    preg_match('/^([\d\.]+)/', $line, $ip_match);
                    $ip_address = isset($ip_match[1]) ? $ip_match[1] : 'Unknown';

                    if (preg_match('/\[(\d{2})\/(\w{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2})\s+([^\]]+)\]/', $line, $matches)) {
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        $hour = $matches[4];

                        $months = array('Jan' => '01', 'Feb' => '02', 'Mar' => '03', 'Apr' => '04', 'May' => '05', 'Jun' => '06',
                                       'Jul' => '07', 'Aug' => '08', 'Sep' => '09', 'Oct' => '10', 'Nov' => '11', 'Dec' => '12');
                        $month_num = isset($months[$month]) ? $months[$month] : '01';

                        $entry_time = strtotime("$year-$month_num-$day $hour:00:00");

                        if ($entry_time >= $cutoff_time) {
                            $hour_key = "$year-$month_num-$day $hour:00";

                            $hour_int = intval($hour);
                            if ($hour_int == 0) { $display_hour = 12; $ampm = 'AM'; }
                            elseif ($hour_int < 12) { $display_hour = $hour_int; $ampm = 'AM'; }
                            elseif ($hour_int == 12) { $display_hour = 12; $ampm = 'PM'; }
                            else { $display_hour = $hour_int - 12; $ampm = 'PM'; }

                            $label = str_pad($day, 2, '0', STR_PAD_LEFT) . " $month " . str_pad($display_hour, 2, '0', STR_PAD_LEFT) . " $ampm";

                            if ($ip_address !== $excluded_ip) {
                                if (!isset($request_counts[$hour_key])) {
                                    $request_counts[$hour_key] = 0;
                                    $hour_labels[$hour_key] = $label;
                                }
                                $request_counts[$hour_key]++;
                            }

                            if (!isset($ip_counts[$ip_address])) $ip_counts[$ip_address] = 0;
                            $ip_counts[$ip_address]++;
                        }
                    }
                }
            }

            arsort($ip_counts);
            ksort($request_counts);

            $paths = array();
            $counts = array();
            foreach ($request_counts as $hour_key => $count) {
                $paths[] = $hour_labels[$hour_key];
                $counts[] = $count;
            }

            // Query page views from database
            $page_view_data = array();
            $page_view_labels = array();
            $all_routes = array();

            try {
                $pdo = new PDO("mysql:host=$db_host;port=$db_port;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // Always use daily grouping for page views chart (each bar = 24 hours)
                $group_format = '%Y-%m-%d';
                $label_format = '%d %b';

                $sql = "SELECT
                            page_route,
                            DATE_FORMAT(viewed_at, :group_format) as time_bucket,
                            DATE_FORMAT(viewed_at, :label_format) as time_label,
                            COUNT(*) as view_count
                        FROM page_views
                        WHERE viewed_at >= DATE_SUB(NOW(), INTERVAL :days DAY)
                        GROUP BY page_route, time_bucket, time_label
                        ORDER BY time_bucket ASC, page_route ASC";

                $stmt = $pdo->prepare($sql);
                $stmt->execute(array(
                    ':group_format' => $group_format,
                    ':label_format' => $label_format,
                    ':days' => $days_back
                ));

                $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

                // Organize data by route
                foreach ($results as $row) {
                    $route = $row['page_route'];
                    $time_bucket = $row['time_bucket'];
                    $time_label = $row['time_label'];
                    $count = (int)$row['view_count'];

                    if (!isset($page_view_data[$route])) {
                        $page_view_data[$route] = array();
                        $all_routes[] = $route;
                    }
                    $page_view_data[$route][$time_bucket] = array(
                        'label' => $time_label,
                        'count' => $count
                    );

                    if (!isset($page_view_labels[$time_bucket])) {
                        $page_view_labels[$time_bucket] = $time_label;
                    }
                }

                ksort($page_view_labels);

            } catch (PDOException $e) {
                $page_view_error = $e->getMessage();
            }
            ?>

            <div class="d-none c-item" id="c-market">
                <h2>Market Data Analytics</h2>

                <div class="view-buttons">
                    <form method="GET" style="display:inline;"><input type="hidden" name="load_tab" value="c-market"><button type="submit" name="range" value="24h" <?php echo $selected_range === '24h' ? 'class="active"' : ''; ?>>24 Hour</button></form>
                    <form method="GET" style="display:inline;"><input type="hidden" name="load_tab" value="c-market"><button type="submit" name="range" value="3d" <?php echo $selected_range === '3d' ? 'class="active"' : ''; ?>>3 Day</button></form>
                    <form method="GET" style="display:inline;"><input type="hidden" name="load_tab" value="c-market"><button type="submit" name="range" value="5d" <?php echo $selected_range === '5d' ? 'class="active"' : ''; ?>>5 Day</button></form>
                    <form method="GET" style="display:inline;"><input type="hidden" name="load_tab" value="c-market"><button type="submit" name="range" value="7d" <?php echo $selected_range === '7d' ? 'class="active"' : ''; ?>>7 Day</button></form>
                    <form method="GET" style="display:inline;"><input type="hidden" name="load_tab" value="c-market"><button type="submit" name="range" value="30d" <?php echo $selected_range === '30d' ? 'class="active"' : ''; ?>>30 Day</button></form>
                </div>

                <div id="market-chart" style="width:calc(100% + 3rem);height:480px;margin-top:20px;margin-left:-1.5rem;margin-right:-1.5rem;"></div>

                <div id="page-views-chart" style="width:calc(100% + 3rem);height:480px;margin-top:30px;margin-left:-1.5rem;margin-right:-1.5rem;"></div>

                <?php if (isset($page_view_error)): ?>
                    <div class="alert" style="background:rgba(220,53,69,0.1);border:1px solid rgba(220,53,69,0.3);color:#ff6b6b;padding:12px;border-radius:6px;margin-top:20px;">
                        Database error: <?php echo htmlspecialchars($page_view_error); ?>
                    </div>
                <?php endif; ?>

                <script>
                    (function(){
                        var pageViewLabels = <?php echo json_encode(array_values($page_view_labels)); ?>;
                        var pageViewBuckets = <?php echo json_encode(array_keys($page_view_labels)); ?>;
                        var pageViewData = <?php echo json_encode($page_view_data); ?>;
                        var allRoutes = <?php echo json_encode($all_routes); ?>;

                        var traces = [];
                        var colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'];

                        allRoutes.forEach(function(route, index) {
                            var xVals = [];
                            var yVals = [];

                            pageViewBuckets.forEach(function(bucket, i) {
                                xVals.push(pageViewLabels[i]);
                                if (pageViewData[route] && pageViewData[route][bucket]) {
                                    yVals.push(pageViewData[route][bucket].count);
                                } else {
                                    yVals.push(0);
                                }
                            });

                            traces.push({
                                x: xVals,
                                y: yVals,
                                type: 'bar',
                                name: route,
                                marker: { color: colors[index % colors.length] }
                            });
                        });

                        var layout = {
                            title: 'Page Views by Route',
                            xaxis: { title: 'Time' },
                            yaxis: { title: 'Page Views' },
                            barmode: 'group',
                            plot_bgcolor: 'rgba(0,0,0,0)',
                            paper_bgcolor: 'rgba(0,0,0,0)',
                            font: { color: '#e6eef6' },
                            legend: { orientation: 'h', y: -0.2 }
                        };

                        if (traces.length > 0) {
                            Plotly.newPlot('page-views-chart', traces, layout, {responsive: true});
                            // Force resize after render to ensure 100% width
                            setTimeout(function() {
                                Plotly.Plots.resize('page-views-chart');
                            }, 50);
                            setTimeout(function() {
                                Plotly.Plots.resize('page-views-chart');
                            }, 200);
                        } else {
                            document.getElementById('page-views-chart').innerHTML = '<p style="text-align:center;color:#9aa3b2;padding:40px;">No page view data available for this time range.</p>';
                        }
                    })();
                </script>

                <div class="ip-table-container" style="margin-top:30px;padding:20px;background:rgba(255,255,255,0.02);border-radius:8px;">
                    <h3>Requests by IP Address</h3>
                    <table class="table table-striped table-modern" style="margin-top:12px;">
                        <thead>
                            <tr><th>IP Address</th><th>Request Count</th></tr>
                        </thead>
                        <tbody>
                        <?php foreach ($ip_counts as $ip => $count): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($ip); ?></td>
                                <td><?php echo number_format($count); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <script>
                    (function(){
                        var paths = <?php echo json_encode($paths); ?>;
                        var counts = <?php echo json_encode($counts); ?>;
                        var trace = { x: paths, y: counts, type: 'bar', marker: { color: '#1f77b4' } };
                        var layout = { title: 'API Requests by Hour', xaxis:{title:'Time'}, yaxis:{title:'Number of Requests'}, plot_bgcolor: 'rgba(0,0,0,0)', paper_bgcolor:'rgba(0,0,0,0)', font:{color:'#e6eef6'} };
                        Plotly.newPlot('market-chart', [trace], layout, {responsive:true});
                    })();
                </script>
            </div>
        </main>
    </div>
</div>

</body>

<script src="scripts.js"></script>
<script src="bootstrap.min.js"></script>
</html>