<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin = $_SESSION['email'];
$userrole = $_SESSION['role'];

if (!isset($_SESSION['email']) || $userrole != "Finance") {
    header("location:../index.php");
    exit();
}

// Get student ID from URL
$studentid = isset($_GET['studentid']) ? mysqli_real_escape_string($conn, $_GET['studentid']) : '';

if (empty($studentid)) {
    header("location: student_balance_report.php");
    exit();
}

// Handle payment deletion
if (isset($_POST['delete_payment'])) {
    $delete_id = mysqli_real_escape_string($conn, $_POST['delete_id']);
    
    // Delete the payment record
    $delete_query = mysqli_query($conn, "DELETE FROM payments WHERE id = '$delete_id'");
    
    if ($delete_query) {
        $_SESSION['message'] = "Payment record deleted successfully!";
        $_SESSION['message_type'] = "success";
    } else {
        $_SESSION['message'] = "Error deleting payment record: " . mysqli_error($conn);
        $_SESSION['message_type'] = "danger";
    }
    
    // Redirect to same page to avoid form resubmission
    header("location: student_payment_record.php?studentid=$studentid");
    exit();
}

// Handle payment update
if (isset($_POST['update_payment'])) {
    $update_id = mysqli_real_escape_string($conn, $_POST['update_id']);
    $payid = mysqli_real_escape_string($conn, $_POST['payid']);
    $fee_type = mysqli_real_escape_string($conn, $_POST['fee_type']);
    $year = mysqli_real_escape_string($conn, $_POST['year']);
    $period = mysqli_real_escape_string($conn, $_POST['period']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $intake = mysqli_real_escape_string($conn, $_POST['intake']);
    $mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $paidday = mysqli_real_escape_string($conn, $_POST['paidday']);
    
    // Update the payment record with correct field names
    $update_query = mysqli_query($conn, "UPDATE payments SET 
        payid = '$payid',
        fee_type = '$fee_type',
        studentid = '$studentid',
        amount = '$amount',
        intake = '$intake',
        mobile = '$mobile',
        year = '$year',
        status = '$status',
        paidday = '$paidday',
        period = '$period'
        WHERE id = '$update_id'");
    
    if ($update_query) {
        $_SESSION['message'] = "Payment record updated successfully!";
        $_SESSION['message_type'] = "success";
    } else {
        $_SESSION['message'] = "Error updating payment record: " . mysqli_error($conn);
        $_SESSION['message_type'] = "danger";
    }
    
    // Redirect to same page to avoid form resubmission
    header("location: student_payment_record.php?studentid=$studentid");
    exit();
}

// Get student details
$student_query = mysqli_query($conn, "SELECT * FROM students WHERE studentid = '$studentid'");
if (!$student_query) {
    die("Error fetching student: " . mysqli_error($conn));
}

$student = mysqli_fetch_assoc($student_query);

if (!$student) {
    echo "Student not found!";
    exit();
}

// Calculate total fees
$total_fees = 0;
$fees_query = mysqli_query($conn, "SHOW TABLES LIKE 'balances'");
if (mysqli_num_rows($fees_query) > 0) {
    $fees_query = mysqli_query($conn, "SELECT SUM(amount) as total_fees FROM balances WHERE program = '{$student['program']}' AND intake = '{$student['intake']}'");
    if ($fees_query) {
        $fees_data = mysqli_fetch_assoc($fees_query);
        $total_fees = $fees_data['total_fees'] ?? 0;
    }
} else {
    $fees_query = mysqli_query($conn, "SHOW TABLES LIKE 'fees'");
    if (mysqli_num_rows($fees_query) > 0) {
        $fees_query = mysqli_query($conn, "SELECT SUM(amount) as total_fees FROM fees WHERE program = '{$student['program']}' AND intake = '{$student['intake']}'");
        if ($fees_query) {
            $fees_data = mysqli_fetch_assoc($fees_query);
            $total_fees = $fees_data['total_fees'] ?? 0;
        }
    } else {
        $total_fees = 0;
    }
}

// Get payment history
$payments_query = mysqli_query($conn, "SELECT * FROM payments WHERE studentid = '$studentid' ORDER BY paidday DESC");
if (!$payments_query) {
    $payments_query = mysqli_query($conn, "SELECT * FROM payments WHERE studentid = '$studentid' ORDER BY id DESC");
}

$total_paid = 0;
$payments = [];

if ($payments_query) {
    while ($payment = mysqli_fetch_assoc($payments_query)) {
        $payments[] = $payment;
        $total_paid += $payment['amount'] ?? 0;
    }
}

$balance_owing = $total_fees - $total_paid;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Record - <?php echo $student['studentname']; ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background: #f8f9fa;
        }
        .content {
            margin-left: 200px;
            padding: 20px;
        }
        .student-header {
            background: #17a2b8;
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .summary-cards {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        .summary-card {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .summary-card h3 {
            margin: 0;
            font-size: 24px;
            font-weight: bold;
        }
        .payment-table {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .payment-table th {
            background: #343a40;
            color: white;
            padding: 15px;
        }
        .back-btn {
            background: #6c757d;
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            text-decoration: none;
            display: inline-block;
        }
        .back-btn:hover {
            background: #5a6268;
            color: white;
            text-decoration: none;
        }
        .debug-info {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            font-size: 14px;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        .modal-header {
            background: #17a2b8;
            color: white;
        }
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
            .summary-cards {
                flex-direction: column;
            }
            .action-buttons {
                flex-direction: column;
            }
        }
        @media print {
            .no-print, .action-buttons, .debug-info, .back-btn {
                display: none !important;
            }
            .content {
                margin-left: 0 !important;
            }
        }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <!-- Back Button -->
    <a href="student_balance_report.php" class="back-btn mb-3 no-print">
        <i class="fas fa-arrow-left me-2"></i> Back to Balance Report
    </a>

    <!-- Debug Information (remove in production) -->
    <div class="debug-info no-print">
        <strong>Debug Info:</strong> StudentID: <?php echo $studentid; ?> | 
        Program: <?php echo $student['program']; ?> | 
        Intake: <?php echo $student['intake']; ?>
    </div>

    <?php
    // Display session messages
    if (isset($_SESSION['message'])) {
        echo "<div class='alert alert-{$_SESSION['message_type']} text-center'>{$_SESSION['message']}</div>";
        unset($_SESSION['message']);
        unset($_SESSION['message_type']);
    }
    ?>

    <!-- Student Header -->
    <div class="student-header">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h2><i class="fas fa-user-graduate me-2"></i> <?php echo htmlspecialchars($student['studentname']); ?></h2>
                <p class="mb-0">
                    <strong>Student ID:</strong> <?php echo $student['studentid']; ?> | 
                    <strong>Program:</strong> <?php echo htmlspecialchars($student['program']); ?> | 
                    <strong>Intake:</strong> <?php echo htmlspecialchars($student['intake']); ?>
                </p>
            </div>
            <div class="col-md-4 text-end">
                <h4>Balance: <span style="color: <?php echo ($balance_owing > 0) ? '#ffebee' : '#e8f5e8'; ?>">
                    K<?php echo number_format($balance_owing, 2); ?>
                </span></h4>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="summary-cards">
        <div class="summary-card" style="border-top: 4px solid #17a2b8;">
            <h3 style="color: #17a2b8;">K<?php echo number_format($total_fees, 2); ?></h3>
            <p>Total Fees</p>
        </div>
        <div class="summary-card" style="border-top: 4px solid #28a745;">
            <h3 style="color: #28a745;">K<?php echo number_format($total_paid, 2); ?></h3>
            <p>Total Paid</p>
        </div>
        <div class="summary-card" style="border-top: 4px solid <?php echo ($balance_owing > 0) ? '#dc3545' : '#28a745'; ?>;">
            <h3 style="color: <?php echo ($balance_owing > 0) ? '#dc3545' : '#28a745'; ?>;">
                K<?php echo number_format($balance_owing, 2); ?>
            </h3>
            <p>Balance Owing</p>
        </div>
        <div class="summary-card" style="border-top: 4px solid #ffc107;">
            <h3 style="color: #ffc107;"><?php echo count($payments); ?></h3>
            <p>Payment Transactions</p>
        </div>
    </div>

    <!-- Payment History -->
    <div class="payment-table">
        <h4 class="p-3 mb-0 bg-dark border-bottom" style="color:white">
            <i class="fas fa-history me-2"></i> Payment History
        </h4>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>Receipt No</th>
                        <th>Fee Type</th>
                        <th>Amount</th>
                        <th>Intake</th>
                        <th>Year</th>
                        <th>Semester</th>
                        <th>Payment Date</th>
                        <th>Status</th>
                        <th class="no-print">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($payments) > 0): ?>
                        <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($payment['payid']); ?></strong></td>
                            <td><?php echo htmlspecialchars($payment['fee_type']); ?></td>
                            <td>
                                <strong class="text-success">
                                    K<?php echo number_format($payment['amount'], 2); ?>
                                </strong>
                            </td>
                            <td><?php echo htmlspecialchars($payment['intake']); ?></td>
                            <td><?php echo htmlspecialchars($payment['year']); ?></td>
                            <td><?php echo htmlspecialchars($payment['period']); ?></td>
                            <td><?php echo isset($payment['paidday']) ? date('M j, Y', strtotime($payment['paidday'])) : 'N/A'; ?></td>
                            <td>
                                <span class="badge bg-<?php echo ($payment['status'] == 'Paid') ? 'success' : 'warning'; ?>">
                                    <?php echo htmlspecialchars($payment['status']); ?>
                                </span>
                            </td>
                            <td class="no-print">
                                <div class="action-buttons">
                                    <!-- Edit Button -->
                                    <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $payment['id']; ?>">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    
                                    <!-- Delete Button with Confirmation -->
                                    <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $payment['id']; ?>">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </div>
                                
                                <!-- Edit Payment Modal -->
                                <div class="modal fade no-print" id="editModal<?php echo $payment['id']; ?>" tabindex="-1" aria-labelledby="editModalLabel<?php echo $payment['id']; ?>" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered">
                                        <div class="modal-content">
                                            <div class="modal-header bg-primary text-white">
                                                <h5 class="modal-title" id="editModalLabel<?php echo $payment['id']; ?>">
                                                    <i class="fas fa-edit me-2"></i>Edit Payment Record
                                                </h5>
                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <form method="POST" action="">
                                                <div class="modal-body">
                                                    <input type="hidden" name="update_id" value="<?php echo $payment['id']; ?>">
                                                    
                                                    <!-- First Row: Receipt No and Fee Type -->
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="payid<?php echo $payment['id']; ?>" class="form-label fw-bold">Receipt No</label>
                                                                <input type="text" class="form-control" id="payid<?php echo $payment['id']; ?>" 
                                                                       name="payid" value="<?php echo htmlspecialchars($payment['payid']); ?>" 
                                                                       placeholder="Enter receipt number" required>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="fee_type<?php echo $payment['id']; ?>" class="form-label fw-bold">Fee Type</label>
                                                                <select class="form-control" id="fee_type<?php echo $payment['id']; ?>" name="fee_type" required>
                                                                    <option value="Tuition" <?php echo ($payment['fee_type'] == 'Tuition') ? 'selected' : ''; ?>>Tuition</option>
                                                                    <option value="Registration" <?php echo ($payment['fee_type'] == 'Registration') ? 'selected' : ''; ?>>Registration</option>
                                                                    <option value="Examination" <?php echo ($payment['fee_type'] == 'Examination') ? 'selected' : ''; ?>>Examination</option>
                                                                    <option value="Other" <?php echo ($payment['fee_type'] == 'Other') ? 'selected' : ''; ?>>Other</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Second Row: Amount and Intake -->
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="amount<?php echo $payment['id']; ?>" class="form-label fw-bold">Amount (K)</label>
                                                                <input type="number" step="0.01" class="form-control" id="amount<?php echo $payment['id']; ?>" 
                                                                       name="amount" value="<?php echo $payment['amount']; ?>" 
                                                                       placeholder="0.00" min="0" required>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="intake<?php echo $payment['id']; ?>" class="form-label fw-bold">Intake</label>
                                                                <input type="text" class="form-control" id="intake<?php echo $payment['id']; ?>" 
                                                                       name="intake" value="<?php echo htmlspecialchars($payment['intake']); ?>" 
                                                                       placeholder="Enter intake" required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Third Row: Year and Semester -->
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="year<?php echo $payment['id']; ?>" class="form-label fw-bold">Year</label>
                                                                <input type="text" class="form-control" id="year<?php echo $payment['id']; ?>" 
                                                                       name="year" value="<?php echo htmlspecialchars($payment['year']); ?>" 
                                                                       placeholder="Enter year" required>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="period<?php echo $payment['id']; ?>" class="form-label fw-bold">Semester</label>
                                                                <select class="form-control" id="period<?php echo $payment['id']; ?>" name="period" required>
                                                                    <option value="1" <?php echo ($payment['period'] == '1') ? 'selected' : ''; ?>>Semester 1</option>
                                                                    <option value="2" <?php echo ($payment['period'] == '2') ? 'selected' : ''; ?>>Semester 2</option>
                                                                    <option value="3" <?php echo ($payment['period'] == '3') ? 'selected' : ''; ?>>Semester 3</option>
                                                                    <option value="Full Year" <?php echo ($payment['period'] == 'Full Year') ? 'selected' : ''; ?>>Full Year</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Fourth Row: Mobile and Payment Date -->
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="mobile<?php echo $payment['id']; ?>" class="form-label fw-bold">Mobile</label>
                                                                <input type="text" class="form-control" id="mobile<?php echo $payment['id']; ?>" 
                                                                       name="mobile" value="<?php echo htmlspecialchars($payment['mobile']); ?>" 
                                                                       placeholder="Enter mobile number">
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label for="paidday<?php echo $payment['id']; ?>" class="form-label fw-bold">Payment Date</label>
                                                                <input type="datetime-local" class="form-control" id="paidday<?php echo $payment['id']; ?>" 
                                                                       name="paidday" value="<?php echo isset($payment['paidday']) ? date('Y-m-d\TH:i', strtotime($payment['paidday'])) : ''; ?>" 
                                                                       required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Fifth Row: Status -->
                                                    <div class="row mb-3">
                                                        <div class="col-12">
                                                            <div class="form-group">
                                                                <label for="status<?php echo $payment['id']; ?>" class="form-label fw-bold">Status</label>
                                                                <select class="form-control" id="status<?php echo $payment['id']; ?>" name="status" required>
                                                                    <option value="Paid" <?php echo ($payment['status'] == 'Paid') ? 'selected' : ''; ?>>Paid</option>
                                                                    <option value="Pending" <?php echo ($payment['status'] == 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                                                    <option value="Cancelled" <?php echo ($payment['status'] == 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                                        <i class="fas fa-times me-1"></i> Cancel
                                                    </button>
                                                    <button type="submit" name="update_payment" class="btn btn-primary">
                                                        <i class="fas fa-save me-1"></i> Update Payment
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Delete Confirmation Modal -->
                                <div class="modal fade no-print" id="deleteModal<?php echo $payment['id']; ?>" tabindex="-1" aria-labelledby="deleteModalLabel<?php echo $payment['id']; ?>" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="deleteModalLabel<?php echo $payment['id']; ?>">Confirm Deletion</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <form method="POST" action="">
                                                <div class="modal-body">
                                                    <input type="hidden" name="delete_id" value="<?php echo $payment['id']; ?>">
                                                    <p>Are you sure you want to delete this payment record?</p>
                                                    <p><strong>Receipt No:</strong> <?php echo htmlspecialchars($payment['payid']); ?></p>
                                                    <p><strong>Amount:</strong> K<?php echo number_format($payment['amount'], 2); ?></p>
                                                    <p class="text-danger"><strong>This action cannot be undone.</strong></p>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                    <button type="submit" name="delete_payment" class="btn btn-danger">Delete Payment</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="text-center py-4 text-muted">
                                <i class="fas fa-receipt fa-2x mb-3"></i><br>
                                No payment records found for this student
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Print Button -->
    <div class="text-center mt-4 no-print">
        <button class="btn btn-primary" onclick="window.print()">
            <i class="fas fa-print me-2"></i> Print Payment Record
        </button>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Auto-hide alerts after 5 seconds
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                alert.style.display = 'none';
            });
        }, 5000);
    });
</script>
</body>
</html>