<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require "Auth/db.php";

/*
|--------------------------------------------------------------------------
| CREATE TABLES
|--------------------------------------------------------------------------
*/

$pdo->exec("
CREATE TABLE IF NOT EXISTS site_status (
    id INT PRIMARY KEY,

    api_status VARCHAR(50) NOT NULL DEFAULT 'Fully Operational',

    database_status VARCHAR(50) NOT NULL DEFAULT 'Fully Operational',

    website_status VARCHAR(50) NOT NULL DEFAULT 'Fully Operational',

    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
)
");

$pdo->exec("
CREATE TABLE IF NOT EXISTS scheduled_maintenance (
    id INT AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255) NOT NULL,

    maintenance_status VARCHAR(50) NOT NULL,

    maintenance_note TEXT,

    starts_at DATETIME NULL,

    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
)
");

/*
|--------------------------------------------------------------------------
| INSERT DEFAULT STATUS ROW
|--------------------------------------------------------------------------
*/

$checkStmt = $pdo->query("
    SELECT COUNT(*)
    FROM site_status
");

$count = (int)$checkStmt->fetchColumn();

if ($count === 0) {

    $stmt = $pdo->prepare("
        INSERT INTO site_status
        (
            id,
            api_status,
            database_status,
            website_status
        )
        VALUES
        (
            1,
            'Fully Operational',
            'Fully Operational',
            'Fully Operational'
        )
    ");

    $stmt->execute();
}

/*
|--------------------------------------------------------------------------
| ADMIN CHECK
|--------------------------------------------------------------------------
*/

$isAdmin =
    isset($_SESSION["user"]) &&
    !empty($_SESSION["user"]["is_admin"]);

/*
|--------------------------------------------------------------------------
| UPDATE STATUS
|--------------------------------------------------------------------------
*/

if ($isAdmin && isset($_POST["update_status"])) {

    $apiStatus = trim($_POST["api_status"] ?? "Fully Operational");

    $databaseStatus = trim($_POST["database_status"] ?? "Fully Operational");

    $websiteStatus = trim($_POST["website_status"] ?? "Fully Operational");

    $stmt = $pdo->prepare("
        UPDATE site_status
        SET
            api_status = ?,
            database_status = ?,
            website_status = ?
        WHERE id = 1
    ");

    $stmt->execute([
        $apiStatus,
        $databaseStatus,
        $websiteStatus
    ]);

    header("Location: Status.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| CREATE MAINTENANCE
|--------------------------------------------------------------------------
*/

if ($isAdmin && isset($_POST["create_maintenance"])) {

    $title = trim($_POST["title"] ?? "");

    $maintenanceStatus = trim($_POST["maintenance_status"] ?? "");

    $maintenanceNote = trim($_POST["maintenance_note"] ?? "");

    $startsAt = trim($_POST["starts_at"] ?? "");

    if (!empty($title)) {

        $stmt = $pdo->prepare("
            INSERT INTO scheduled_maintenance
            (
                title,
                maintenance_status,
                maintenance_note,
                starts_at
            )
            VALUES (?, ?, ?, ?)
        ");

        $stmt->execute([
            $title,
            $maintenanceStatus,
            $maintenanceNote,
            $startsAt
        ]);
    }

    header("Location: Status.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| DELETE MAINTENANCE
|--------------------------------------------------------------------------
*/

if ($isAdmin && isset($_GET["delete_maintenance"])) {

    $deleteId = (int)$_GET["delete_maintenance"];

    $stmt = $pdo->prepare("
        DELETE FROM scheduled_maintenance
        WHERE id = ?
    ");

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

    header("Location: Status.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH STATUS
|--------------------------------------------------------------------------
*/

$statusStmt = $pdo->query("
    SELECT *
    FROM site_status
    WHERE id = 1
");

$status = $statusStmt->fetch(PDO::FETCH_ASSOC);

if (!$status) {

    $status = [
        "api_status" => "Fully Operational",
        "database_status" => "Fully Operational",
        "website_status" => "Fully Operational"
    ];
}

/*
|--------------------------------------------------------------------------
| FETCH MAINTENANCE
|--------------------------------------------------------------------------
*/

$maintenanceStmt = $pdo->query("
    SELECT *
    FROM scheduled_maintenance
    ORDER BY starts_at ASC
");

$maintenanceList = $maintenanceStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| STATUS CLASS
|--------------------------------------------------------------------------
*/

function getStatusClass($status)
{
    switch ($status) {

        case "Fully Operational":
            return "status-green";

        case "Partially Operational":
            return "status-yellow";

        case "Full Outage":
            return "status-red";

        default:
            return "status-green";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Status - Rewire</title>

<style>
body{
    background:#030303;
    color:white;
    font-family:Arial,sans-serif;
    padding:60px 25px;
}

.status-wrap{
    width:100%;
    max-width:1200px;
    margin:auto;
}

/* HEADER */

.hero-header{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    margin-bottom:45px;
    gap:20px;
}

.tiny-label{
    color:#00c2ff;
    font-size:0.72rem;
    font-weight:900;
    letter-spacing:2px;
    margin-bottom:12px;
}

.page-title{
    font-size:3rem;
    font-weight:900;
}

.last-updated{
    color:#7f8a96;
    font-size:0.92rem;
}

/* STATUS GRID */

.status-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:22px;
    margin-bottom:55px;
}

.status-card{
    background:#071014;
    border:1px solid rgba(0,194,255,0.12);
    border-radius:20px;
    padding:24px;
    transition:0.25s ease;
}

.status-card:hover{
    transform:translateY(-3px);
    border-color:rgba(0,194,255,0.28);
    box-shadow:0 10px 30px rgba(0,194,255,0.08);
}

.status-card-top{
    display:flex;
    align-items:center;
    justify-content:space-between;
    margin-bottom:20px;
    gap:15px;
}

.status-service{
    font-size:1.05rem;
    font-weight:800;
}

.status-badge{
    font-size:0.82rem;
    font-weight:900;
}

.status-bar{
    width:100%;
    height:14px;
    border-radius:999px;
    overflow:hidden;
    background:#111;
}

.status-fill{
    height:100%;
    border-radius:999px;
}

/* STATUS COLORS */

.status-green .status-badge{
    color:#00ff9d;
}

.status-green .status-fill{
    width:100%;
    background:linear-gradient(90deg,#00ff9d,#00d084);
}

.status-yellow .status-badge{
    color:#ffcc00;
}

.status-yellow .status-fill{
    width:65%;
    background:linear-gradient(90deg,#ffcc00,#ff9900);
}

.status-red .status-badge{
    color:#ff5c5c;
}

.status-red .status-fill{
    width:25%;
    background:linear-gradient(90deg,#ff5c5c,#cc0000);
}

/* MAINTENANCE */

.maintenance-section{
    margin-top:20px;
}

.maintenance-header{
    margin-bottom:25px;
}

.maintenance-header h2{
    font-size:2rem;
    font-weight:900;
}

.maintenance-wrapper{
    display:flex;
    flex-direction:column;
    gap:20px;
}

/* MAINTENANCE CARD */

.maintenance-card{
    background:#071014;
    border:1px solid rgba(0,194,255,0.12);
    border-radius:20px;
    padding:24px;
}

.maintenance-card-top{
    display:flex;
    justify-content:space-between;
    gap:20px;
    margin-bottom:18px;
}

.maintenance-title{
    font-size:1.15rem;
    font-weight:900;
    margin-bottom:8px;
}

.maintenance-date{
    color:#7f8a96;
    font-size:0.9rem;
}

.maintenance-note{
    color:#c8d0d8;
    line-height:1.7;
}

.maintenance-status{
    font-size:0.8rem;
    font-weight:900;
    white-space:nowrap;
}

/* EMPTY */

.empty-state{
    background:#071014;
    border:1px dashed rgba(255,255,255,0.08);
    border-radius:20px;
    padding:60px 30px;
    text-align:center;
}

.empty-icon{
    font-size:2rem;
    margin-bottom:14px;
}

.empty-title{
    font-size:1.2rem;
    font-weight:900;
    margin-bottom:10px;
}

.empty-text{
    color:#7f8a96;
}

/* MOBILE */

@media(max-width:900px){

    .hero-header{
        flex-direction:column;
        align-items:flex-start;
    }

    .status-grid{
        grid-template-columns:1fr;
    }

    .maintenance-card-top{
        flex-direction:column;
    }

    .page-title{
        font-size:2.2rem;
    }
}
</style>
</head>

<body>
<?php include "Preloader.php"; ?>
<div class="status-wrap">

    <div class="hero-header">
        <div>
            <h1 class="page-title">
                Rewire System Status
            </h1>
        </div>

        <div class="last-updated">
            Last Updated:
            <?php echo date("M j, Y g:i A"); ?>
        </div>
    </div>

    <!-- STATUS GRID -->

    <div class="status-grid">

        <!-- API -->

        <div class="status-card <?php echo getStatusClass($status["api_status"]); ?>">

            <div class="status-card-top">

                <div class="status-service">
                    API
                </div>

                <div class="status-badge">
                    <?php echo htmlspecialchars($status["api_status"]); ?>
                </div>

            </div>

            <div class="status-bar">
                <div class="status-fill"></div>
            </div>

        </div>

        <!-- DATABASE -->

        <div class="status-card <?php echo getStatusClass($status["database_status"]); ?>">

            <div class="status-card-top">

                <div class="status-service">
                    Website Database
                </div>

                <div class="status-badge">
                    <?php echo htmlspecialchars($status["database_status"]); ?>
                </div>

            </div>

            <div class="status-bar">
                <div class="status-fill"></div>
            </div>

        </div>

        <!-- WEBSITE -->

        <div class="status-card <?php echo getStatusClass($status["website_status"]); ?>">

            <div class="status-card-top">

                <div class="status-service">
                    Website
                </div>

                <div class="status-badge">
                    <?php echo htmlspecialchars($status["website_status"]); ?>
                </div>

            </div>

            <div class="status-bar">
                <div class="status-fill"></div>
            </div>

        </div>

    </div>

    <!-- MAINTENANCE SECTION -->

    <div class="maintenance-section">

        <div class="maintenance-header">

            <div>
                <h2>
                    Scheduled Maintenance
                </h2>
            </div>

        </div>

        <div class="maintenance-wrapper">

            <?php if (empty($maintenanceList)): ?>

                <div class="empty-state">

                    <div class="empty-icon">
                        ⚡
                    </div>

                    <div class="empty-title">
                        No Scheduled Maintenance
                    </div>

                    <div class="empty-text">
                        All System Operational
                    </div>

                </div>

            <?php else: ?>

                <?php foreach ($maintenanceList as $maintenance): ?>

                    <div class="maintenance-card">

                        <div class="maintenance-card-top">

                            <div>
                                <div class="maintenance-title">
                                    <?php echo htmlspecialchars($maintenance["title"]); ?>
                                </div>

                                <div class="maintenance-date">
                                    <?php
                                    echo !empty($maintenance["starts_at"])
                                        ? date("F j, Y • g:i A", strtotime($maintenance["starts_at"]))
                                        : "Unknown Start Time";
                                    ?>
                                </div>
                            </div>

                            <div class="maintenance-status <?php echo getStatusClass($maintenance["maintenance_status"]); ?>">
                                <?php echo htmlspecialchars($maintenance["maintenance_status"]); ?>
                            </div>

                        </div>

                        <div class="maintenance-note">
                            <?php echo nl2br(htmlspecialchars($maintenance["maintenance_note"])); ?>
                        </div>

                    </div>

                <?php endforeach; ?>

            <?php endif; ?>

        </div>

    </div>

</div>
<script src="Security.js"></script>
</body>
</html>