<?php
session_start();
include "config.php";

if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href="index.php";</script>';
    exit();
}

/* ================= INSERT PORTAL ================= */
if (isset($_POST['save_portal'])) {

    $category = mysqli_real_escape_string($con, $_POST['category']);
    $sub_category = mysqli_real_escape_string($con, $_POST['sub_category']);
    $title = mysqli_real_escape_string($con, $_POST['title']);
    $url = mysqli_real_escape_string($con, $_POST['url']);

    // DUPLICATE CHECK
    $check = mysqli_query(
        $con,
        "SELECT id FROM cyber_portal 
         WHERE category='$category' 
         AND sub_category='$sub_category'
         AND title='$title' 
         AND url='$url'"
    );

    if (mysqli_num_rows($check) == 0) {

        mysqli_query(
            $con,
            "INSERT INTO cyber_portal (category, sub_category, title, url)
             VALUES ('$category','$sub_category','$title','$url')"
        );

        echo "<script>alert('Portal added successfully');</script>";

    } else {
        echo "<script>alert('This portal already exists');</script>";
    }

    echo "<script>window.location='portal.php';</script>";
}

function getIconByTitle($title)
{
    $title = strtolower($title);
    if (strpos($title, 'whatsapp') !== false)
        return 'bi-whatsapp';
    if (strpos($title, 'facebook') !== false)
        return 'bi-facebook';
    if (strpos($title, 'instagram') !== false)
        return 'bi-instagram';
    if (strpos($title, 'google') !== false)
        return 'bi-google';
    if (strpos($title, 'mail') !== false)
        return 'bi-envelope';
    if (strpos($title, 'cctv') !== false)
        return 'bi-camera-video';
    if (strpos($title, 'court') !== false)
        return 'bi-bank';
    if (strpos($title, 'ip') !== false)
        return 'bi-pc-display';
    if (strpos($title, 'training') !== false)
        return 'bi-mortarboard';
    if (strpos($title, 'map') !== false)
        return 'bi-geo-alt';
    return 'bi-globe';
}

/* ================= COLOR CLASSES ================= */
$colors = ['primary', 'info', 'warning', 'danger'];

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="images/favicon.ico" sizes="32x32" type="image/x-icon">
    <title>Portal</title>
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>

<body class="app sidebar-mini">

    <?php include "header.php"; ?>

    <div class="app-sidebar__overlay" data-toggle="sidebar"></div>
    <aside class="app-sidebar">
        <?php include "./common/name.php"; ?>
        <?php include "sidebar.php"; ?>
    </aside>

    <main class="app-content">

        <div class="app-title">
            <h1><i class="bi bi-speedometer"></i> Portal</h1>
        </div>

        <!-- SEARCH + ADD BUTTON -->
        <div class="d-flex justify-content-between align-items-center mt-4 mb-3">
            <input type="text" id="searchPortal" class="form-control" style="max-width:300px;"
                placeholder="Search portal...">

            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPortalModal">
                <i class="bi bi-plus-circle"></i> ADD Portal
            </button>
        </div>

        <!-- CATEGORY WISE DATA -->
        <?php
        $catQuery = mysqli_query($con, "SELECT DISTINCT category FROM cyber_portal ORDER BY category");
        $colorIndex = 0;

        while ($cat = mysqli_fetch_assoc($catQuery)) {
            $category = $cat['category'];
            ?>
        <h4 class="mt-4 fw-bold"><?= htmlspecialchars($category) ?></h4>
        <div class="row">
            <?php
                $dataQuery = mysqli_query($con, "SELECT * FROM cyber_portal WHERE category='$category' ORDER BY title");
                while ($row = mysqli_fetch_assoc($dataQuery)) {
                    $searchText = strtolower($row['category'] . ' ' . $row['sub_category'] . ' ' . $row['title']);
                    $colorClass = $colors[$colorIndex % count($colors)];
                    $iconClass = getIconByTitle($row['title']);
                    $colorIndex++;
                    ?>
            <div class="col-md-6 col-lg-3 portal-card" data-search="<?= $searchText ?>">
                <div class="widget-small <?= $colorClass ?> coloured-icon"
                    onclick="window.open('<?= htmlspecialchars($row['url']) ?>','_blank')">
                    <div class="icon"><i class="bi <?= $iconClass ?> fs-1"></i></div>
                    <div class="info">
                        <h4><?= htmlspecialchars($row['title']) ?></h4>
                        <h5><?= htmlspecialchars($row['sub_category']) ?></h5>
                    </div>
                </div>
            </div>
            <?php } ?>
        </div>
        <?php } ?>
    </main>

    <!-- ADD PORTAL MODAL -->
    <div class="modal fade" id="addPortalModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">

                <form method="POST" id="portalForm">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Portal</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label>Category</label>
                                <input type="text" name="category" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label>Sub Category</label>
                                <input type="text" name="sub_category" class="form-control" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label>Title</label>
                            <input type="text" name="title" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>URL</label>
                            <input type="url" name="url" id="portalUrl" class="form-control" required>
                            <small class="text-muted">
                                Must start with http:// or https://
                            </small>
                        </div>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="save_portal" class="btn btn-primary">Save</button>
                    </div>
                </form>

            </div>
        </div>
    </div>

    <script src="js/jquery-3.7.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>

    <script>
    // URL VALIDATION
    document.getElementById('portalForm').addEventListener('submit', function(e) {
        let url = document.getElementById('portalUrl').value.trim();
        if (!url.match(/^https?:\/\//i)) {
            alert('Invalid URL');
            e.preventDefault();
        }
    });

    // LIVE SEARCH
    document.getElementById('searchPortal').addEventListener('keyup', function() {
        let value = this.value.toLowerCase();
        document.querySelectorAll('.portal-card').forEach(function(card) {
            let text = card.getAttribute('data-search');
            card.style.display = text.includes(value) ? '' : 'none';
        });
    });
    </script>

</body>

</html>