<?php
session_start();

$db = new PDO('sqlite:database.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$notification = "";

// Function to format the table name (PRO + EachWordCapitalized)
function formatTableName($name)
{
    $name = trim($name);
    $words = preg_split('/\s+/', $name);
    $formatted = 'PRO';
    foreach ($words as $word) {
        $formatted .= ucfirst(strtolower($word));
    }
    return $formatted;
}

// Function to format display name (remove PRO, add spaces between words)
function formatDisplayName($name)
{
    $name = preg_replace('/^PRO/', '', $name);
    $name = preg_replace('/(?<!^)([A-Z])/', ' $1', $name);
    return trim($name);
}

// Handle table creation
if (isset($_POST['create_table'])) {
    $inputName = $_POST['table_name'] ?? '';
    $formattedTableName = formatTableName($inputName);

    // Create the table if not exists
    $db->exec("
        CREATE TABLE IF NOT EXISTS '$formattedTableName' (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            activity TEXT,
            score_0 REAL DEFAULT 0,
            score_0_25 REAL DEFAULT 0,
            score_0_5 REAL DEFAULT 0,
            score_1 REAL DEFAULT 0,
            alot_mark REAL DEFAULT 0
        )
    ");

    $_SESSION['created_table'] = $formattedTableName;
    $notification = "Table '" . formatDisplayName($formattedTableName) . "' created successfully!";
}

// Handle adding activities
if (isset($_POST['add_activity']) && isset($_SESSION['created_table'])) {
    $table = $_SESSION['created_table'];
    $activity = $_POST['activity'];
    $score = $_POST['alot_mark'];

    // Determine which score column to mark
    $columns = ['score_0', 'score_0_25', 'score_0_5', 'score_1'];
    $values = ['0', '0.25', '0.5', '1'];

    $insertCols = ['activity', 'alot_mark'];
    $insertVals = [$activity, $score];

    // Mark the selected score column with the corresponding value
    foreach ($columns as $i => $col) {
        $insertCols[] = $col;
        $insertVals[] = ($score == $values[$i]) ? $score : 0;
    }

    $placeholders = implode(',', array_fill(0, count($insertVals), '?'));
    $colNames = implode(',', $insertCols);

    $stmt = $db->prepare("INSERT INTO '$table' ($colNames) VALUES ($placeholders)");
    $stmt->execute($insertVals);

    $notification = "Activity '$activity' added with score $score!";
}

// Reset session to create a new table
if (isset($_POST['reset'])) {
    unset($_SESSION['created_table']);
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$currentTable = $_SESSION['created_table'] ?? null;
$records = [];

if ($currentTable) {
    $records = $db->query("SELECT * FROM '$currentTable' ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
}

// Get current page name for active navigation
$current_page = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CAOSCE · Network</title>
    <link rel="icon" type="image/x-icon" href="CAOSCE Network.ico">
    <!-- Font Awesome 6 (Free) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* ----- RESET & BASE ----- */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f0f4fb;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            color: #10233f;
        }

        /* ----- NAVIGATION (SOLID, NON-TRANSPARENT) ----- */
        .navbar {
            position: sticky;
            top: 0;
            z-index: 60;
            background: #ffffff;
            border-bottom: 2px solid #e2eaf2;
            padding: 0 5vw;
            height: 74px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 12px rgba(16, 35, 63, 0.06);
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 800;
            font-size: 20px;
            color: #10233f;
            text-decoration: none;
        }

        .brand-icon {
            width: 38px;
            height: 38px;
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            border-radius: 12px;
            display: grid;
            place-items: center;
            color: white;
            font-size: 18px;
            font-weight: 900;
            box-shadow: 0 8px 18px rgba(26, 108, 240, 0.25);
        }

        .brand-light {
            font-weight: 500;
            color: #4f6580;
        }

        .nav-links {
            display: flex;
            align-items: center;
            gap: 28px;
        }

        .nav-links a {
            font-size: 14px;
            font-weight: 600;
            color: #4f6580;
            text-decoration: none;
            transition: 0.2s;
            position: relative;
            padding: 6px 0;
        }

        .nav-links a i {
            margin-right: 6px;
            font-size: 13px;
        }

        .nav-links a:hover {
            color: #1a6cf0;
        }

        .nav-links a.active {
            color: #1a6cf0;
        }

        .nav-links a.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 3px;
            background: #1a6cf0;
            border-radius: 4px;
        }

        .nav-logout {
            background: #f0f4fb;
            border: 1px solid #d9e2eb;
            border-radius: 30px;
            padding: 6px 18px;
            font-weight: 600;
            font-size: 13px;
            color: #10233f;
            transition: 0.2s;
        }

        .nav-logout:hover {
            background: #e2eaf2;
            border-color: #b0c4d8;
            color: #1a6cf0;
        }

        /* ----- MAIN CONTAINER ----- */
        main {
            flex: 1;
            padding: 30px 5vw;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        /* ----- PAGE HEADER ----- */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px 28px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
            border: 1px solid #eef4fa;
            flex-wrap: wrap;
            gap: 15px;
        }

        .page-header h1 {
            color: #10233f;
            font-weight: 700;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header h1 i {
            color: #1a6cf0;
        }

        .page-header .subtitle {
            font-size: 14px;
            color: #6b7a8f;
            margin-top: 2px;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 22px;
            border: none;
            border-radius: 30px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            font-size: 14px;
        }

        .btn-back {
            background: #e9ecef;
            color: #4f6580;
        }

        .btn-back:hover {
            background: #dde1e6;
            transform: translateY(-2px);
        }

        .btn-primary {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
            box-shadow: 0 4px 14px rgba(26, 108, 240, 0.25);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(26, 108, 240, 0.35);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(40, 167, 69, 0.3);
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(220, 53, 69, 0.25);
        }

        /* ----- CARD ----- */
        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
            padding: 28px 30px;
            margin-bottom: 25px;
            border: 1px solid #eef4fa;
            transition: 0.3s;
        }

        .card:hover {
            box-shadow: 0 8px 28px rgba(0, 0, 0, 0.08);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f4fb;
            flex-wrap: wrap;
            gap: 10px;
        }

        .card-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #10233f;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-title i {
            color: #1a6cf0;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 5px 14px;
            background: #1a6cf0;
            color: white;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .badge-success {
            background: #28a745;
        }

        /* ----- FORM ----- */
        .form-group {
            margin-bottom: 18px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 6px;
            color: #10233f;
            font-size: 14px;
        }

        .form-group label i {
            margin-right: 6px;
            color: #1a6cf0;
        }

        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 15px;
            transition: 0.3s;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: #1a6cf0;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
        }

        .form-control::placeholder {
            color: #a0b0c4;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 18px;
        }

        @media (max-width: 600px) {
            .form-row {
                grid-template-columns: 1fr;
            }
        }

        /* ----- TABLE ----- */
        .table-wrapper {
            overflow-x: auto;
            border-radius: 12px;
            border: 1px solid #eef4fa;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        th {
            background: #f8fafc;
            color: #10233f;
            font-weight: 700;
            padding: 12px 16px;
            text-align: left;
            border-bottom: 2px solid #e2eaf2;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        td {
            padding: 11px 16px;
            border-bottom: 1px solid #eef4fa;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover td {
            background: #f8fafc;
        }

        .text-center {
            text-align: center;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6b7a8f;
        }

        .empty-state i {
            font-size: 40px;
            color: #d9e2eb;
            display: block;
            margin-bottom: 10px;
        }

        /* ----- NOTIFICATION ----- */
        .notification {
            padding: 14px 20px;
            border-radius: 12px;
            font-weight: 500;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: slideDown 0.4s ease;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .notification-success {
            background: #d4edda;
            color: #155724;
            border-left: 5px solid #28a745;
        }

        .notification-info {
            background: #cce5ff;
            color: #004085;
            border-left: 5px solid #007bff;
        }

        .notification i {
            font-size: 20px;
        }

        /* ----- FOOTER ----- */
        .footer {
            margin-top: auto;
            padding: 24px 5vw 20px;
            background: #071a31;
            color: #b6c9dd;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            border-top: 1px solid #1f3550;
        }

        .footer strong {
            color: #dce7f5;
        }

        .footer .meta {
            display: flex;
            gap: 24px;
            align-items: center;
        }

        .footer .meta span {
            color: #7c92ab;
        }

        /* ----- RESPONSIVE ----- */
        @media (max-width: 900px) {
            .navbar {
                padding: 0 4vw;
                height: 68px;
            }

            .nav-links a:not(.nav-logout) {
                display: none;
            }

            .nav-links a.nav-logout {
                display: inline-block;
            }

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

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
                justify-content: center;
            }
        }

        @media (max-width: 600px) {
            main {
                padding: 16px 4vw;
            }

            .card {
                padding: 18px 16px;
            }

            .page-header {
                padding: 16px 18px;
            }

            .page-header h1 {
                font-size: 1.4rem;
            }

            th,
            td {
                padding: 8px 10px;
                font-size: 13px;
            }

            .footer {
                flex-direction: column;
                gap: 10px;
                align-items: flex-start;
            }
        }

        @media (max-width: 400px) {
            .brand {
                font-size: 16px;
            }

            .brand-icon {
                width: 30px;
                height: 30px;
                font-size: 14px;
            }
        }
    </style>
</head>

<body>

    <!-- ============================================================
         NAVIGATION (SOLID, NON-TRANSPARENT)
         ============================================================ -->
    <header class="navbar">
        <a href="admin.php" class="brand">
            <span class="brand-icon">CN</span>
            <span>CAOSCE <span class="brand-light">Network</span></span>
        </a>
        <div class="nav-links">
            <a href="admin.php" class="<?php echo $current_page == 'admin.php' ? 'active' : ''; ?>">
                <i class="fas fa-th-large"></i> Dashboard
            </a>
            <a href="classes.php" class="<?php echo $current_page == 'classes.php' ? 'active' : ''; ?>">
                <i class="fas fa-user-plus"></i> Class lists
            </a>
            <a href="result.php" class="<?php echo $current_page == 'result.php' ? 'active' : ''; ?>">
                <i class="fas fa-chart-pie"></i>OSCE Result
            </a>
            <a href="exam_manager.php" class="<?php echo $current_page == 'exam_manager.php' ? 'active' : ''; ?>">
                <i class="fas fa-sliders-h"></i> Exams settings
            </a>
            <a href="logout.php" class="nav-logout">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
    </header>

    <!-- ============================================================
         MAIN CONTENT
         ============================================================ -->
    <main>
        <div class="container">

            <!-- Page Header -->
            <div class="page-header">
                <div>
                    <h1>
                        <i class="fas fa-plus-circle"></i>
                        Create Procedure Checklist
                    </h1>
                    <div class="subtitle">
                        <i class="fas fa-clipboard-list"></i>
                        Build a new OSCE procedure checklist
                    </div>
                </div>
                <div class="header-actions">
                    <a href="exam_manager.php" class="btn btn-back">
                        <i class="fas fa-arrow-left"></i> Go Back
                    </a>
                </div>
            </div>

            <!-- Notification -->
            <?php if ($notification): ?>
                <div class="notification notification-success" id="notify">
                    <i class="fas <?= strpos($notification, '✅') !== false ? 'fa-check-circle' : 'fa-plus-circle' ?>"></i>
                    <span><?= htmlspecialchars($notification) ?></span>
                </div>
                <script>
                    setTimeout(() => {
                        const n = document.getElementById('notify');
                        if (n) n.style.display = 'none';
                    }, 4000);
                </script>
            <?php endif; ?>

            <!-- Main Content -->
            <?php if (!$currentTable): ?>

                <!-- Step 1: Create Table -->
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="fas fa-table"></i>
                            Step 1: Name Your Checklist
                        </h2>
                        <span class="badge">New</span>
                    </div>
                    <form method="POST">
                        <div class="form-group">
                            <label for="table_name"><i class="fas fa-pen"></i> Procedure Name</label>
                            <input type="text" name="table_name" id="table_name" class="form-control"
                                placeholder="e.g., Vital Signs Assessment" required>
                            <small style="color:#6b7a8f; font-size:13px; display:block; margin-top:6px;">
                        </div>
                        <button type="submit" name="create_table" class="btn btn-primary" style="width:100%; justify-content:center; padding:14px;">
                            <i class="fas fa-check-circle"></i> Create Checklist
                        </button>
                    </form>
                </div>

            <?php else: ?>

                <!-- Step 2: Add Activities -->
                <?php
                $displayTableName = formatDisplayName($currentTable);
                ?>
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="fas fa-edit"></i>
                            <?= htmlspecialchars($displayTableName) ?>
                        </h2>
                        <span class="badge badge-success">
                            <i class="fas fa-list"></i> <?= count($records) ?> Items
                        </span>
                    </div>

                    <form method="POST">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="activity"><i class="fas fa-tasks"></i> Activity Name</label>
                                <input type="text" name="activity" id="activity" class="form-control"
                                    placeholder="Enter activity name" required>
                            </div>
                            <div class="form-group">
                                <label for="alot_mark"><i class="fas fa-star"></i> Score Value</label>
                                <select name="alot_mark" id="alot_mark" class="form-control" required>
                                    <option value="">Select score</option>
                                    <option value="0">0</option>
                                    <option value="0.25">0.25</option>
                                    <option value="0.5">0.5</option>
                                    <option value="1">1</option>
                                </select>
                            </div>
                        </div>
                        <button type="submit" name="add_activity" class="btn btn-success" style="width:100%; justify-content:center; padding:14px;">
                            <i class="fas fa-plus-circle"></i> Add Activity
                        </button>
                    </form>
                </div>

                <!-- Activities Table -->
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="fas fa-list-ul"></i>
                            Activities
                        </h2>
                    </div>

                    <div class="table-wrapper">
                        <table>
                            <thead>
                                <tr>
                                    <th style="width:60px;">#</th>
                                    <th>Activity</th>
                                    <th class="text-center" style="width:70px;">0</th>
                                    <th class="text-center" style="width:70px;">0.25</th>
                                    <th class="text-center" style="width:70px;">0.5</th>
                                    <th class="text-center" style="width:70px;">1</th>
                                    <th class="text-center" style="width:90px;">Allotted</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($records) > 0): ?>
                                    <?php foreach ($records as $r): ?>
                                        <tr>
                                            <td><?= $r['id'] ?></td>
                                            <td><strong><?= htmlspecialchars($r['activity']) ?></strong></td>
                                            <td class="text-center"><?= $r['score_0'] ?></td>
                                            <td class="text-center"><?= $r['score_0_25'] ?></td>
                                            <td class="text-center"><?= $r['score_0_5'] ?></td>
                                            <td class="text-center"><?= $r['score_1'] ?></td>
                                            <td class="text-center" style="font-weight:700; color:#1a6cf0;">
                                                <?= $r['alot_mark'] ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7">
                                            <div class="empty-state">
                                                <i class="fas fa-inbox"></i>
                                                <p>No activities added yet. Add your first activity above.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <form method="POST" style="margin-top:20px;">
                        <button type="submit" name="reset" class="btn btn-danger" style="width:100%; justify-content:center; padding:14px;">
                            <i class="fas fa-check-circle"></i> Finish & Save Checklist
                        </button>
                    </form>
                </div>

            <?php endif; ?>

        </div>
    </main>

    <!-- ============================================================
         FOOTER
         ============================================================ -->
    <footer class="footer">
        <div>
            <strong><i class="fas fa-network-wired" style="margin-right:8px;"></i> CAOSCE Network</strong>
            <span style="margin-left:18px;">© <?php echo date('Y'); ?> All rights reserved</span>
        </div>
        <div class="meta">
            <span><i class="fas fa-code"></i> v2.0</span>
            <span>|</span>
            <span><i class="fas fa-user-cog"></i> Admin Panel</span>
            <span>|</span>
        </div>
    </footer>

    <!-- ============================================================
         SCRIPTS
         ============================================================ -->
    <script>
        // Table row animation
        document.addEventListener('DOMContentLoaded', function() {
            const rows = document.querySelectorAll('tbody tr');
            rows.forEach((row, index) => {
                row.style.opacity = '0';
                row.style.transform = 'translateY(6px)';
                setTimeout(() => {
                    row.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                    row.style.opacity = '1';
                    row.style.transform = 'translateY(0)';
                }, index * 40);
            });
        });
    </script>

</body>

</html>