<?php

require_once __DIR__ . '/library/auth.php';


$school_id = $_SESSION['school_id'];

$current_session_id = get_current_session_id($pdo);

$current_session_name = get_current_session_name($pdo);


/*
======================================================
TOTAL STUDENTS
======================================================
*/

$stmt = $pdo->prepare("

    SELECT COUNT(*)

    FROM student_sessions

    WHERE school_id = ?
    AND session_id = ?
    AND status = 'Active'

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$total_students = $stmt->fetchColumn();


// ======================================================
// TOTAL TEACHERS
// ======================================================

$stmt = $pdo->prepare("

    SELECT
        COUNT(*)

    FROM teachers

    WHERE school_id = ?
    AND status = 'Active'

");

$stmt->execute([$school_id]);

$total_teachers = $stmt->fetchColumn();


// ======================================================
// TOTAL CLASSES
// ======================================================

$stmt = $pdo->prepare("

    SELECT
        COUNT(*)

    FROM classes

    WHERE school_id = ?

");

$stmt->execute([$school_id]);

$total_classes = $stmt->fetchColumn();


// ======================================================
// TOTAL FEES COLLECTION
// ======================================================

$stmt = $pdo->prepare("

    SELECT
        COALESCE(SUM(paid_amount), 0)

    FROM fee_payments

    WHERE school_id = ?
    AND session_id = ?

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$total_fees = $stmt->fetchColumn();


// ======================================================
// TODAY COLLECTION
// ======================================================

$stmt = $pdo->prepare("

    SELECT
        COALESCE(SUM(paid_amount), 0)

    FROM fee_payments

    WHERE school_id = ?
    AND session_id = ?
    AND DATE(payment_date) = CURDATE()

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$today_collection = $stmt->fetchColumn();


// ======================================================
// TOTAL EXPENSE
// ======================================================

$stmt = $pdo->prepare("

    SELECT
        COALESCE(SUM(amount), 0)

    FROM expenses

    WHERE school_id = ?
    AND session_id = ?

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$total_expense = $stmt->fetchColumn();
/*
======================================================
PENDING FEES
======================================================
*/

$stmt = $pdo->prepare("

    SELECT

        COALESCE(

            (

                SELECT SUM(

                    cf.total_fees * class_students.total_students

                )

                FROM class_fees cf

                LEFT JOIN (

                    SELECT

                        class_id,

                        COUNT(*) AS total_students

                    FROM student_sessions

                    WHERE school_id = ?
                    AND session_id = ?
                    AND status = 'Active'

                    GROUP BY class_id

                ) class_students

                ON cf.class_id = class_students.class_id

                WHERE cf.school_id = ?

            ),

            0

        )

        -

        COALESCE(

            (

                SELECT SUM(paid_amount)

                FROM fee_payments

                WHERE school_id = ?
                AND session_id = ?

            ),

            0

        )

        AS pending_fees

");

$stmt->execute([

    $school_id,
    $current_session_id,

    $school_id,

    $school_id,
    $current_session_id

]);

$pending_fees = $stmt->fetchColumn();

// ======================================================
// NOTIFICATIONS
// ======================================================

$stmt = $pdo->prepare("

    SELECT *

    FROM notifications

    WHERE is_active = 1
    AND school_id = ?

    ORDER BY created_at DESC

    LIMIT 5

");

$stmt->execute([$school_id]);

$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

$notifications_count = count($notifications);


// ======================================================
// BIRTHDAYS
// ======================================================

$stmt = $pdo->prepare("

    SELECT

        'Student' AS type,
        name

    FROM students

    WHERE MONTH(dob) = MONTH(CURDATE())
    AND DAY(dob) = DAY(CURDATE())
    AND school_id = ?

    UNION ALL

    SELECT

        'Teacher' AS type,
        name

    FROM teachers

    WHERE MONTH(date_of_birth) = MONTH(CURDATE())
    AND DAY(date_of_birth) = DAY(CURDATE())
    AND status = 'Active'
    AND school_id = ?

");

$stmt->execute([

    $school_id,
    $school_id

]);

$birthdays = $stmt->fetchAll(PDO::FETCH_ASSOC);

$birthdays_count = count($birthdays);


// ======================================================
// MONTHLY FEE COLLECTION CHART
// ======================================================

$fees_chart_labels = [];

$fees_chart_data = [];

$stmt = $pdo->prepare("

    SELECT

        MONTHNAME(payment_date) AS month_name,

        SUM(paid_amount) AS total_amount

    FROM fee_payments

    WHERE school_id = ?
    AND session_id = ?

    GROUP BY MONTH(payment_date)

    ORDER BY MONTH(payment_date)

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$feesChart = $stmt->fetchAll(PDO::FETCH_ASSOC);


foreach ($feesChart as $row) {

    $fees_chart_labels[] = $row['month_name'];

    $fees_chart_data[] = $row['total_amount'];
}


// ======================================================
// INCOME VS EXPENSE CHART
// ======================================================

$income_chart = [];

$expense_chart = [];

$chart_months = [];


// INCOME

$stmt = $pdo->prepare("

    SELECT

        MONTHNAME(payment_date) AS month_name,

        SUM(amount) AS total_income

    FROM income

    WHERE school_id = ?
    AND session_id = ?

    GROUP BY MONTH(payment_date)

    ORDER BY MONTH(payment_date)

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$incomeData = $stmt->fetchAll(PDO::FETCH_ASSOC);


foreach ($incomeData as $row) {

    $income_chart[] = $row['total_income'];

    $chart_months[] = $row['month_name'];
}


// EXPENSE

$stmt = $pdo->prepare("

    SELECT

        MONTHNAME(payment_date) AS month_name,

        SUM(amount) AS total_expense

    FROM expenses

    WHERE school_id = ?
    AND session_id = ?

    GROUP BY MONTH(payment_date)

    ORDER BY MONTH(payment_date)

");

$stmt->execute([

    $school_id,
    $current_session_id

]);

$expenseData = $stmt->fetchAll(PDO::FETCH_ASSOC);


foreach ($expenseData as $row) {

    $expense_chart[] = $row['total_expense'];
}


// ======================================================
// PAGE TITLE
// ======================================================

$page_title = 'Dashboard';

require_once __DIR__ . '/include/header.php';

require_once __DIR__ . '/include/sidebar.php';

?>


<div class="content-wrapper">

    <!-- ============================================= -->
    <!-- CONTENT HEADER -->
    <!-- ============================================= -->

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-2">

                <div class="col-sm-6">

                    <h1>

                        Dashboard

                    </h1>

                </div>

            </div>

        </div>

    </section>


    <!-- ============================================= -->
    <!-- MAIN CONTENT -->
    <!-- ============================================= -->

    <section class="content">

        <div class="container-fluid">


            <!-- ========================================= -->
            <!-- WELCOME CARD -->
            <!-- ========================================= -->

           <div class="card modern-card mb-4 border-0">

    <div
        class="card-body"
        style="
            background: linear-gradient(135deg,#1e293b,#0f172a);
            border-radius: 18px;
            padding: 35px;
            color: #fff;
        "
    >

        <div class="row align-items-center">

            <!-- LEFT -->

            <div class="col-lg-8">

                <div class="d-flex align-items-center mb-3">

                    <div
                        style="
                            width:70px;
                            height:70px;
                            border-radius:18px;
                            background:rgba(255,255,255,0.12);
                            display:flex;
                            align-items:center;
                            justify-content:center;
                            font-size:28px;
                            margin-right:18px;
                        "
                    >

                        <i class="fas fa-school"></i>

                    </div>

                    <div>

                        <h2
                            class="font-weight-bold mb-1"
                            style="font-size:32px;"
                        >

                            Welcome Back,
                            <?= htmlspecialchars($_SESSION['name']); ?> 👋

                        </h2>

                        <p
                            class="mb-0"
                            style="
                                color: rgba(255,255,255,0.75);
                                font-size:15px;
                            "
                        >

                            Manage your school operations efficiently
                            from one centralized ERP dashboard.

                        </p>

                    </div>

                </div>

            </div>


            <!-- RIGHT -->

            <div class="col-lg-4 text-lg-right mt-4 mt-lg-0">

                <div
                    style="
                        background: rgba(255,255,255,0.08);
                        padding: 18px;
                        border-radius: 16px;
                        display:inline-block;
                        min-width:240px;
                    "
                >

                    <div
                        style="
                            font-size:15px;
                            color:rgba(255,255,255,0.7);
                            margin-bottom:8px;
                        "
                    >

                        Current Session

                    </div>

                    <h4 class="font-weight-bold mb-3">

                        <?= htmlspecialchars($current_session_name); ?>

                    </h4>

                    <div class="d-flex justify-content-between">

                        <span
                            class="badge badge-light px-3 py-2"
                            style="
                                font-size:13px;
                                border-radius:10px;
                            "
                        >

                            <?= strtoupper($_SESSION['role']); ?>

                        </span>

                        <span
                            style="
                                font-size:14px;
                                color:rgba(255,255,255,0.8);
                            "
                        >

                            <?= date('d M Y'); ?>

                        </span>

                    </div>

                </div>

            </div>

        </div>

    </div>

</div>


            <!-- ========================================= -->
            <!-- STATS -->
            <!-- ========================================= -->

            <div class="row">

    <!-- STUDENTS -->

    <div class="col-lg-3 col-md-6 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-blue">

                <i class="fas fa-user-graduate"></i>

            </div>

            <h3>

                <?= number_format($total_students); ?>

            </h3>

            <p>

                Total Students

            </p>

        </div>

    </div>


    <!-- TEACHERS -->

    <div class="col-lg-3 col-md-6 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-green">

                <i class="fas fa-chalkboard-teacher"></i>

            </div>

            <h3>

                <?= number_format($total_teachers); ?>

            </h3>

            <p>

                Total Teachers

            </p>

        </div>

    </div>


    <!-- CLASSES -->

    <div class="col-lg-3 col-md-6 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-orange">

                <i class="fas fa-school"></i>

            </div>

            <h3>

                <?= number_format($total_classes); ?>

            </h3>

            <p>

                Total Classes

            </p>

        </div>

    </div>


    <!-- FEES -->

    <div class="col-lg-3 col-md-6 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-red">

                <i class="fas fa-money-bill-wave"></i>

            </div>

            <h3>

                ₹<?= number_format($total_fees); ?>

            </h3>

            <p>

                Total Collection

            </p>

        </div>

    </div>


    <!-- TODAY -->

    <div class="col-lg-4 col-md-6 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-purple">

                <i class="fas fa-cash-register"></i>

            </div>

            <h3>

                ₹<?= number_format($today_collection); ?>

            </h3>

            <p>

                Today's Collection

            </p>

        </div>

    </div>


    <!-- EXPENSE -->

    <div class="col-lg-4 col-md-6 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-dark">

                <i class="fas fa-wallet"></i>

            </div>

            <h3>

                ₹<?= number_format($total_expense); ?>

            </h3>

            <p>

                Total Expense

            </p>

        </div>

    </div>


    <!-- PENDING -->

    <div class="col-lg-4 col-md-12 mb-4">

        <div class="dashboard-stat-card">

            <div class="stat-icon bg-red">

                <i class="fas fa-exclamation-circle"></i>

            </div>

            <h3>

                ₹<?= number_format($pending_fees); ?>

            </h3>

            <p>

                Pending Fees

            </p>

        </div>

    </div>

</div>


            <!-- ========================================= -->
            <!-- QUICK ACTIONS -->
            <!-- ========================================= -->

            <div class="card modern-card mb-4">

    <div class="card-header d-flex justify-content-between align-items-center">

        <h3 class="card-title">

            Quick Actions

        </h3>

        <span class="badge badge-primary p-2">

            Shortcuts

        </span>

    </div>

    <div class="card-body">

        <div class="row">

            <!-- ADD STUDENT -->

            <div class="col-lg-2 col-md-3 col-6 mb-4">

                <a
                    href="<?= WEB_ROOT; ?>student/add.php"
                    class="quick-card"
                >

                    <i class="fas fa-user-plus text-primary"></i>

                    <h6>

                        Add Student

                    </h6>

                </a>

            </div>


            <!-- FEES -->

            <?php if (in_array($_SESSION['role'], ['admin', 'accountant'])): ?>

            <div class="col-lg-2 col-md-3 col-6 mb-4">

                <a
                    href="<?= WEB_ROOT; ?>fees/add_fees.php"
                    class="quick-card"
                >

                    <i class="fas fa-money-check-alt text-success"></i>

                    <h6>

                        Collect Fees

                    </h6>

                </a>

            </div>

            <?php endif; ?>


            <!-- ATTENDANCE -->

            <div class="col-lg-2 col-md-3 col-6 mb-4">

                <a
                    href="<?= WEB_ROOT; ?>attendance/index.php"
                    class="quick-card"
                >

                    <i class="fas fa-clipboard-check text-warning"></i>

                    <h6>

                        Attendance

                    </h6>

                </a>

            </div>


            <!-- NOTICE -->

            <div class="col-lg-2 col-md-3 col-6 mb-4">

                <a
                    href="<?= WEB_ROOT; ?>notifications/add_notice.php"
                    class="quick-card"
                >

                    <i class="fas fa-bell text-info"></i>

                    <h6>

                        Add Notice

                    </h6>

                </a>

            </div>


            <!-- RESULTS -->

            <div class="col-lg-2 col-md-3 col-6 mb-4">

                <a
                    href="<?= WEB_ROOT; ?>marksheet/generate_result.php"
                    class="quick-card"
                >

                    <i class="fas fa-poll text-danger"></i>

                    <h6>

                        Results

                    </h6>

                </a>

            </div>


            <!-- ENQUIRIES -->

            <div class="col-lg-2 col-md-3 col-6 mb-4">

                <a
                    href="<?= WEB_ROOT; ?>enquiry/index.php"
                    class="quick-card"
                >

                    <i class="fas fa-user-clock text-dark"></i>

                    <h6>

                        Enquiries

                    </h6>

                </a>

            </div>

        </div>

    </div>

</div>


            <!-- ========================================= -->
            <!-- BOTTOM ROW -->
            <!-- ========================================= -->

            <div class="row">


                <!-- BIRTHDAYS -->

                <div class="col-md-6">

                    <div class="card modern-card card-danger shadow-sm">

                        <div class="card-header">

                            <h3 class="card-title">

                                🎂 Today's Birthdays

                            </h3>

                            <div class="card-tools">

                                <span class="badge badge-danger">

                                    <?= $birthdays_count; ?>

                                </span>

                            </div>

                        </div>

                        <div class="card-body">


                            <?php if ($birthdays): ?>

                                <?php foreach ($birthdays as $bday): ?>

                                    <div class="feed-item">

                                        <strong>

                                            <?= htmlspecialchars($bday['name']); ?>

                                        </strong>

                                        <span class="badge badge-primary float-right">

                                            <?= $bday['type']; ?>

                                        </span>

                                    </div>

                                <?php endforeach; ?>

                            <?php else: ?>

                                <div class="text-center text-muted py-4">

                                    <i class="fas fa-birthday-cake fa-3x mb-3"></i>

                                    <p>

                                        No birthdays today

                                    </p>

                                </div>

                            <?php endif; ?>

                        </div>

                    </div>

                </div>


                <!-- NOTIFICATIONS -->

                <div class="col-md-6">

                    <div class="card modern-card card-warning shadow-sm">

                        <div class="card-header">

                            <h3 class="card-title">

                                Notifications

                            </h3>

                            <div class="card-tools">

                                <span class="badge badge-warning">

                                    <?= $notifications_count; ?>

                                </span>

                            </div>

                        </div>

                        <div class="card-body">


                            <?php if ($notifications): ?>

                                <?php foreach ($notifications as $notif): ?>

                                    <div class="alert alert-light border">

                                        <strong>

                                            <?= htmlspecialchars($notif['title']); ?>

                                        </strong>

                                        <br>

                                        <small>

                                            <?= htmlspecialchars(
                                                mb_strimwidth(
                                                    $notif['message'],
                                                    0,
                                                    100,
                                                    '...'
                                                )
                                            ); ?>

                                        </small>

                                    </div>

                                <?php endforeach; ?>

                            <?php else: ?>

                                <div class="text-center text-muted py-4">

                                    <i class="fas fa-bell-slash fa-3x mb-3"></i>

                                    <p>

                                        No notifications available

                                    </p>

                                </div>

                            <?php endif; ?>

                        </div>

                    </div>

                </div>

            </div>
			<?php

						$activity_stmt = $pdo->prepare("

							SELECT

								module,
								action,
								message,
								created_at

							FROM audit_logs

							WHERE school_id = ?

							ORDER BY id DESC

							LIMIT 5

						");

						$activity_stmt->execute([$school_id]);

						$activities = $activity_stmt->fetchAll(PDO::FETCH_ASSOC);

						?>

						<div class="card modern-card card-dark shadow-sm mb-4">

							<div class="card-header">

								<h3 class="card-title">

									Recent Activities

								</h3>

							</div>

							<div class="card-body">

								<?php if($activities): ?>

									<?php foreach($activities as $activity): ?>

										<div class="alert alert-light border">

											<strong>

												<?= htmlspecialchars($activity['module']) ?>

											</strong>

											-

											<?= htmlspecialchars($activity['action']) ?>

											<br>

											<small>

												<?= htmlspecialchars($activity['message']) ?>

											</small>

											<br>

											<small class="text-muted">

												<?= date(
													'd M Y h:i A',
													strtotime($activity['created_at'])
												) ?>

											</small>

										</div>

									<?php endforeach; ?>

								<?php else: ?>

									<div class="text-muted">

										No recent activity found.

									</div>

								<?php endif; ?>

							</div>

						</div>


            <!-- ========================================= -->
            <!-- CHARTS -->
            <!-- ========================================= -->

            <?php if (in_array($_SESSION['role'], ['admin', 'accountant'])): ?>

            <div class="row">


                <div class="col-md-6">

                    <div class="card modern-card card-primary shadow-sm">

                        <div class="card-header">

                            <h3 class="card-title">

                                Monthly Fee Collection

                            </h3>

                        </div>

                        <div class="card-body">

                            <canvas id="feesChart"></canvas>

                        </div>

                    </div>

                </div>


                <div class="col-md-6">

                    <div class="card modern-card card-success shadow-sm">

                        <div class="card-header">

                            <h3 class="card-title">

                                Income vs Expense

                            </h3>

                        </div>

                        <div class="card-body">

                            <canvas id="incomeExpenseChart"></canvas>

                        </div>

                    </div>

                </div>

            </div>

            <?php endif; ?>


            <!-- ========================================= -->
            <!-- SYSTEM INFO -->
            <!-- ========================================= -->

            <div class="card modern-card card-secondary shadow-sm">

                <div class="card-header">

                    <h3 class="card-title">

                        System Information

                    </h3>

                </div>

                <div class="card-body">

                    <div class="row">


                        <div class="col-md-4">

                            <strong>

                                Logged In User

                            </strong>

                            <br>

                            <?= htmlspecialchars($_SESSION['name']); ?>

                        </div>


                        <div class="col-md-4">

                            <strong>

                                Role

                            </strong>

                            <br>

                            <?= strtoupper($_SESSION['role']); ?>

                        </div>


                        <div class="col-md-4">

                            <strong>

                                Academic Session

                            </strong>

                            <br>

                            <?= htmlspecialchars($current_session_name); ?>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>


<?php if (in_array($_SESSION['role'], ['admin', 'accountant'])): ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>

const feesCtx =
    document
    .getElementById('feesChart')
    .getContext('2d');


new Chart(feesCtx, {

    type: 'bar',

    data: {

        labels: <?= json_encode($fees_chart_labels); ?>,

        datasets: [{

            label: 'Fee Collection',

            data: <?= json_encode($fees_chart_data); ?>,

            borderWidth: 1
        }]
    },

    options: {

        responsive: true,

        maintainAspectRatio: false
    }
});


const incomeExpenseCtx =
    document
    .getElementById('incomeExpenseChart')
    .getContext('2d');


new Chart(incomeExpenseCtx, {

    type: 'line',

    data: {

        labels: <?= json_encode($chart_months); ?>,

        datasets: [

            {

                label: 'Income',

                data: <?= json_encode($income_chart); ?>,

                borderWidth: 2
            },

            {

                label: 'Expense',

                data: <?= json_encode($expense_chart); ?>,

                borderWidth: 2
            }
        ]
    },

    options: {

        responsive: true,

        maintainAspectRatio: false
    }
});

</script>

<?php endif; ?>


<style>
.dashboard-stat-card {

    background: #ffffff;

    border-radius: 18px;

    padding: 22px;

    position: relative;

    overflow: hidden;

    box-shadow: 0 4px 18px rgba(0,0,0,0.05);

    transition: 0.25s ease;
}

.dashboard-stat-card:hover {

    transform: translateY(-5px);
}

.dashboard-stat-card .stat-icon {

    width: 58px;

    height: 58px;

    border-radius: 16px;

    display: flex;

    align-items: center;

    justify-content: center;

    font-size: 22px;

    color: #fff;

}

.dashboard-stat-card h3 {

    font-size: 28px;

    font-weight: 700;

    margin: 15px 0 5px;
}

.dashboard-stat-card p {

    margin: 0;

    color: #6b7280;

    font-size: 14px;

    font-weight: 500;
}

.bg-blue {

    background: linear-gradient(135deg,#2563eb,#1d4ed8);
}

.bg-green {

    background: linear-gradient(135deg,#10b981,#059669);
}

.bg-orange {

    background: linear-gradient(135deg,#f59e0b,#d97706);
}

.bg-red {

    background: linear-gradient(135deg,#ef4444,#dc2626);
}

.bg-purple {

    background: linear-gradient(135deg,#8b5cf6,#7c3aed);
}

.bg-dark {

    background: linear-gradient(135deg,#374151,#111827);
}

.quick-card {

    background: #fff;

    border-radius: 18px;

    padding: 25px 15px;

    text-align: center;

    box-shadow: 0 4px 18px rgba(0,0,0,0.05);

    transition: 0.25s ease;

    color: #111827;

    display: block;
}

.quick-card:hover {

    transform: translateY(-4px);

    text-decoration: none;

    color: #2563eb;
}

.quick-card i {

    font-size: 30px;

    margin-bottom: 14px;
}

.feed-item {

    padding: 14px 16px;

    border-left: 4px solid #2563eb;

    background: #f8fafc;

    border-radius: 12px;

    margin-bottom: 12px;
}

.feed-item small {

    color: #6b7280;
}

.modern-card {

    border: none;

    border-radius: 18px;

    overflow: hidden;

    box-shadow: 0 4px 18px rgba(0,0,0,0.05);
}

.modern-card .card-header {

    background: #fff;

    border-bottom: 1px solid #eef2f7;

    padding: 18px 22px;
}

.modern-card .card-title {

    font-weight: 700;

    margin: 0;
}

canvas {

    min-height: 320px;
}

.card-body canvas {

    height: 320px !important;
}



</style>


<?php require_once __DIR__ . '/include/footer.php'; ?>