<?php
// Backup version of index.php with error handling
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // Check if required files exist
    if (!file_exists('config/config.php')) {
        throw new Exception('config/config.php not found');
    }
    if (!file_exists('config/database.php')) {
        throw new Exception('config/database.php not found');
    }
    if (!file_exists('models/Student.php')) {
        throw new Exception('models/Student.php not found');
    }

    require_once 'config/config.php';
    require_once 'config/database.php';
    require_once 'models/Student.php';

    requireLogin();

    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    $student = new Student($db);

    // Handle delete request
    if (isset($_GET['delete']) && !empty($_GET['delete'])) {
        $student->id = $_GET['delete'];
        if ($student->delete()) {
            $_SESSION['success_message'] = 'Student deleted successfully!';
        } else {
            $_SESSION['error_message'] = 'Failed to delete student!';
        }
        redirect('index.php');
    }

    // Get search term
    $search_term = isset($_GET['search']) ? sanitizeInput($_GET['search']) : '';

    // Get students data
    if (!empty($search_term)) {
        $stmt = $student->search($search_term);
    } else {
        $stmt = $student->readAll();
    }

    // Get statistics
    $stats = $student->getStats();

} catch (Exception $e) {
    // Show error page
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Error - Student Management System</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light">
        <div class="container mt-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header bg-danger text-white">
                            <h4 class="mb-0">System Error</h4>
                        </div>
                        <div class="card-body">
                            <p class="text-danger"><?php echo htmlspecialchars($e->getMessage()); ?></p>
                            <hr>
                            <h6>Possible Solutions:</h6>
                            <ul>
                                <li>Make sure you have run the installation script</li>
                                <li>Check if all files are uploaded correctly</li>
                                <li>Verify database connection settings</li>
                                <li>Check file permissions</li>
                            </ul>
                            <div class="mt-3">
                                <a href="install.php" class="btn btn-primary">Run Installation</a>
                                <a href="test.php" class="btn btn-secondary">Test System</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255, 255, 255, 0.1);
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .stats-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            border: none;
            transition: transform 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .stats-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar">
                    <div class="p-3">
                        <h4 class="text-center mb-4">
                            <i class="fas fa-graduation-cap me-2"></i>
                            <?php echo APP_NAME; ?>
                        </h4>
                        <nav class="nav flex-column">
                            <a class="nav-link active" href="index.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                            <a class="nav-link" href="add_student.php">
                                <i class="fas fa-user-plus me-2"></i>Add Student
                            </a>
                            <a class="nav-link" href="reports.php">
                                <i class="fas fa-chart-bar me-2"></i>Reports
                            </a>
                            <a class="nav-link" href="settings.php">
                                <i class="fas fa-cog me-2"></i>Settings
                            </a>
                            <hr class="my-3">
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Logout
                            </a>
                        </nav>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 px-0">
                <div class="main-content">
                    <!-- Top Navigation -->
                    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
                        <div class="container-fluid">
                            <span class="navbar-brand mb-0 h1">Dashboard</span>
                            <div class="d-flex align-items-center">
                                <span class="me-3">Welcome, <?php echo $_SESSION['admin_name']; ?></span>
                                <div class="dropdown">
                                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                        <i class="fas fa-user-circle"></i>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </nav>

                    <div class="p-4">
                        <!-- Statistics Cards -->
                        <div class="row mb-4">
                            <div class="col-md-3 mb-3">
                                <div class="card stats-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stats-icon bg-primary me-3">
                                            <i class="fas fa-users"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Total Students</h6>
                                            <h4 class="mb-0"><?php echo $stats['total_students']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card stats-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stats-icon bg-success me-3">
                                            <i class="fas fa-user-check"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Active Students</h6>
                                            <h4 class="mb-0"><?php echo $stats['active_students']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card stats-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stats-icon bg-info me-3">
                                            <i class="fas fa-rupee-sign"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Total Fees</h6>
                                            <h4 class="mb-0"><?php echo formatCurrency($stats['total_fees']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card stats-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stats-icon bg-warning me-3">
                                            <i class="fas fa-exclamation-triangle"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Pending Fees</h6>
                                            <h4 class="mb-0"><?php echo formatCurrency($stats['total_pending']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Students Table -->
                        <div class="card">
                            <div class="card-header">
                                <div class="row align-items-center">
                                    <div class="col-md-6">
                                        <h5 class="mb-0">
                                            <i class="fas fa-list me-2"></i>Students List
                                        </h5>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="d-flex justify-content-end">
                                            <form method="GET" class="d-flex me-3">
                                                <input type="text" class="form-control" name="search" 
                                                       placeholder="Search students..." value="<?php echo $search_term; ?>">
                                                <button type="submit" class="btn btn-outline-primary ms-2">
                                                    <i class="fas fa-search"></i>
                                                </button>
                                            </form>
                                            <a href="add_student.php" class="btn btn-primary">
                                                <i class="fas fa-plus me-2"></i>Add Student
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Student ID</th>
                                                <th>Name</th>
                                                <th>Father's Name</th>
                                                <th>DOB</th>
                                                <th>Gender</th>
                                                <th>Joining Date</th>
                                                <th>Total Fee</th>
                                                <th>Deposited</th>
                                                <th>Pending</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
                                            <tr>
                                                <td><strong><?php echo $row['student_id']; ?></strong></td>
                                                <td><?php echo $row['student_name']; ?></td>
                                                <td><?php echo $row['fathers_name']; ?></td>
                                                <td><?php echo formatDate($row['date_of_birth']); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $row['gender'] == 'Male' ? 'primary' : ($row['gender'] == 'Female' ? 'danger' : 'secondary'); ?>">
                                                        <?php echo $row['gender']; ?>
                                                    </span>
                                                </td>
                                                <td><?php echo formatDate($row['joining_date']); ?></td>
                                                <td><?php echo formatCurrency($row['total_fee']); ?></td>
                                                <td><?php echo formatCurrency($row['fees_deposit']); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $row['pending_fee'] > 0 ? 'warning' : 'success'; ?>">
                                                        <?php echo formatCurrency($row['pending_fee']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="badge bg-<?php echo $row['status'] == 'Active' ? 'success' : ($row['status'] == 'Inactive' ? 'danger' : 'info'); ?>">
                                                        <?php echo $row['status']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <a href="edit_student.php?id=<?php echo $row['id']; ?>" 
                                                       class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="view_student.php?id=<?php echo $row['id']; ?>" 
                                                       class="btn btn-sm btn-outline-info">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    <a href="?delete=<?php echo $row['id']; ?>" 
                                                       class="btn btn-sm btn-outline-danger"
                                                       onclick="return confirm('Are you sure you want to delete this student?')">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Container -->
    <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="toast show" role="alert">
                <div class="toast-header bg-success text-white">
                    <i class="fas fa-check-circle me-2"></i>
                    <strong class="me-auto">Success</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="toast show" role="alert">
                <div class="toast-header bg-danger text-white">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong class="me-auto">Error</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
