<?php
/**
 * Parent Portal - Fee Payment
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/database.php';

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();

}

// Check if user is logged in as parent
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'parent') {
    header('Location: ../parent_login.php');
    exit;
}

// Get parent information
$stmt = $pdo->prepare("SELECT * FROM parents WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$parent = $stmt->fetch();

if (!$parent) {
    header('Location: ../parent_register.php');
    exit;
}

// Get associated students
try {
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE s.id IN (
            SELECT student_id FROM parent_students WHERE parent_id = ?
        ) AND s.status = 'active'
    ");
    $stmt->execute([$parent['id']]);
    $students = $stmt->fetchAll();
} catch (Exception $e) {
    $students = [];
}

// Get selected student
$selected_student_id = $_GET['student_id'] ?? ($students[0]['id'] ?? null);

// Get pending fees for selected student
$pending_fees = [];
if ($selected_student_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT * FROM fees 
            WHERE student_id = ? AND status IN ('pending', 'overdue')
            ORDER BY due_date
        ");
        $stmt->execute([$selected_student_id]);
        $pending_fees = $stmt->fetchAll();
    } catch (Exception $e) {
        $pending_fees = [];
    }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pay_fee'])) {
    $fee_id = $_POST['fee_id'];
    $amount_paid = floatval($_POST['amount_paid']);
    $payment_method = $_POST['payment_method'];
    $receipt_number = $_POST['receipt_number'];
    $transaction_id = $_POST['transaction_id'] ?? '';
    
    try {
        $pdo->beginTransaction();
        
        // Verify fee belongs to student
        $stmt = $pdo->prepare("SELECT * FROM fees WHERE id = ? AND student_id = ?");
        $stmt->execute([$fee_id, $selected_student_id]);
        $fee = $stmt->fetch();
        
        if (!$fee) {
            throw new Exception('অবৈধ ফি অথবা পেমেন্টের তথ্য!');
        }
        
        if ($amount_paid > ($fee['amount'] - $fee['paid_amount'])) {
            throw new Exception('পরিশোধিত টাকার পরিমান অতিরিক্ত হয়েছে!');
        }
        
        // Update fee payment
        $new_paid_amount = $fee['paid_amount'] + $amount_paid;
        $new_status = $new_paid_amount >= $fee['amount'] ? 'paid' : 'partial';
        
        $stmt = $pdo->prepare("
            UPDATE fees 
            SET paid_amount = ?, status = ?, updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$new_paid_amount, $new_status, $fee_id]);
        
        // Create payment record
        $stmt = $pdo->prepare("
            INSERT INTO fee_payments (fee_id, student_id, amount, payment_method, receipt_number, transaction_id, parent_id, payment_date)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$fee_id, $selected_student_id, $amount_paid, $payment_method, $receipt_number, $transaction_id, $parent['id']]);
        
        $pdo->commit();
        $payment_success = true;
        
        // Refresh pending fees
        $stmt = $pdo->prepare("
            SELECT * FROM fees 
            WHERE student_id = ? AND status IN ('pending', 'overdue')
            ORDER BY due_date
        ");
        $stmt->execute([$selected_student_id]);
        $pending_fees = $stmt->fetchAll();
        
    } catch (Exception $e) {
        $pdo->rollback();
        $payment_error = $e->getMessage();
    }
}

// Calculate total pending amount
$total_pending = array_sum(array_map(function($fee) {
    return $fee['amount'] - $fee['paid_amount'];
}, $pending_fees));
?>

<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .parent-sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .parent-sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 15px 20px;
            border-radius: 8px;
            margin: 5px 0;
            text-decoration: none;
            display: block;
        }
        .parent-sidebar .nav-link:hover, .parent-sidebar .nav-link.active {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .fee-card {
            border-left: 4px solid #28a745;
        }
        .payment-form {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }
        .receipt-input {
            background: #fff3cd;
            border: 2px dashed #ffc107;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Parent Sidebar -->
            <nav class="col-md-2 d-none d-md-block parent-sidebar p-3">
                <div class="text-center mb-4">
                    <div class="bg-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width:80px;height:80px;">
                        <i class="fas fa-user-tie fa-2x text-primary"></i>
                    </div>
                    <h6 class="mb-0"><?= htmlspecialchars($parent['father_name']) ?></h6>
                    <small>অভিভাবক</small>
                </div>
                
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-home me-2"></i> ড্যাশবোর্ড
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="results.php">
                            <i class="fas fa-chart-line me-2"></i> ফলাফল
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="subjects.php">
                            <i class="fas fa-book me-2"></i> বিষয়সমূহ
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="fees.php">
                            <i class="fas fa-money-bill-wave me-2"></i> ফি পেমেন্ট
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="events.php">
                            <i class="fas fa-calendar-alt me-2"></i> ইভেন্ট
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="attendance.php">
                            <i class="fas fa-clipboard-check me-2"></i> উপস্থিতি
                        </a>
                    </li>
                    <li class="nav-item mt-4">
                        <a class="nav-link text-warning" href="../parent_logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> লগআউট
                        </a>
                    </li>
                </ul>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-10 ms-sm-auto px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-money-bill-wave text-success"></i> ফি পেমেন্ট</h2>
                    <div class="text-muted">
                        <?= date('l, d F Y', strtotime('now')) ?>
                    </div>
                </div>
                
                <?php if ($payment_success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> পেমেন্ট সফলভাবে সম্পন্ন হয়েছে!
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if ($payment_error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($payment_error) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if (count($students) > 0): ?>
                <!-- Student Selection -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-filter"></i> শিক্ষার্থী নির্বাচন করুন</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET">
                            <div class="row">
                                <div class="col-md-6">
                                    <select name="student_id" class="form-select" onchange="this.form.submit()">
                                        <?php foreach ($students as $student): ?>
                                            <option value="<?= $student['id'] ?>" <?= $selected_student_id == $student['id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> - 
                                                <?= htmlspecialchars($student['class_name'] ?? 'N/A') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($selected_student_id): ?>
                <div class="row">
                    <!-- Pending Fees -->
                    <div class="col-md-7">
                        <div class="card">
                            <div class="card-header bg-danger text-white">
                                <h5 class="mb-0"><i class="fas fa-exclamation-circle"></i> বকেয়া ফি</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($pending_fees) > 0): ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ফির ধরন</th>
                                                <th>পরিমান</th>
                                                <th>বকেয়া</th>
                                                <th>শেষ তারিখ</th>
                                                <th>অ্যাকশন</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($pending_fees as $fee): 
                                                $due_amount = $fee['amount'] - $fee['paid_amount'];
                                                $is_overdue = strtotime($fee['due_date']) < time();
                                            ?>
                                            <tr class="<?= $is_overdue ? 'table-danger' : '' ?>">
                                                <td>
                                                    <strong><?= htmlspecialchars($fee['fee_type']) ?></strong><br>
                                                    <small class="text-muted"><?= htmlspecialchars($fee['description'] ?? '') ?></small>
                                                </td>
                                                <td>৳<?= number_format($fee['amount'], 2) ?></td>
                                                <td>
                                                    <span class="badge bg-<?= $is_overdue ? 'danger' : 'warning' ?>">
                                                        ৳<?= number_format($due_amount, 2) ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?= date('d-m-Y', strtotime($fee['due_date'])) ?>
                                                    <?php if ($is_overdue): ?>
                                                    <br><span class="badge bg-danger">ওভারডিউ</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#paymentModal<?= $fee['id'] ?>">
                                                        <i class="fas fa-credit-card"></i> পেমেন্ট
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                                    <h5 class="text-success">কোনো বকেয়া ফি নেই!</h5>
                                    <p class="text-muted">সব ফি পরিশোধিত হয়েছে।</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Summary -->
                    <div class="col-md-5">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0"><i class="fas fa-chart-pie"></i> পেমেন্ট সারাংশ</h5>
                            </div>
                            <div class="card-body">
                                <div class="text-center mb-4">
                                    <h2 class="text-<?= $total_pending > 0 ? 'danger' : 'success' ?>">
                                        ৳<?= number_format($total_pending, 2) ?>
                                    </h2>
                                    <p class="text-muted">মোট বকেয়া</p>
                                </div>
                                
                                <div class="row text-center">
                                    <div class="col-6">
                                        <h4 class="text-primary"><?= count($pending_fees) ?></h4>
                                        <p class="text-muted small">বকেয়া আইটেম</p>
                                    </div>
                                    <div class="col-6">
                                        <h4 class="text-success">
                                            <?php 
                                                $paid_fees = array_filter($pending_fees, function($fee) {
                                                    return $fee['status'] == 'paid';
                                                });
                                                echo count($paid_fees);
                                            ?>
                                        </h4>
                                        <p class="text-muted small">পরিশোধিত</p>
                                    </div>
                                </div>
                                
                                <hr>
                                
                                <h6 class="text-center mb-3"><i class="fas fa-info-circle"></i> পেমেন্ট নির্দেশনা</h6>
                                <ul class="small text-muted">
                                    <li>রশিদ নম্বর অবশ্যই প্রয়োজন</li>
                                    <li>পেমেন্ট করার পর তথ্য আপডেট হতে ২৪ ঘন্টা লাগতে পারে</li>
                                    <li>কোনো সমস্যা হলে স্কুল অফিসে যোগাযোগ করুন</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Payment Modals -->
                <?php foreach ($pending_fees as $fee): 
                    $due_amount = $fee['amount'] - $fee['paid_amount'];
                ?>
                <div class="modal fade" id="paymentModal<?= $fee['id'] ?>" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-primary text-white">
                                <h5 class="modal-title"><i class="fas fa-credit-card"></i> ফি পেমেন্ট</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                            </div>
                            <form method="POST">
                                <div class="modal-body">
                                    <input type="hidden" name="fee_id" value="<?= $fee['id'] ?>">
                                    <input type="hidden" name="pay_fee" value="1">
                                    
                                    <div class="mb-3">
                                        <label class="form-label">ফির ধরন</label>
                                        <input type="text" class="form-control" value="<?= htmlspecialchars($fee['fee_type']) ?>" readonly>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">মোট পরিমান</label>
                                            <input type="text" class="form-control" value="৳<?= number_format($fee['amount'], 2) ?>" readonly>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">বকেয়া পরিমান</label>
                                            <input type="text" class="form-control" value="৳<?= number_format($due_amount, 2) ?>" readonly>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">পরিশোধিত টাকার পরিমান <span class="text-danger">*</span></label>
                                        <input type="number" name="amount_paid" class="form-control" step="0.01" min="1" max="<?= $due_amount ?>" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">পেমেন্ট মেথড <span class="text-danger">*</span></label>
                                        <select name="payment_method" class="form-select" required>
                                            <option value="">নির্বাচন করুন</option>
                                            <option value="cash">নগদ</option>
                                            <option value="bank">ব্যাংক</option>
                                            <option value="mobile">মোবাইল ব্যাংকিং</option>
                                            <option value="bkash">বিকাশ</option>
                                            <option value="nagad">নগদ</option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">রশিদ নম্বর <span class="text-danger">*</span></label>
                                        <input type="text" name="receipt_number" class="form-control receipt-input" placeholder="রশিদ নম্বর লিখুন" required>
                                        <div class="form-text">পেমেন্টের রশিদ নম্বর অবশ্যই প্রয়োজন</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">ট্রানজেকশন আইডি (যদি থাকে)</label>
                                        <input type="text" name="transaction_id" class="form-control" placeholder="ট্রানজেকশন আইডি">
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-check"></i> পেমেন্ট করুন
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php endif; ?>
                
                <?php else: ?>
                <div class="alert alert-info">
                    <h5><i class="fas fa-info-circle"></i> কোনো শিক্ষার্থী খুঁজে পাওয়া যায়নি</h5>
                    <p>সিস্টেমে আপনার শিক্ষার্থীর একাউন্ট অ্যাকটিভ করতে স্কুল অফিসে যোগাযোগ করুন।</p>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>