<?php 
/**
 * Mumbai University Dashboard & Slider Management
 * Location: /college/orc_sch/dashbored1.php
 */

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

session_start();

// Database connection
require_once '../db.php';

// Authentication check
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$school_id = 3; // Mumbai University ID
$admin_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'Admin';
$page_title = "Dashboard - Mumbai University";

// ==================== HANDLE FORM SUBMISSIONS ====================

// Add New Slider
if (isset($_POST['add_slider'])) {
    $title = mysqli_real_escape_string($db, $_POST['title']);
    $description = mysqli_real_escape_string($db, $_POST['description']);
    $status = mysqli_real_escape_string($db, $_POST['status']);
    $display_order = (int)$_POST['display_order'];
    
    // Handle file upload
    $image_path = '';
    if (isset($_FILES['slider_image']) && $_FILES['slider_image']['error'] == 0) {
        $upload_dir = '../uploads/sliders/';
        
        // Create directory if not exists
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_extension = pathinfo($_FILES['slider_image']['name'], PATHINFO_EXTENSION);
        $file_name = 'slider_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
        $target_file = $upload_dir . $file_name;
        
        if (move_uploaded_file($_FILES['slider_image']['tmp_name'], $target_file)) {
            $image_path = $target_file;
        }
    }
    
    $insert_query = "INSERT INTO slider_sch (school_id, title, description, image_path, status, display_order, created_at) 
                     VALUES ($school_id, '$title', '$description', '$image_path', '$status', $display_order, NOW())";
    
    if (mysqli_query($db, $insert_query)) {
        $success_message = "Slider added successfully!";
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// Delete Slider
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    
    // Get image path before deleting
    $get_image = mysqli_query($db, "SELECT image_path FROM slider_sch WHERE id = $delete_id AND school_id = $school_id");
    if ($row = mysqli_fetch_assoc($get_image)) {
        if (!empty($row['image_path']) && file_exists($row['image_path'])) {
            unlink($row['image_path']); // Delete image file
        }
    }
    
    $delete_query = "DELETE FROM slider_sch WHERE id = $delete_id AND school_id = $school_id";
    if (mysqli_query($db, $delete_query)) {
        $success_message = "Slider deleted successfully!";
    }
}

// Update Slider Status
if (isset($_GET['toggle_status'])) {
    $slider_id = (int)$_GET['toggle_status'];
    $update_query = "UPDATE slider_sch 
                     SET status = IF(status = 'active', 'inactive', 'active') 
                     WHERE id = $slider_id AND school_id = $school_id";
    mysqli_query($db, $update_query);
    header("Location: dashbored1.php");
    exit;
}

// ==================== GET STATISTICS ====================
$stats = [
    'total_students' => 0,
    'total_sliders' => 0,
    'total_gallery' => 0,
    'total_contacts' => 0,
    'total_content' => 0
];

// Safe count function with table existence check
function safeCount($db, $table, $school_id) {
    $school_id = (int)$school_id;
    $table_name = mysqli_real_escape_string($db, $table);
    
    // First check if table exists
    $check_query = "SHOW TABLES LIKE '$table_name'";
    $check_result = @mysqli_query($db, $check_query);
    
    if (!$check_result || mysqli_num_rows($check_result) == 0) {
        return 0; // Table doesn't exist, return 0
    }
    
    // Table exists, now count rows
    $count_query = "SELECT COUNT(*) as count FROM `$table_name` WHERE school_id = $school_id";
    $count_result = @mysqli_query($db, $count_query);
    
    if ($count_result) {
        $row = mysqli_fetch_assoc($count_result);
        return $row ? (int)$row['count'] : 0;
    }
    
    return 0;
}

// Get all statistics safely
$stats['total_students'] = safeCount($db, 'students', $school_id);
$stats['total_sliders'] = safeCount($db, 'slider_sch', $school_id);
$stats['total_gallery'] = safeCount($db, 'gallery_images', $school_id);
$stats['total_contacts'] = safeCount($db, 'contact_submissions', $school_id);
$stats['total_content'] = safeCount($db, 'content_pages', $school_id);

// Fetch all sliders
$sliders_query = "SELECT * FROM slider_sch WHERE school_id = $school_id ORDER BY display_order ASC, id DESC";
$sliders_result = @mysqli_query($db, $sliders_query);
$total_sliders = $sliders_result ? mysqli_num_rows($sliders_result) : 0;

require_once '../header.php';
?>

<style>
/* ==================== COMPLETE DASHBOARD STYLES ==================== */

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: #f5f6fa;
    color: #2c3e50;
}

/* Sidebar */
.sidebar {
    position: fixed;
    left: 0;
    top: 0;
    width: 260px;
    height: 100vh;
    background: linear-gradient(180deg, #2c3e50 0%, #34495e 100%);
    color: white;
    padding: 20px 0;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 2px 0 10px rgba(0,0,0,0.1);
}

.sidebar-header {
    padding: 20px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    margin-bottom: 20px;
}

.sidebar-header h2 {
    font-size: 1.3em;
    font-weight: 600;
}

.sidebar-menu {
    padding: 0 10px;
}

.menu-item {
    display: block;
    padding: 12px 20px;
    color: #ecf0f1;
    text-decoration: none;
    border-radius: 8px;
    margin-bottom: 5px;
    transition: all 0.3s ease;
    font-size: 0.95em;
}

.menu-item:hover {
    background: rgba(255,255,255,0.1);
    padding-left: 25px;
}

.menu-item.active {
    background: #3498db;
    font-weight: 600;
}

/* Main Content */
.main-content-area {
    margin-left: 260px;
    padding: 30px;
    min-height: 100vh;
}

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

/* Page Header */
.page-header {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
}

.page-header h2 {
    color: #2c3e50;
    font-size: 2em;
    margin-bottom: 10px;
}

.page-header p {
    color: #7f8c8d;
    font-size: 1.05em;
}

/* Statistics Grid */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    gap: 20px;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8em;
}

.stat-icon.blue { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.green { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
.stat-icon.orange { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.purple { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.teal { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

.stat-info h3 {
    font-size: 2em;
    color: #2c3e50;
    margin-bottom: 5px;
}

.stat-info p {
    color: #7f8c8d;
    font-size: 0.95em;
}

/* Quick Actions */
.actions-section {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
}

.actions-section h3 {
    color: #2c3e50;
    margin-bottom: 20px;
    font-size: 1.4em;
}

.action-buttons {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
}

.action-btn {
    padding: 15px 25px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    text-decoration: none;
    border-radius: 8px;
    text-align: center;
    font-weight: 600;
    transition: all 0.3s ease;
}

.action-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.action-btn.green { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
.action-btn.red { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.action-btn.purple { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.action-btn.orange { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.action-btn.teal { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

/* Alert Messages */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-weight: 500;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

/* Slider Management Section */
.slider-section {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
}

.slider-section h3 {
    color: #2c3e50;
    margin-bottom: 20px;
    font-size: 1.4em;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.btn-add {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    font-size: 0.9em;
    cursor: pointer;
    border: none;
}

.btn-add:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

/* Add Slider Form */
.form-container {
    background: #f8f9fa;
    padding: 25px;
    border-radius: 10px;
    margin-bottom: 30px;
    display: none;
}

.form-container.show {
    display: block;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #2c3e50;
}

.form-control {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 1em;
    transition: border 0.3s ease;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

textarea.form-control {
    resize: vertical;
    min-height: 100px;
}

.btn-submit {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    color: white;
    padding: 12px 30px;
    border: none;
    border-radius: 8px;
    font-size: 1em;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

/* Sliders Table */
.sliders-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

.sliders-table th {
    background: #f8f9fa;
    padding: 15px;
    text-align: left;
    font-weight: 600;
    color: #2c3e50;
    border-bottom: 2px solid #e9ecef;
}

.sliders-table td {
    padding: 15px;
    border-bottom: 1px solid #e9ecef;
}

.sliders-table tr:hover {
    background: #f8f9fa;
}

.slider-thumb {
    width: 100px;
    height: 60px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.status-badge {
    padding: 6px 15px;
    border-radius: 20px;
    font-size: 0.85em;
    font-weight: 600;
    display: inline-block;
}

.status-active {
    background: #d4edda;
    color: #155724;
}

.status-inactive {
    background: #f8d7da;
    color: #721c24;
}

.action-buttons-table {
    display: flex;
    gap: 8px;
}

.btn-action {
    padding: 6px 12px;
    border-radius: 6px;
    text-decoration: none;
    font-size: 0.85em;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-toggle {
    background: #3498db;
    color: white;
}

.btn-delete {
    background: #e74c3c;
    color: white;
}

.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 3px 10px rgba(0,0,0,0.2);
}

.no-data {
    text-align: center;
    padding: 40px;
    color: #7f8c8d;
}

/* Responsive */
@media (max-width: 768px) {
    .sidebar {
        width: 100%;
        height: auto;
        position: relative;
    }
    
    .main-content-area {
        margin-left: 0;
        padding: 15px;
    }
    
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .action-buttons {
        grid-template-columns: 1fr;
    }
    
    .section-header {
        flex-direction: column;
        gap: 15px;
    }
    
    .sliders-table {
        display: block;
        overflow-x: auto;
    }
}
</style>

<!-- SIDEBAR -->
<div class="sidebar">
    <div class="sidebar-header">
        <h2>📚 Mumbai University</h2>
    </div>
    <nav class="sidebar-menu">
        <a href="/college/orc_sch/dashbored1.php" class="menu-item <?php echo $current_page == 'dashbored1.php' ? 'active' : ''; ?>">🏠 Dashboard</a>
        <a href="/college/orc_sch/course.php" class="menu-item <?php echo $current_page == 'course.php' ? 'active' : ''; ?>">📚 Course</a>
        <a href="/college/orc_sch/teachers.php" class="menu-item <?php echo $current_page == 'teachers.php' ? 'active' : ''; ?>">👨‍🏫 Teachers</a>
        <a href="/college/orc_sch/complaint.php" class="menu-item <?php echo ($current_page == 'complaint.php') ? 'active' : ''; ?>">👨‍🏫Complaint</a>
        <a href="/college/orc_sch/gallery.php" class="menu-item <?php echo $current_page == 'gallery.php' ? 'active' : ''; ?>">🖼️ Gallery</a>
        <a href="/college/orc_sch/contact.php" class="menu-item <?php echo $current_page == 'contact.php' ? 'active' : ''; ?>">📧 Contact</a>
        <a href="/college/orc_sch/logout.php" class="menu-item <?php echo ($current_page == 'logout.php') ? 'active' : ''; ?>">🚪Logout</a>
    </nav>
</div>

<!-- MAIN CONTENT -->
<div class="main-content-area">
    <div class="dashboard-container">
        
        <!-- Page Header -->
        <div class="page-header">
            <h2>🎓ORCHID School</h2>
            <p>Welcome back, <?php echo htmlspecialchars($admin_name); ?>! Manage your university content and data.</p>
        </div>

        <!-- Success/Error Messages -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success">✓ <?php echo $success_message; ?></div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-error">✗ <?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="stats-grid">
            
            <div class="stat-card">
                <div class="stat-icon blue">👨‍🎓</div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_students']); ?></h3>
                    <p>Total Students</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon green">🎞️</div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_sliders']); ?></h3>
                    <p>Total Sliders</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon orange">🖼️</div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_gallery']); ?></h3>
                    <p>Gallery Images</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon purple">📧</div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_contacts']); ?></h3>
                    <p>Contact Messages</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon teal">📝</div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_content']); ?></h3>
                    <p>Content Pages</p>
                </div>
            </div>

        </div>

        <!-- Quick Actions -->
        <div class="actions-section">
            <h3>⚡ Quick Actions</h3>
            <div class="action-buttons">
                <a href="#slider-management" class="action-btn" onclick="document.getElementById('add-form').classList.toggle('show'); return false;">🎞️ Add New Slider</a>
                <a href="../gallery.php?school_id=3" class="action-btn green">🖼️ Manage Gallery</a>
                <a href="../students.php?school_id=3" class="action-btn red">👨‍🎓 View Students</a>
                <a href="../contacts.php?school_id=3" class="action-btn purple">📧 View Contacts</a>
                <a href="../manage_content.php?school_id=3" class="action-btn orange">📝 Manage Content</a>
                <a href="../donations.php?school_id=3" class="action-btn teal">💰 View Donations</a>
            </div>
        </div>

        <!-- Slider Management Section -->
        <div class="slider-section" id="slider-management">
            <div class="section-header">
                <h3>🎞️ Slider Management (<?php echo $total_sliders; ?>)</h3>
                <button class="btn-add" onclick="document.getElementById('add-form').classList.toggle('show');">➕ Add New Slider</button>
            </div>

            <!-- Add New Slider Form -->
            <div class="form-container" id="add-form">
                <h4 style="margin-bottom: 15px; color: #2c3e50;">➕ Add New Slider</h4>
                <form method="POST" enctype="multipart/form-data">
                    
                    <div class="form-group">
                        <label>Slider Title *</label>
                        <input type="text" name="title" class="form-control" required placeholder="Enter slider title">
                    </div>

                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" class="form-control" placeholder="Enter slider description"></textarea>
                    </div>

                    <div class="form-group">
                        <label>Slider Image *</label>
                        <input type="file" name="slider_image" class="form-control" accept="image/*" required>
                        <small style="color: #7f8c8d;">Recommended size: 1920x600 pixels</small>
                    </div>

                    <div class="form-group">
                        <label>Display Order</label>
                        <input type="number" name="display_order" class="form-control" value="0" min="0">
                        <small style="color: #7f8c8d;">Lower number = Higher priority</small>
                    </div>

                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>

                    <button type="submit" name="add_slider" class="btn-submit">💾 Add Slider</button>
                </form>
            </div>

            <!-- Existing Sliders List -->
            <?php if ($total_sliders > 0): ?>
                <table class="sliders-table">
                    <thead>
                        <tr>
                            <th>Image</th>
                            <th>Title</th>
                            <th>Description</th>
                            <th>Order</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($slider = mysqli_fetch_assoc($sliders_result)): ?>
                            <tr>
                                <td>
                                    <?php if (!empty($slider['image_path']) && file_exists($slider['image_path'])): ?>
                                        <img src="<?php echo htmlspecialchars($slider['image_path']); ?>" 
                                             alt="Slider" class="slider-thumb">
                                    <?php else: ?>
                                        <div style="width:100px;height:60px;background:#ddd;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#999;font-size:0.8em;">No Image</div>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo htmlspecialchars($slider['title']); ?></strong></td>
                                <td><?php echo htmlspecialchars(substr($slider['description'], 0, 60)) . '...'; ?></td>
                                <td>#<?php echo $slider['display_order']; ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $slider['status']; ?>">
                                        <?php echo ucfirst($slider['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons-table">
                                        <a href="?toggle_status=<?php echo $slider['id']; ?>" 
                                           class="btn-action btn-toggle"
                                           title="Toggle Status">
                                            🔄 Toggle
                                        </a>
                                        <a href="?delete_id=<?php echo $slider['id']; ?>" 
                                           class="btn-action btn-delete"
                                           onclick="return confirm('Are you sure you want to delete this slider?')"
                                           title="Delete Slider">
                                            🗑️ Delete
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-data">
                    <p>📭 No sliders found</p>
                    <p style="margin-top: 10px;">Click "Add New Slider" button above to create your first slider!</p>
                </div>
            <?php endif; ?>

        </div>

    </div>
</div>

<?php require_once 'footer.php'; ?>
