<?php
session_start();
require_once '../config/database.php';

// Clear session variable if requested (for testing)
if (isset($_GET['clear_session'])) {
    unset($_SESSION['fee_management_password_verified']);
}

// Function to get setting from admin settings table
function get_admin_setting($pdo, $key, $default = null) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        if ($row && !empty($row['setting_value'])) return $row['setting_value'];
    } catch (Exception $e) {
        // ignore
    }
    return $default;
}

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Check if fee management password is set and verify it
$fee_management_password_verified = false;
$fee_management_password_hash = get_admin_setting($pdo, 'fee_management_password');

// If no fee management password is set, allow access
if (empty($fee_management_password_hash)) {
    $fee_management_password_verified = true;
} else {
    // Check if password is already verified in session
    if (!empty($_SESSION['fee_management_password_verified']) && $_SESSION['fee_management_password_verified'] === true) {
        $fee_management_password_verified = true;
    } else if (!empty($_POST['fee_management_password'])) {
        if (password_verify($_POST['fee_management_password'], $fee_management_password_hash)) {
            $_SESSION['fee_management_password_verified'] = true;
            $fee_management_password_verified = true;
        }
    } else {
        // If fee management password is set but not verified, show password form
        $fee_management_password_verified = false;
    }
}

// If fee management password is required but not verified, show password form
if (!$fee_management_password_verified):
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ফি ব্যবস্থাপনা পাসওয়ার্ড</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/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">
        <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
        <style>
            body { 
                font-family: 'Hind Siliguri', sans-serif; 
                background-color: #f8f9fa; 
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                margin: 0;
                padding: 20px;
            }
            .password-container { 
                max-width: 400px; 
                width: 100%;
            }
            .card {
                border-radius: 15px;
                box-shadow: 0 0 30px rgba(0,0,0,0.1);
            }
        </style>
    </head>
    <body>
        <div class="password-container">
            <div class="card">
                <div class="card-header text-center bg-primary text-white">
                    <h4><i class="fas fa-lock"></i> ফি ব্যবস্থাপনা পাসওয়ার্ড</h4>
                </div>
                <div class="card-body">
                    <p class="text-center text-muted mb-4">এই মডিউলটি সুরক্ষিত। অ্যাক্সেসের জন্য পাসওয়ার্ড প্রয়োজন।</p>
                    
                    <?php if (isset($_GET['clear_session'])): ?>
                        <div class="alert alert-info">
                            সেশন মুছে ফেলা হয়েছে। ফি ব্যবস্থাপনা মডিউলে প্রবেশের জন্য পাসওয়ার্ড দিন।
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_POST['fee_management_password']) && !$fee_management_password_verified): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> পাসওয়ার্ড সঠিক নয়!
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label for="fee_management_password" class="form-label">পাসওয়ার্ড দিন</label>
                            <input type="password" class="form-control" id="fee_management_password" name="fee_management_password" required autofocus>
                            <div class="form-text">ফি ব্যবস্থাপনা মডিউলে প্রবেশের জন্য পাসওয়ার্ড প্রয়োজন</div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-unlock"></i> প্রবেশ করুন
                        </button>
                        
                        <div class="text-center mt-3">
                            <a href="../index.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                            </a>
                            <?php if (isset($_GET['clear_session'])): ?>
                                <a href="." class="btn btn-success ms-2">
                                    <i class="fas fa-redo"></i> রিফ্রেশ
                                </a>
                            <?php else: ?>
                                <a href="?clear_session=1" class="btn btn-warning ms-2">
                                    <i class="fas fa-trash"></i> সেশন মুছুন
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="text-center mt-4 text-muted">
                <small>© <?php echo date('Y'); ?> স্কুল ম্যানেজমেন্ট সিস্টেম</small>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit();
endif;

// If password is verified, show the fee management dashboard
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি ব্যবস্থাপনা ড্যাশবোর্ড</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/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">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root{--indigo:#4fc3f7;--pink:#e83e8c;--teal:#4dd0e1;--orange:#ffb74d}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 20px rgba(0,0,0,.4)}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none;display:flex;align-items:center;gap:8px}
        .top-bar .brand i{font-size:1.2rem}
        .top-bar .nav-links{display:flex;gap:12px}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.78rem;font-weight:500;padding:4px 10px;border-radius:6px;transition:.2s}
        .top-bar .nav-links a:hover{color:#fff;background:rgba(255,255,255,.08)}
        .page-header{padding:14px 0 6px}
        .page-header h4{font-weight:800;font-size:1.1rem;color:#4fc3f7;margin:0}
        .page-header p{font-size:.78rem;color:rgba(255,255,255,.5);margin:2px 0 0}
        .stat-row{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:14px}
        .stat-card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:10px 12px;display:flex;align-items:center;gap:10px}
        .stat-card .stat-icon{width:38px;height:38px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:1.1rem;flex-shrink:0}
        .stat-card .stat-info{flex:1}
        .stat-card .stat-info .num{font-size:1.05rem;font-weight:800;line-height:1.2;color:#fff}
        .stat-card .stat-info .lbl{font-size:.72rem;color:rgba(255,255,255,.5)}
        .section-title{font-size:.82rem;font-weight:700;color:#4fc3f7;margin:0 0 8px;display:flex;align-items:center;gap:6px}
        .section-title i{color:var(--indigo)}
        .action-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;margin-bottom:16px}
        .action-card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:10px 8px;text-align:center;text-decoration:none!important;transition:.2s}
        .action-card:hover{transform:translateY(-2px);box-shadow:0 6px 20px rgba(0,0,0,.3);border-color:rgba(79,195,247,.3)}
        .action-card .ac-icon{width:36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;margin:0 auto 5px;font-size:.95rem}
        .action-card .ac-title{font-size:.75rem;font-weight:700;color:#e0e0e0;line-height:1.2}
        .action-card .ac-desc{font-size:.68rem;color:rgba(255,255,255,.4);margin-top:1px}
        .module-section{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);border-radius:12px;padding:12px 14px;margin-bottom:14px}
        .module-section a{color:#90caf9}
        .module-section a:hover{color:#4fc3f7}
        .badge-mod{font-size:.65rem;padding:2px 8px;border-radius:10px;font-weight:600}
        .module-section .text-muted{color:rgba(255,255,255,.5)!important}
        .module-section h6,.module-section strong{color:#e0e0e0}
        @media(max-width:768px){
            .stat-row{grid-template-columns:repeat(2,1fr)}
            .action-grid{grid-template-columns:repeat(3,1fr)}
        }
    </style>
</head>
<body>
    <?php
    // Get some basic stats for the dashboard
    $total_collections = 0; $total_students_with_fees = 0; $pending_count = 0;
    try {
        $r1 = $pdo->query("SELECT COUNT(DISTINCT student_id) as c FROM fee_collections");
        $total_students_with_fees = $r1->fetch()['c'] ?? 0;
        $r2 = $pdo->query("SELECT COALESCE(SUM(paid_amount),0) as tot FROM fee_collections");
        $total_collections = $r2->fetch()['tot'] ?? 0;
        $r3 = $pdo->query("SELECT COUNT(*) as c FROM students WHERE status='active'");
        $total_active = $r3->fetch()['c'] ?? 0;
        $pending_count = max(0, $total_active - $total_students_with_fees);
    } catch (Exception $e) {}
    ?>

    <div class="top-bar">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ</a>
            <a href="new_dashboard.php"><i class="fas fa-chart-pie"></i> ড্যাশবোর্ড</a>
            <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>

    <div class="container-fluid px-4">
        <div class="page-header">
            <h4><i class="fas fa-cog" style="color:var(--indigo);margin-right:6px"></i>ফি ব্যবস্থাপনা</h4>
            <p>ফি ব্যবস্থাপনা সম্পর্কিত সকল কার্যক্রম</p>
        </div>

        <div class="stat-row">
            <div class="stat-card">
                <div class="stat-icon" style="background:#e8f5e9;color:#2e7d32"><i class="fas fa-users"></i></div>
                <div class="stat-info"><div class="num"><?=$total_active?></div><div class="lbl">মোট শিক্ষার্থী</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:#e3f2fd;color:#1565c0"><i class="fas fa-check-circle"></i></div>
                <div class="stat-info"><div class="num"><?=$total_students_with_fees?></div><div class="lbl">ফি পরিশোধ করেছে</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:#fff3e0;color:#e65100"><i class="fas fa-hourglass-half"></i></div>
                <div class="stat-info"><div class="num"><?=$pending_count?></div><div class="lbl">বাকি আছে</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:#fce4ec;color:#c62828"><i class="fas fa-coins"></i></div>
                <div class="stat-info"><div class="num">৳<?=number_format($total_collections)?></div><div class="lbl">মোট আদায়</div></div>
            </div>
        </div>

        <div class="module-section">
            <div class="section-title"><i class="fas fa-bolt"></i> দ্রুত অ্যাকশন</div>
            <div class="action-grid">
                <a href="student_fees.php" class="action-card">
                    <div class="ac-icon" style="background:linear-gradient(135deg,#667eea,#764ba2);color:#fff"><i class="fas fa-money-bill-wave"></i></div>
                    <div class="ac-title">ফি সংগ্রহ</div>
                    <div class="ac-desc">শিক্ষার্থীদের ফি নিন</div>
                </a>
                <a href="collect.php" class="action-card">
                    <div class="ac-icon" style="background:linear-gradient(135deg,#f093fb,#f5576c);color:#fff"><i class="fas fa-cash-register"></i></div>
                    <div class="ac-title">দ্রুত কালেক্ট</div>
                    <div class="ac-desc">দ্রুত ফি সংগ্রহ</div>
                </a>
                <a href="new_dashboard.php" class="action-card">
                    <div class="ac-icon" style="background:linear-gradient(135deg,#4facfe,#00f2fe);color:#fff"><i class="fas fa-chart-pie"></i></div>
                    <div class="ac-title">ফি ড্যাশবোর্ড</div>
                    <div class="ac-desc">পরিসংখ্যান দেখুন</div>
                </a>
                <a href="reports.php" class="action-card">
                    <div class="ac-icon" style="background:linear-gradient(135deg,#43e97b,#38f9d7);color:#fff"><i class="fas fa-chart-bar"></i></div>
                    <div class="ac-title">ফি রিপোর্ট</div>
                    <div class="ac-desc">বিস্তারিত রিপোর্ট</div>
                </a>
                <a href="bill_submission.php" class="action-card">
                    <div class="ac-icon" style="background:linear-gradient(135deg,#fa709a,#fee140);color:#fff"><i class="fas fa-file-invoice"></i></div>
                    <div class="ac-title">বিল সাবমিশন</div>
                    <div class="ac-desc">বিল জমা দিন</div>
                </a>
                <a href="settings.php" class="action-card">
                    <div class="ac-icon" style="background:linear-gradient(135deg,#a18cd1,#fbc2eb);color:#fff"><i class="fas fa-cog"></i></div>
                    <div class="ac-title">সেটিংস</div>
                    <div class="ac-desc">কনফিগারেশন</div>
                </a>
            </div>
        </div>

        <div class="row g-2 mb-3">
            <div class="col-md-6">
                <div class="module-section h-100 mb-0">
                    <div class="section-title"><i class="fas fa-star"></i> গুরুত্বপূর্ণ লিংক</div>
                    <div class="d-flex flex-wrap gap-2">
                        <a href="student_fees.php" class="btn btn-sm" style="background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:.75rem"><i class="fas fa-money-bill-wave me-1"></i>ফি সংগ্রহ</a>
                        <a href="new_dashboard.php" class="btn btn-sm" style="background:linear-gradient(135deg,#4facfe,#00f2fe);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:.75rem"><i class="fas fa-chart-pie me-1"></i>ড্যাশবোর্ড</a>
                        <a href="reports.php" class="btn btn-sm" style="background:linear-gradient(135deg,#43e97b,#38f9d7);color:#1a1a2e;border:none;border-radius:8px;font-weight:600;font-size:.75rem"><i class="fas fa-chart-bar me-1"></i>রিপোর্ট</a>
                        <a href="collect.php" class="btn btn-sm" style="background:linear-gradient(135deg,#f093fb,#f5576c);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:.75rem"><i class="fas fa-cash-register me-1"></i>দ্রুত কালেক্ট</a>
                        <a href="bill_submission.php" class="btn btn-sm" style="background:linear-gradient(135deg,#fa709a,#fee140);color:#1a1a2e;border:none;border-radius:8px;font-weight:600;font-size:.75rem"><i class="fas fa-file-invoice me-1"></i>বিল সাবমিশন</a>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="module-section h-100 mb-0">
                    <div class="section-title"><i class="fas fa-info-circle"></i> তথ্য</div>
                    <p class="small text-muted mb-0" style="font-size:.75rem;line-height:1.5">
                        <i class="fas fa-check-circle text-success me-1"></i>মোট <strong><?=$total_active?></strong> জন শিক্ষার্থীর মধ্যে <strong><?=$total_students_with_fees?></strong> জন ফি পরিশোধ করেছে।<br>
                        <i class="fas fa-hourglass-half text-warning me-1"></i>আরও <strong><?=$pending_count?></strong> জন শিক্ষার্থীর ফি বাকি আছে।<br>
                        <i class="fas fa-coins text-danger me-1"></i>মোট আদায়কৃত ফি: <strong>৳<?=number_format($total_collections)?></strong>
                    </p>
                </div>
            </div>
        </div>
    </div>

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