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

// Check if user is logged in
if (!isset($_SESSION['student_logged_in']) || $_SESSION['student_logged_in'] !== true) {
    header('Location: student_login.php');
    exit();
}

$application_no = $_SESSION['student_application_no'];
$application_id = $_SESSION['student_application_id'];

// Get application details
$stmt = $pdo->prepare("SELECT * FROM admission_applications WHERE application_no = ?");
$stmt->execute([$application_no]);
$application = $stmt->fetch();

if (!$application) {
    header('Location: student_login.php');
    exit();
}

// Get outstanding fees for this application
$outstanding_fees = [];

// First, try to find if this application has been converted to a student record
$stmt = $pdo->prepare("SELECT id FROM students WHERE phone = ? AND first_name = ? AND last_name = ? LIMIT 1");
$stmt->execute([$application['phone'], $application['first_name'], $application['last_name']]);
$student = $stmt->fetch();

if ($student) {
    $student_id = $student['id'];
    
    // Fetch outstanding fees for this student
    $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND (status = 'pending' OR status = 'partial') ORDER BY due_date ASC");
    $stmt->execute([$student_id]);
    $outstanding_fees = $stmt->fetchAll();
} else {
    // If student not found in students table, try to match by application number or other identifiers
    // For admission applications, fees might be associated directly with the application
    // or we can try to match based on the application number if it's stored in fees table
    // This is a fallback for when the student is not yet converted to a full student record
    
    // For now, we'll check if there are any fees associated with this phone number
    // by checking the students table for records with this phone
    $stmt = $pdo->prepare("SELECT id FROM students WHERE phone = ? LIMIT 1");
    $stmt->execute([$application['phone']]);
    $possible_students = $stmt->fetchAll();
    
    foreach ($possible_students as $possible_student) {
        $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND (status = 'pending' OR status = 'partial') ORDER BY due_date ASC");
        $stmt->execute([$possible_student['id']]);
        $fees = $stmt->fetchAll();
        
        if (!empty($fees)) {
            $outstanding_fees = $fees;
            break;
        }
    }
}

// Handle payment submission
$payment_success = false;
$payment_error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_fee'])) {
    $fee_id = (int)$_POST['fee_id'];
    
    // Validate that the fee belongs to the logged-in student
    $fee_valid = false;
    foreach ($outstanding_fees as $fee) {
        if ($fee['id'] == $fee_id) {
            $fee_valid = true;
            break;
        }
    }
    
    if ($fee_valid) {
        // Update fee status to paid
        $stmt = $pdo->prepare("UPDATE fees SET status = 'paid', paid_date = NOW(), paid_amount = amount WHERE id = ?");
        $result = $stmt->execute([$fee_id]);
        
        if ($result) {
            // Check if all fees for this student are now paid
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM fees WHERE student_id = ? AND (status = 'pending' OR status = 'partial')");
            $stmt->execute([$student_id]);
            $remaining_fees = $stmt->fetchColumn();
            
            if ($remaining_fees == 0) {
                // Update application status to approved
                $stmt = $pdo->prepare("UPDATE admission_applications SET status = 'approved', approved_at = NOW() WHERE id = ?");
                $stmt->execute([$application_id]);
                
                $payment_success = true;
            }
        } else {
            $payment_error = 'পেমেন্ট প্রক্রিয়াকরণে সমস্যা হয়েছে।';
        }
    } else {
        $payment_error = 'অবৈধ ফি নির্বাচন।';
    }
}
?>

<!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;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: #f5f7fa;
        }
        
        .dashboard-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
        }
        
        .dashboard-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,103,71,0.15);
            border: 1px solid #e0e0e0;
            margin-bottom: 2rem;
        }
        
        .status-badge {
            font-size: 1rem;
            padding: 0.5em 1em;
        }
        
        .fee-card {
            border-left: 4px solid #006747;
            margin-bottom: 1rem;
        }
        
        .fee-card.overdue {
            border-left-color: #dc3545;
        }
        
        .fee-card.partial {
            border-left-color: #ffc107;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="dashboard-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1><i class="fas fa-user-graduate"></i> শিক্ষার্থী ড্যাশবোর্ড</h1>
                    <p class="mb-0">স্বাগতম, <?php echo htmlspecialchars($_SESSION['student_name']); ?></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <a href="logout.php" class="btn btn-light">
                        <i class="fas fa-sign-out-alt"></i> লগআউট
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if ($payment_success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> পেমেন্ট সফল! আপনার আবেদন এখন অনুমোদিত।
            </div>
        <?php endif; ?>
        
        <?php if ($payment_error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $payment_error; ?>
            </div>
        <?php endif; ?>

        <!-- Application Information -->
        <div class="dashboard-card">
            <div class="card-body p-4">
                <div class="row mb-4">
                    <div class="col-md-8">
                        <h3><i class="fas fa-file-alt"></i> আবেদন তথ্য</h3>
                        <p>আবেদন নং: <strong><?php echo htmlspecialchars($application['application_no']); ?></strong></p>
                        <p>আবেদনের তারিখ: <?php echo date('d/m/Y H:i', strtotime($application['created_at'])); ?></p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <span class="badge bg-
                            <?php 
                                if ($application['status'] == 'pending') echo 'warning'; 
                                elseif ($application['status'] == 'approved') echo 'success'; 
                                elseif ($application['status'] == 'rejected') echo 'danger'; 
                                else echo 'secondary'; 
                            ?>
                            status-badge">
                            <?php 
                                if ($application['status'] == 'pending') echo 'মুলতুবি'; 
                                elseif ($application['status'] == 'approved') echo 'অনুমোদিত'; 
                                elseif ($application['status'] == 'rejected') echo 'প্রত্যাখ্যাত'; 
                                else echo 'বাতিল'; 
                            ?>
                        </span>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>নাম:</strong> <?php echo htmlspecialchars($application['first_name'] . ' ' . $application['last_name']); ?>
                        </div>
                        <div class="mb-2">
                            <strong>পিতার নাম:</strong> <?php echo htmlspecialchars($application['father_name']); ?>
                        </div>
                        <div class="mb-2">
                            <strong>মাতার নাম:</strong> <?php echo htmlspecialchars($application['mother_name']); ?>
                        </div>
                        <div class="mb-2">
                            <strong>ফোন:</strong> <?php echo htmlspecialchars($application['phone']); ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>আবেদনকৃত ক্লাস:</strong> <?php echo htmlspecialchars($application['class_name'] . ($application['section'] ? ' - ' . $application['section'] : '')); ?>
                        </div>
                        <div class="mb-2">
                            <strong>ধর্ম:</strong> 
                            <?php 
                                switch($application['religion']) {
                                    case 'islam': echo 'ইসলাম'; break;
                                    case 'hinduism': echo 'হিন্দু'; break;
                                    case 'buddhism': echo 'বৌদ্ধ'; break;
                                    case 'christianity': echo 'খ্রিস্টান'; break;
                                    case 'other': echo 'অন্যান্য'; break;
                                    default: echo 'N/A';
                                }
                            ?>
                        </div>
                        <div class="mb-2">
                            <strong>ইমেইল:</strong> <?php echo htmlspecialchars($application['email'] ?? 'N/A'); ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Outstanding Fees Section -->
        <div class="dashboard-card">
            <div class="card-body p-4">
                <h3><i class="fas fa-money-bill-wave"></i> বকেয়া ফি তথ্য</h3>
                
                <?php if (!empty($outstanding_fees) && is_array($outstanding_fees)): ?>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="table-success">
                                <tr>
                                    <th>ক্রমিক</th>
                                    <th>ফি ধরন</th>
                                    <th>মোট পরিমান</th>
                                    <th>জমা দেওয়া হয়েছে</th>
                                    <th>বকেয়া রয়েছে</th>
                                    <th>অবস্থা</th>
                                    <th>পরিশোধের তারিখ</th>
                                    <th>কার্যক্রম</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $counter = 1; ?>
                                <?php foreach ($outstanding_fees as $fee): ?>
                                <?php 
                                    $due_amount = $fee['amount'] - $fee['paid_amount'];
                                ?>
                                <tr class="
                                    <?php 
                                        if (strtotime($fee['due_date']) < time() && $fee['status'] !== 'paid') echo 'table-danger'; 
                                        elseif ($fee['status'] == 'partial') echo 'table-warning';
                                    ?>
                                ">
                                    <td><?php echo $counter++; ?></td>
                                    <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                    <td><?php echo number_format($fee['amount'], 2); ?> টাকা</td>
                                    <td><?php echo number_format($fee['paid_amount'], 2); ?> টাকা</td>
                                    <td class="text-danger fw-bold"><?php echo number_format($due_amount, 2); ?> টাকা</td>
                                    <td>
                                        <span class="badge bg-
                                            <?php 
                                                if ($fee['status'] == 'paid') echo 'success'; 
                                                elseif ($fee['status'] == 'partial') echo 'warning'; 
                                                else echo 'danger'; 
                                            ?>
                                        ">
                                            <?php 
                                                if ($fee['status'] == 'paid') echo 'পরিশোধিত'; 
                                                elseif ($fee['status'] == 'partial') echo 'আংশিক পরিশোধ'; 
                                                else echo 'বকেয়া'; 
                                            ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('d/m/Y', strtotime($fee['due_date'])); ?></td>
                                    <td>
                                        <form method="POST" action="" style="display: inline;">
                                            <input type="hidden" name="fee_id" value="<?php echo $fee['id']; ?>">
                                            <input type="hidden" name="pay_fee" value="1">
                                            <button type="submit" class="btn btn-sm btn-success" 
                                                onclick="return confirm('আপনি কি নিশ্চিত যে আপনি এই ফি পরিশোধ করতে চান?')">
                                                <i class="fas fa-credit-card"></i> পরিশোধ করুন
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="alert alert-info mt-3">
                        <h5><i class="fas fa-info-circle"></i> ব্যাংকে জমা দেয়ার নির্দেশনা:</h5>
                        <ol>
                            <li>উপরের বকেয়া ফি টাকা ব্যাংকে জমা দিন</li>
                            <li>ব্যাংক রসিদে আপনার নাম, শ্রেণি ও ফোন নম্বর উল্লেখ করুন</li>
                            <li>ব্যাংক জমার পর রসিদ সংরক্ষণ করুন</li>
                            <li>এখানে পরিশোধ করুন বাটনে ক্লিক করুন</li>
                        </ol>
                    </div>
                <?php else: ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i> আপনার কোনো বকেয়া ফি নেই। সমস্ত ফি পরিশোধিত!
                    </div>
                    
                    <?php if ($application['status'] == 'pending'): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> আপনার আবেদন এখনো মুলতুবি রয়েছে। ফি পরিশোধের পর এটি অনুমোদিত হবে।
                        </div>
                    <?php elseif ($application['status'] == 'approved'): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> আপনার আবেদন অনুমোদিত হয়েছে! ধন্যবাদ।
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Auto-refresh if application status changes to approved
        <?php if ($application['status'] == 'pending' && empty($outstanding_fees)): ?>
            setTimeout(function() {
                location.reload();
            }, 2000);
        <?php endif; ?>
    </script>
</body>
</html>