<?php
session_start();
if(!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit();
}
require_once '../includes/db.php';

$page = isset($_GET['page']) ? $_GET['page'] : 'dashboard';

// Helper to handle uploads safely on any server environment
function handleUpload($file, $dest_folder) {
    if($file['error'] == 0) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $new_name = time() . '_' . rand(1000,9999) . '.' . $ext;
        
        $target_dir = __DIR__ . '/../uploads/' . $dest_folder;
        $dest = $target_dir . '/' . $new_name;
        
        if(!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        if(move_uploaded_file($file['tmp_name'], $dest)) {
            return $new_name;
        } else {
            $_SESSION['upload_error'] = "Failed to copy file to directory (Permissions issue).";
        }
    } else {
        $_SESSION['upload_error'] = "File rejected: Too large (max 2MB by default) or corrupt. Error code: " . $file['error'];
    }
    return false;
}

// Handle Form Submissions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if($action == 'add_slider') {
        $img = handleUpload($_FILES['image'], 'sliders');
        if($img) {
            $conn->query("INSERT INTO sliders (image) VALUES ('$img')");
        }
        header("Location: index.php?page=sliders"); exit;
    }
    if($action == 'delete_slider') {
        $id = (int)$_POST['id'];
        $conn->query("DELETE FROM sliders WHERE id=$id");
        header("Location: index.php?page=sliders"); exit;
    }

    if($action == 'update_popup') {
        $img = handleUpload($_FILES['image'], 'popups');
        if($img) {
            // activate this one, deactivate others
            $conn->query("UPDATE popup SET status=0");
            $conn->query("INSERT INTO popup (image, status) VALUES ('$img', 1)");
        }
        header("Location: index.php?page=popup"); exit;
    }

        if($action == 'add_member') {
        $name = $conn->real_escape_string($_POST['name']);
        $designation = $conn->real_escape_string($_POST['designation']);
        $cell = $conn->real_escape_string($_POST['cell']);
        $sort_order = (int)$_POST['sort_order'];
        
        $img = handleUpload($_FILES['image'], 'members');
        if(!$img) $img = ''; // fallback string
        
        $conn->query("INSERT INTO board_members (name, designation, cell, image, sort_order) VALUES ('$name', '$designation', '$cell', '$img', $sort_order)");
        header("Location: index.php?page=members"); exit;
    }
    if($action == 'delete_member') {
        $id = (int)$_POST['id'];
        $conn->query("DELETE FROM board_members WHERE id=$id");
        header("Location: index.php?page=members"); exit;
    }

    if($action == 'update_user_status') {
        $id = (int)$_POST['id'];
        $status = $conn->real_escape_string($_POST['status']);
        $conn->query("UPDATE users SET status='$status' WHERE id=$id");
        header("Location: index.php?page=users"); exit;
    }

    if($action == 'add_notice') {
        $title = $conn->real_escape_string($_POST['title']);
        $category = $conn->real_escape_string($_POST['category']);
        $content = $conn->real_escape_string($_POST['content']);
        
        $img = handleUpload($_FILES['image'], 'notices');
        $pdf = handleUpload($_FILES['pdf_file'], 'notices');
        
        if(!$img) $img = '';
        if(!$pdf) $pdf = '';

        $conn->query("INSERT INTO notices (title, category, image, content, pdf_file) VALUES ('$title', '$category', '$img', '$content', '$pdf')");
        header("Location: index.php?page=notices"); exit;
    }
    if($action == 'delete_notice') {
        $id = (int)$_POST['id'];
        $conn->query("DELETE FROM notices WHERE id=$id");
        header("Location: index.php?page=notices"); exit;
    }

    if($action == 'add_video') {
        $title = $conn->real_escape_string($_POST['title']);
        $code = $conn->real_escape_string($_POST['youtube_code']); // e.g. from https://www.youtube.com/watch?v=XXXX, just XXXX
        $conn->query("INSERT INTO videos (title, youtube_code) VALUES ('$title', '$code')");
        header("Location: index.php?page=videos"); exit;
    }
    if($action == 'delete_video') {
        $id = (int)$_POST['id'];
        $conn->query("DELETE FROM videos WHERE id=$id");
        header("Location: index.php?page=videos"); exit;
    }

    if($action == 'add_service') {
        $title = $conn->real_escape_string($_POST['title']);
        $title_hi = $conn->real_escape_string($_POST['title_hi']);
        $description = $conn->real_escape_string($_POST['description']);
        $description_hi = $conn->real_escape_string($_POST['description_hi']);
        $icon = $conn->real_escape_string($_POST['icon']);
        $section = $conn->real_escape_string($_POST['section']);
        
        $conn->query("INSERT INTO services (title, title_hi, description, description_hi, icon, section) VALUES ('$title', '$title_hi', '$description', '$description_hi', '$icon', '$section')");
        header("Location: index.php?page=services"); exit;
    }
    if($action == 'delete_service') {
        $id = (int)$_POST['id'];
        $conn->query("DELETE FROM services WHERE id=$id");
        header("Location: index.php?page=services"); exit;
    }

    if($action == 'add_gallery') {
        $service_id = (int)$_POST['service_id'];
        $title = $conn->real_escape_string($_POST['title']);
        $subtitle = $conn->real_escape_string($_POST['subtitle']);
        
        $img = handleUpload($_FILES['image'], 'gallery');
        if($img) {
            $conn->query("INSERT INTO service_gallery (service_id, image, title, subtitle) VALUES ($service_id, '$img', '$title', '$subtitle')");
        }
        header("Location: index.php?page=gallery"); exit;
    }
    if($action == 'delete_gallery') {
        $id = (int)$_POST['id'];
        $conn->query("DELETE FROM service_gallery WHERE id=$id");
        header("Location: index.php?page=gallery"); exit;
    }

    if($action == 'upload_constitution') {
        if(isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] == 0) {
            $ext = strtolower(pathinfo($_FILES['pdf_file']['name'], PATHINFO_EXTENSION));
            if($ext == 'pdf') {
                move_uploaded_file($_FILES['pdf_file']['tmp_name'], '../uploads/constitution.pdf');
            } else {
                $_SESSION['upload_error'] = "Only PDF files are allowed for the Constitution.";
            }
        }
        header("Location: index.php?page=constitution"); exit;
    }

    if($action == 'update_dynamic_page') {
        $id = (int)$_POST['id'];
        $content = $conn->real_escape_string($_POST['content']);
        $pdf_file = $_POST['existing_pdf'];

        if(isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] == 0) {
            $ext = strtolower(pathinfo($_FILES['pdf_file']['name'], PATHINFO_EXTENSION));
            if($ext == 'pdf') {
                $pdf_file = time() . '_' . $_FILES['pdf_file']['name'];
                move_uploaded_file($_FILES['pdf_file']['tmp_name'], '../uploads/' . $pdf_file);
            }
        }
        $conn->query("UPDATE dynamic_pages SET content='$content', pdf_file='$pdf_file' WHERE id=$id");
        header("Location: index.php?page=dynamic_pages&edit=$id&success=1"); exit;
    }
}

// Fetch dashboard stats
$stats = [
    'members' => $conn->query("SELECT COUNT(*) as c FROM board_members")->fetch_assoc()['c'],
    'notices' => $conn->query("SELECT COUNT(*) as c FROM notices")->fetch_assoc()['c'],
    'sliders' => $conn->query("SELECT COUNT(*) as c FROM sliders")->fetch_assoc()['c'],
    'users' => $conn->query("SELECT COUNT(*) as c FROM users")->fetch_assoc()['c']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Bhartiya Seva</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .sidebar { min-height: 100vh; background-color: #1e293b; }
        .sidebar a { color: rgba(255,255,255,0.7); text-decoration: none; padding: 15px 20px; display: block; border-bottom: 1px solid rgba(255,255,255,0.05); }
        .sidebar a:hover, .sidebar a.active { background-color: #0f172a; color: white; border-left: 4px solid #f97316; }
        .top-navbar { background-color: white; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .dashboard-card { transition: transform 0.3s; border-radius: 10px; border: none; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
        .dashboard-card:hover { transform: translateY(-5px); }
        .icon-box { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 24px; color: white; }
        .ck-editor__editable { min-height: 250px; }
    </style>
    <!-- CKEditor 5 -->
    <script src="https://cdn.ckeditor.com/ckeditor5/38.0.1/classic/ckeditor.js"></script>
</head>
<body class="bg-light">

<div class="d-flex">
    <!-- Sidebar -->
    <div class="sidebar" style="width: 250px; flex-shrink: 0;">
        <div class="p-4 text-center border-bottom border-secondary">
            <img src="https://i.ibb.co/4gVbp8YZ/Whats-App-Image-2026-04-23-at-9-54-25-PM.png" alt="Logo" class="img-fluid bg-white p-2 rounded mb-2" style="max-height: 60px;">
            <h6 class="text-white mb-0 mt-2">Admin Panel</h6>
        </div>
        <div class="nav flex-column mt-3">
            <a href="index.php?page=dashboard" class="<?php echo  $page=='dashboard'?'active':'' ?>"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a>
            <a href="index.php?page=sliders" class="<?php echo  $page=='sliders'?'active':'' ?>"><i class="fas fa-images me-2"></i> Manage Sliders</a>
            <a href="index.php?page=popup" class="<?php echo  $page=='popup'?'active':'' ?>"><i class="fas fa-window-restore me-2"></i> Entry Popup</a>
            <a href="index.php?page=members" class="<?php echo  $page=='members'?'active':'' ?>"><i class="fas fa-users me-2"></i> Board Members</a>
            <a href="index.php?page=services" class="<?php echo  $page=='services'?'active':'' ?>"><i class="fas fa-hand-holding-heart me-2"></i> Manage Services</a>
            <a href="index.php?page=gallery" class="<?php echo  $page=='gallery'?'active':'' ?>"><i class="fas fa-photo-video me-2"></i> Services Gallery</a>
            <a href="index.php?page=sites" class="<?php echo  $page=='sites'?'active':'' ?>"><i class="fas fa-link me-2"></i> Important Sites</a>
            <a href="index.php?page=notices" class="<?php echo  $page=='notices'?'active':'' ?>"><i class="fas fa-bullhorn me-2"></i> Notices & News</a>
            <a href="index.php?page=videos" class="<?php echo  $page=='videos'?'active':'' ?>"><i class="fas fa-video me-2"></i> Video Gallery</a>
            <a href="index.php?page=users" class="<?php echo  $page=='users'?'active':'' ?>"><i class="fas fa-user-plus me-2"></i> Registered Users</a>
            <a href="index.php?page=constitution" class="<?php echo  $page=='constitution'?'active':'' ?>"><i class="fas fa-book me-2"></i> Constitution</a>
            <a href="index.php?page=dynamic_pages" class="<?php echo  $page=='dynamic_pages'?'active':'' ?>"><i class="fas fa-file-alt me-2"></i> Document Pages</a>
            <a href="logout.php" class="text-danger mt-5"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="flex-grow-1 overflow-auto" style="height: 100vh;">
        <!-- Topbar -->
        <div class="top-navbar p-3 d-flex justify-content-between align-items-center mb-4">
            <h4 class="mb-0 text-dark text-capitalize"><?php echo  h($page) ?> Overview</h4>
            <div class="d-flex align-items-center">
                <span class="me-3 fw-bold">Admin</span>
                <img src="https://ui-avatars.com/api/?name=Admin&background=15803d&color=fff" class="rounded-circle" width="40" alt="Admin">
            </div>
        </div>

        <div class="p-4 pt-0">
            <?php if(isset($_SESSION['upload_error'])): ?>
                <div class="alert alert-danger alert-dismissible fade show mb-4">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?php echo  h($_SESSION['upload_error']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['upload_error']); ?>
            <?php endif; ?>

            <?php if($page == 'dashboard'): ?>
            <!-- DASHBOARD WIDGETS -->
            <div class="row g-4 mb-4">
                <div class="col-md-3">
                    <div class="card dashboard-card">
                        <div class="card-body d-flex align-items-center">
                            <div class="icon-box bg-primary me-3"><i class="fas fa-users"></i></div>
                            <div>
                                <h6 class="text-muted mb-1">Total Members</h6>
                                <h3 class="mb-0 fw-bold"><?php echo  $stats['members'] ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Notices widget -->
                <div class="col-md-3">
                    <div class="card dashboard-card">
                        <div class="card-body d-flex align-items-center">
                            <div class="icon-box bg-success me-3"><i class="fas fa-bullhorn"></i></div>
                            <div>
                                <h6 class="text-muted mb-1">Notices</h6>
                                <h3 class="mb-0 fw-bold"><?php echo  $stats['notices'] ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card dashboard-card">
                        <div class="card-body d-flex align-items-center">
                            <div class="icon-box bg-warning me-3"><i class="fas fa-images"></i></div>
                            <div>
                                <h6 class="text-muted mb-1">Active Sliders</h6>
                                <h3 class="mb-0 fw-bold"><?php echo  $stats['sliders'] ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card dashboard-card">
                        <div class="card-body d-flex align-items-center">
                            <div class="icon-box bg-info me-3"><i class="fas fa-user-plus"></i></div>
                            <div>
                                <h6 class="text-muted mb-1">Registered Users</h6>
                                <h3 class="mb-0 fw-bold"><?php echo  $stats['users'] ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Access Menu -->
            <div class="row g-4">
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm rounded">
                        <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                            <h5 class="mb-0"><i class="fas fa-cog me-2 text-primary"></i> Quick Actions</h5>
                        </div>
                        <div class="card-body">
                            <div class="list-group list-group-flush">
                                <a href="index.php?page=popup" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    Update Entry Popup Image <i class="fas fa-chevron-right text-muted"></i>
                                </a>
                                <a href="index.php?page=notices" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    Add New Scrolling Notice <i class="fas fa-chevron-right text-muted"></i>
                                </a>
                                <a href="index.php?page=members" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    Add New Board Member <i class="fas fa-chevron-right text-muted"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm rounded h-100">
                        <div class="card-header bg-white border-bottom py-3">
                            <h5 class="mb-0"><i class="fas fa-info-circle me-2 text-success"></i> System Info</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>Database Status:</strong> <span class="badge bg-success">Connected</span></p>
                            <p><strong>PHP Version:</strong> <?php echo phpversion(); ?></p>
                            <p><strong>Last Login:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
                            <hr>
                            <p class="text-muted small">Welcome to the management portal. From the left sidebar, you can easily control the dynamic elements of the website. The database structures are fully generated to accommodate CRUD operations for all these sections.</p>
                        </div>
                    </div>
                </div>
            </div>

            <?php elseif($page == 'sliders'): ?>
            <!-- SLIDERS -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add New Slider</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="add_slider">
                        <div class="mb-3">
                            <label>Upload Image</label>
                            <input type="file" name="image" class="form-control" required accept="image/*">
                        </div>
                        <button type="submit" class="btn btn-primary">Add Slider</button>
                    </form>
                </div>
            </div>
            
            <div class="row">
                <?php 
                $res = $conn->query("SELECT * FROM sliders ORDER BY id DESC");
                while($row = $res->fetch_assoc()):
                ?>
                <div class="col-md-4 mb-3">
                    <div class="card">
                        <img src="../uploads/sliders/<?php echo  h($row['image']) ?>" class="card-img-top" style="height: 150px; object-fit: cover;">
                        <div class="card-body text-center">
                            <form action="index.php" method="POST">
                                <input type="hidden" name="action" value="delete_slider">
                                <input type="hidden" name="id" value="<?php echo  $row['id'] ?>">
                                <button class="btn btn-danger btn-sm">Delete</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>

            <?php elseif($page == 'popup'): ?>
            <!-- POPUP -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Update Front-Page Popup</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="update_popup">
                        <div class="mb-3">
                            <label>Upload New Popup Image (This will replace the active one)</label>
                            <input type="file" name="image" class="form-control" required accept="image/*">
                        </div>
                        <button type="submit" class="btn btn-primary">Update Popup</button>
                    </form>
                </div>
            </div>
            
            <?php 
            $res = $conn->query("SELECT * FROM popup WHERE status=1 LIMIT 1");
            if($row = $res->fetch_assoc()):
            ?>
            <div class="card mt-3">
                <div class="card-header bg-success text-white">Currently Active Popup</div>
                <div class="card-body text-center">
                    <img src="../uploads/popups/<?php echo  h($row['image']) ?>" style="max-height: 300px; max-width: 100%;">
                </div>
            </div>
            <?php endif; ?>

            <?php elseif($page == 'members'): ?>
            <!-- MEMBERS -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add New Board Member / Executive</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="add_member">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Name</label>
                                <input type="text" name="name" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Designation (e.g. President, Secretary, Adv)</label>
                                <input type="text" name="designation" class="form-control" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Cell Selection</label>
                                <select name="cell" class="form-control">
                                    <option value="STATE">Board Members</option>
                                    <option value="LEGAL">LEGAL CELL</option>
                                    <option value="MEDIA">MEDIA CELL</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Image (Square aspect ratio is best)</label>
                                <input type="file" name="image" class="form-control" accept="image/*">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Sort Order (Lowest shows first)</label>
                                <input type="number" name="sort_order" class="form-control" value="0">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Member</button>
                    </form>
                </div>
            </div>
            
            <div class="table-responsive bg-white shadow-sm p-3 rounded">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Image</th>
                            <th>Name</th>
                            <th>Designation</th>
                            <th>Cell</th>
                            <th>Order</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $res = $conn->query("SELECT * FROM board_members ORDER BY sort_order ASC, id DESC");
                        while($row = $res->fetch_assoc()):
                            $img_src = (strpos($row['image'], 'http') === 0) ? $row['image'] : '../uploads/members/'.$row['image'];
                        ?>
                        <tr>
                            <td><img src="<?php echo  $img_src ?>" width="50" height="50" style="object-fit:cover; border-radius:5px;" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo  urlencode($row['name']) ?>&background=random'"></td>
                            <td class="fw-bold"><?php echo  h($row['name']) ?></td>
                            <td><?php echo  h($row['designation']) ?></td>
                            <td><span class="badge bg-info text-dark"><?php echo  h($row['cell']) ?></span></td>
                            <td><?php echo  $row['sort_order'] ?></td>
                            <td>
                                <form action="index.php" method="POST" onsubmit="return confirm('Delete this member?');">
                                    <input type="hidden" name="action" value="delete_member">
                                    <input type="hidden" name="id" value="<?php echo  $row['id'] ?>">
                                    <button class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php elseif($page == 'notices'): ?>
            <!-- NOTICES -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add News / Notice / Order</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="add_notice">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Heading / Title</label>
                                <input type="text" name="title" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Category</label>
                                <select name="category" class="form-select" required>
                                    <option value="Announcements">Announcements</option>
                                    <option value="Notices / Circulars">Notices / Circulars</option>
                                    <option value="All Govt Order and Acts">All Govt Order and Acts</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label>Full Content (MS Word Style Formatting)</label>
                            <textarea name="content" id="editor" class="form-control" rows="10"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Feature Image (Optional)</label>
                                <input type="file" name="image" class="form-control" accept="image/*">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>PDF Attachment (Optional)</label>
                                <input type="file" name="pdf_file" class="form-control" accept=".pdf">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Publish News</button>
                    </form>
                </div>
            </div>

            <div class="table-responsive bg-white shadow-sm p-3 rounded">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Category</th>
                            <th>Title</th>
                            <th>Media</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $res = $conn->query("SELECT * FROM notices ORDER BY id DESC");
                        while($row = $res->fetch_assoc()):
                        ?>
                        <tr>
                            <td><?php echo  date('d M, Y', strtotime($row['created_at'])) ?></td>
                            <td><span class="badge bg-info text-dark"><?php echo  h($row['category']) ?></span></td>
                            <td><?php echo  h($row['title']) ?></td>
                            <td>
                                <?php if($row['image']): ?> <i class="fas fa-image text-muted" title="Has Image"></i> <?php endif; ?>
                                <?php if($row['pdf_file']): ?> <i class="fas fa-file-pdf text-danger" title="Has PDF"></i> <?php endif; ?>
                            </td>
                            <td>
                                <form action="index.php" method="POST" onsubmit="return confirm('Delete this notice?');">
                                    <input type="hidden" name="action" value="delete_notice">
                                    <input type="hidden" name="id" value="<?php echo  $row['id'] ?>">
                                    <button class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php elseif($page == 'videos'): ?>
            <!-- VIDEOS -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add YouTube Video</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST">
                        <input type="hidden" name="action" value="add_video">
                        <div class="mb-3">
                            <label>Video Title</label>
                            <input type="text" name="title" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label>YouTube Video ID (e.g. for https://www.youtube.com/watch?v=<b>dQw4w9WgXcQ</b>, enter <b>dQw4w9WgXcQ</b>)</label>
                            <input type="text" name="youtube_code" class="form-control" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Add Video</button>
                    </form>
                </div>
            </div>

            <div class="row">
                <?php 
                $res = $conn->query("SELECT * FROM videos ORDER BY id DESC");
                while($row = $res->fetch_assoc()):
                ?>
                <div class="col-md-4 mb-3">
                    <div class="card">
                        <div class="ratio ratio-16x9">
                            <iframe src="https://www.youtube.com/embed/<?php echo  h($row['youtube_code']) ?>" allowfullscreen></iframe>
                        </div>
                        <div class="card-body text-center">
                            <h6><?php echo  h($row['title']) ?></h6>
                            <form action="index.php" method="POST">
                                <input type="hidden" name="action" value="delete_video">
                                <input type="hidden" name="id" value="<?php echo  $row['id'] ?>">
                                <button class="btn btn-danger btn-sm w-100">Delete</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>

            <?php elseif($page == 'services'): ?>
            <!-- SERVICES -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add New Service</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST">
                        <input type="hidden" name="action" value="add_service">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Title (English)</label>
                                <input type="text" name="title" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Title (Hindi)</label>
                                <input type="text" name="title_hi" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Description (English)</label>
                                <textarea name="description" class="form-control" rows="3"></textarea>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Description (Hindi)</label>
                                <textarea name="description_hi" class="form-control" rows="3"></textarea>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Icon (FontAwesome class, e.g., fas fa-book)</label>
                                <input type="text" name="icon" class="form-control" value="fas fa-hands-helping">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Section</label>
                                <select name="section" class="form-control">
                                    <option value="Standard">Standard</option>
                                    <option value="Others Social Work">Others Social Work</option>
                                    <option value="Shaaskt Bharat">Shaaskt Bharat</option>
                                </select>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Service</button>
                    </form>
                </div>
            </div>

            <div class="table-responsive bg-white shadow-sm p-3 rounded">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Icon</th>
                            <th>Title</th>
                            <th>Section</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $res = $conn->query("SELECT * FROM services ORDER BY section ASC, id DESC");
                        while($row = $res->fetch_assoc()):
                        ?>
                        <tr>
                            <td><i class="<?php echo $row['icon'] ?> fa-2x text-primary"></i></td>
                            <td>
                                <div><b><?php echo h($row['title']) ?></b></div>
                                <small class="text-muted"><?php echo h($row['title_hi']) ?></small>
                            </td>
                            <td><span class="badge bg-secondary"><?php echo $row['section'] ?></span></td>
                            <td>
                                <form action="index.php" method="POST" onsubmit="return confirm('Delete this service?');">
                                    <input type="hidden" name="action" value="delete_service">
                                    <input type="hidden" name="id" value="<?php echo $row['id'] ?>">
                                    <button class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php elseif($page == 'gallery'): ?>
            <!-- GALLERY -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add Image to Service Gallery</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="add_gallery">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label>Select Service</label>
                                <select name="service_id" class="form-control" required>
                                    <?php 
                                    $sres = $conn->query("SELECT id, title FROM services");
                                    while($srow = $sres->fetch_assoc()) echo "<option value='".$srow['id']."'>".$srow['title']."</option>";
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Image</label>
                                <input type="file" name="image" class="form-control" required accept="image/*">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Title (Optional)</label>
                                <input type="text" name="title" class="form-control">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label>Subtitle / Description (Optional)</label>
                                <input type="text" name="subtitle" class="form-control">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Upload Image</button>
                    </form>
                </div>
            </div>

            <div class="row">
                <?php 
                $res = $conn->query("SELECT g.*, s.title as service_name FROM service_gallery g JOIN services s ON g.service_id = s.id ORDER BY g.id DESC");
                while($row = $res->fetch_assoc()):
                ?>
                <div class="col-md-3 mb-3">
                    <div class="card h-100">
                        <img src="../uploads/gallery/<?php echo h($row['image']) ?>" class="card-img-top" style="height: 150px; object-fit: cover;">
                        <div class="card-body">
                            <small class="badge bg-info mb-2"><?php echo h($row['service_name']) ?></small>
                            <h6 class="card-title"><?php echo h($row['title']) ?></h6>
                            <form action="index.php" method="POST">
                                <input type="hidden" name="action" value="delete_gallery">
                                <input type="hidden" name="id" value="<?php echo $row['id'] ?>">
                                <button class="btn btn-danger btn-sm w-100 mt-2">Delete</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>

            <?php elseif($page == 'sites'): ?>
            <!-- IMPORTANT SITES -->
            <div class="card mb-4 shadow-sm">
                <div class="card-header bg-white"><h5>Add Important Site / External Link</h5></div>
                <div class="card-body">
                    <form action="index.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="add_site">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label>Heading (Title)</label>
                                <input type="text" name="title" class="form-control" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Subheading</label>
                                <input type="text" name="subtitle" class="form-control">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>Site Logo/Image</label>
                                <input type="file" name="image" class="form-control" accept="image/*" required>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Add Site</button>
                    </form>
                </div>
            </div>
            
            <div class="row">
                <?php 
                $res = $conn->query("SELECT * FROM important_sites ORDER BY id DESC");
                if($res):
                while($row = $res->fetch_assoc()):
                    $img_src = (strpos($row['image'], 'http') === 0) ? $row['image'] : '../uploads/sites/'.$row['image'];
                ?>
                <div class="col-md-3 mb-3">
                    <div class="card text-center h-100">
                        <div class="card-body">
                            <img src="<?php echo  h($img_src) ?>" class="img-fluid mb-2" style="max-height: 80px;">
                            <h6 class="fw-bold"><?php echo  h($row['title']) ?></h6>
                            <p class="text-muted small"><?php echo  h($row['subtitle']) ?></p>
                            <form action="index.php" method="POST" onsubmit="return confirm('Delete this site?');">
                                <input type="hidden" name="action" value="delete_site">
                                <input type="hidden" name="id" value="<?php echo  $row['id'] ?>">
                                <button class="btn btn-danger btn-sm">Delete</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php 
                endwhile;
                endif; 
                ?>
            </div>

            <?php elseif($page == 'users'): ?>
            <!-- USERS -->
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-white"><h5>Registered Users</h5></div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Type</th>
                                    <th>Name / Institute</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $res = $conn->query("SELECT * FROM users ORDER BY id DESC");
                                if($res && $res->num_rows > 0):
                                while($row = $res->fetch_assoc()):
                                    $type = strtolower($row['type'] ?? 'individual');
                                    $status = strtolower($row['status'] ?? 'pending');
                                ?>
                                <tr>
                                    <td><?php echo $row['id'] ?></td>
                                    <td><span class="badge bg-<?php echo $type == 'individual' ? 'primary' : 'success' ?>"><?php echo ucfirst($type) ?></span></td>
                                    <td class="fw-bold">
                                        <?php echo h($row['name']) ?>
                                        <div class="small text-muted"><?php echo h($row['designation']); ?></div>
                                    </td>
                                    <td><?php echo h($row['email']) ?></td>
                                    <td><?php echo h($row['phone']) ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $status == 'active' ? 'success' : 'warning text-dark' ?>"><?php echo ucfirst($status) ?></span>
                                    </td>
                                    <td>
                                        <form method="POST" action="index.php" class="d-inline">
                                            <input type="hidden" name="action" value="update_user_status">
                                            <input type="hidden" name="id" value="<?php echo $row['id'] ?>">
                                            <?php if($status == 'pending'): ?>
                                                <input type="hidden" name="status" value="active">
                                                <button type="submit" class="btn btn-sm btn-success rounded-pill px-3">Activate</button>
                                            <?php else: ?>
                                                <input type="hidden" name="status" value="pending">
                                                <button type="submit" class="btn btn-sm btn-danger rounded-pill px-3">Deactivate</button>
                                            <?php endif; ?>
                                        </form>
                                    </td>
                                </tr>
                                <?php 
                                endwhile; 
                                else:
                                ?>
                                <tr><td colspan="8" class="text-center py-4">No users found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <?php elseif($page == 'constitution'): ?>
            <!-- CONSTITUTION UPLOAD -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-white"><h5>Upload Constitution PDF</h5></div>
                        <div class="card-body">
                            <form method="POST" action="index.php" enctype="multipart/form-data">
                                <input type="hidden" name="action" value="upload_constitution">
                                <div class="mb-3">
                                    <label class="form-label">Select PDF File</label>
                                    <input type="file" name="pdf_file" class="form-control" accept="application/pdf" required>
                                    <div class="form-text">This will overwrite the current Constitution PDF on the homepage.</div>
                                </div>
                                <button type="submit" class="btn btn-primary"><i class="fas fa-upload me-2"></i> Upload PDF</button>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-white"><h5>Current Constitution</h5></div>
                        <div class="card-body">
                            <?php if(file_exists('../uploads/constitution.pdf')): ?>
                                <div class="alert alert-success">
                                    <i class="fas fa-check-circle me-2"></i> A Constitution PDF is currently active.
                                </div>
                                <a href="../uploads/constitution.pdf" target="_blank" class="btn btn-outline-primary"><i class="fas fa-eye me-2"></i> View Current PDF</a>
                            <?php else: ?>
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-triangle me-2"></i> No Constitution PDF found. Please upload one.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <?php elseif($page == 'dynamic_pages'): ?>
            <!-- DYNAMIC PAGES -->
            <?php if(isset($_GET['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle me-2"></i> Page updated successfully.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if(isset($_GET['edit'])): 
                $id = (int)$_GET['edit'];
                $row = $conn->query("SELECT * FROM dynamic_pages WHERE id=$id")->fetch_assoc();
            ?>
                <div class="card shadow-sm">
                    <div class="card-header bg-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Edit Page: <?php echo h($row['title']); ?></h5>
                        <a href="index.php?page=dynamic_pages" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left me-1"></i> Back to List</a>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="index.php" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="update_dynamic_page">
                            <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                            <input type="hidden" name="existing_pdf" value="<?php echo h($row['pdf_file']); ?>">
                            
                            <div class="mb-4">
                                <label class="form-label fw-bold">Page Content</label>
                                <textarea name="content" id="editor"><?php echo htmlspecialchars($row['content']); ?></textarea>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label fw-bold">Upload New PDF (Optional)</label>
                                <input type="file" name="pdf_file" class="form-control" accept="application/pdf">
                                <?php if(!empty($row['pdf_file']) && file_exists('../uploads/'.$row['pdf_file'])): ?>
                                    <div class="form-text text-success mt-2">
                                        <i class="fas fa-check-circle me-1"></i> Current PDF: <a href="../uploads/<?php echo $row['pdf_file']; ?>" target="_blank">View File</a>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i> Save Changes</button>
                        </form>
                    </div>
                </div>
            <?php else: ?>
                <div class="card shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="mb-0">Manage Document Pages</h5>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Title</th>
                                        <th>Slug / URL</th>
                                        <th>Has PDF</th>
                                        <th class="text-end">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $res = $conn->query("SELECT * FROM dynamic_pages ORDER BY id ASC");
                                    if($res && $res->num_rows > 0):
                                        while($row = $res->fetch_assoc()):
                                    ?>
                                    <tr>
                                        <td class="fw-bold"><?php echo h($row['title']); ?></td>
                                        <td><code>page.php?slug=<?php echo h($row['slug']); ?></code></td>
                                        <td>
                                            <?php if(!empty($row['pdf_file']) && file_exists('../uploads/'.$row['pdf_file'])): ?>
                                                <span class="badge bg-success"><i class="fas fa-check"></i> Yes</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">No</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <a href="index.php?page=dynamic_pages&edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-edit me-1"></i> Edit</a>
                                            <a href="../page.php?slug=<?php echo h($row['slug']); ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fas fa-external-link-alt"></i> View</a>
                                        </td>
                                    </tr>
                                    <?php endwhile; else: ?>
                                    <tr><td colspan="4" class="text-center py-4">No dynamic pages found. Please run the seed script.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php else: ?>
            <div class="alert alert-warning">Section under construction or not found.</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Initialize CKEditor
    if(document.querySelector('#editor')) {
        ClassicEditor
            .create(document.querySelector('#editor'))
            .catch(error => {
                console.error(error);
            });
    }
</script>
</body>
</html>
