<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Get payment filters
$type_filter = $_GET['type'] ?? '';
$status_filter = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';

// Build query without admin join (since payments.admin_id column doesn't exist)
$sql = "SELECT p.*, pt.name as payment_type_name, 
        s.first_name as student_first_name, s.last_name as student_last_name,
        u.email as student_email
        FROM payments p
        JOIN payment_types pt ON p.payment_type_id = pt.id
        JOIN students s ON p.student_id = s.id
        JOIN users u ON s.id = u.id";

$conditions = [];
$params = [];

if ($type_filter) {
    $conditions[] = "p.payment_type_id = ?";
    $params[] = $type_filter;
}

if ($status_filter) {
    $conditions[] = "p.status = ?";
    $params[] = $status_filter;
}

if ($date_from) {
    $conditions[] = "p.payment_date >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $conditions[] = "p.payment_date <= ?";
    $params[] = $date_to;
}

if ($search) {
    $conditions[] = "(s.first_name LIKE ? OR s.last_name LIKE ? OR u.email LIKE ? OR pt.name LIKE ? OR p.reference_number LIKE ?)";
    for ($i = 0; $i < 5; $i++) {
        $params[] = "%$search%";
    }
}

if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY p.payment_date DESC, p.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$payments = $stmt->fetchAll();

// Get stats
$total_paid = $pdo->query("SELECT SUM(amount) FROM payments WHERE status = 'completed'")->fetchColumn() ?: 0;
$total_pending = $pdo->query("SELECT SUM(amount) FROM payments WHERE status = 'pending'")->fetchColumn() ?: 0;
$total_refunded = $pdo->query("SELECT SUM(amount) FROM payments WHERE status = 'refunded'")->fetchColumn() ?: 0;
$total_failed = $pdo->query("SELECT SUM(amount) FROM payments WHERE status = 'failed'")->fetchColumn() ?: 0;

// Get payment types for filter
$payment_types = $pdo->query("SELECT id, name FROM payment_types WHERE is_active = 1 ORDER BY name")->fetchAll();

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Payments - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-completed {
            background: #d4edda;
            color: #155724;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-refunded {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
        .payment-method {
            font-size: 0.9em;
            color: #6c757d;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Financial Management</h6>
        <h1 class="display-5">Manage Payments</h1>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Payments</h6>
                    <h3><?= count($payments) ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <h6>Completed</h6>
                    <h3>$<?= number_format($total_paid, 2) ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <h6>Pending</h6>
                    <h3>$<?= number_format($total_pending, 2) ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #17a2b8;">
                <div class="card-body">
                    <h6>Refunded</h6>
                    <h3>$<?= number_format($total_refunded, 2) ?></h3>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <h6>Failed</h6>
                    <h3>$<?= number_format($total_failed, 2) ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-9 mb-3">
            <div class="text-right">
                <a href="admin-create-payment.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-plus"></i> Record Payment
                </a>
            </div>
        </div>
    </div>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <input type="text" name="search" class="form-control" placeholder="Search by student, payment type, or reference number" 
                           value="<?= htmlspecialchars($search) ?>">
                </div>
                <button type="submit" class="btn btn-primary">Search</button>
            </form>
        </div>
        <div class="col-lg-4">
            <div class="row">
                <div class="col-md-6 mb-2">
                    <select name="type" class="form-control" onchange="window.location='admin-payments.php?type='+this.value<?= $status_filter ? '&status='.urlencode($status_filter) : '' ?><?= $date_from ? '&date_from='.urlencode($date_from) : '' ?><?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Types</option>
                        <?php foreach ($payment_types as $pt): ?>
                        <option value="<?= $pt['id'] ?>" <?= $type_filter == $pt['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($pt['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="status" class="form-control" onchange="window.location='admin-payments.php<?= $type_filter ? '&type='.urlencode($type_filter) : '' ?>&status='+this.value<?= $date_from ? '&date_from='.urlencode($date_from) : '' ?><?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Statuses</option>
                        <option value="completed" <?= $status_filter === 'completed' ? 'selected' : '' ?>>Completed</option>
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="refunded" <?= $status_filter === 'refunded' ? 'selected' : '' ?>>Refunded</option>
                        <option value="failed" <?= $status_filter === 'failed' ? 'selected' : '' ?>>Failed</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-6">
            <div class="form-group">
                <label>From Date</label>
                <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>" 
                       onchange="window.location='admin-payments.php<?= $type_filter ? '&type='.urlencode($type_filter) : '' ?><?= $status_filter ? '&status='.urlencode($status_filter) : '' ?>&date_from='+this.value<?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label>To Date</label>
                <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>" 
                       onchange="window.location='admin-payments.php<?= $type_filter ? '&type='.urlencode($type_filter) : '' ?><?= $status_filter ? '&status='.urlencode($status_filter) : '' ?><?= $date_from ? '&date_from='.urlencode($date_from) : '' ?>&date_to='+this.value<?= $search ? '&search='.urlencode($search) : '' ?>">
            </div>
        </div>
    </div>

    <!-- Payments List -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Student</th>
                    <th>Payment Type</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Reference</th>
                    <th>Processed By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($payments)): ?>
                <tr>
                    <td colspan="8" class="text-center">No payments found.</td>
                </tr>
                <?php else: ?>
                <?php foreach ($payments as $payment): ?>
                <tr>
                    <td>
                        <?= htmlspecialchars($payment['student_first_name'] . ' ' . $payment['student_last_name']) ?>
                        <br>
                        <small class="text-muted"><?= htmlspecialchars($payment['student_email']) ?></small>
                    </td>
                    <td><?= htmlspecialchars($payment['payment_type_name']) ?></td>
                    <td><strong>$<?= number_format($payment['amount'], 2) ?></strong></td>
                    <td>
                        <span class="status-badge status-<?= $payment['status'] ?>">
                            <?= ucfirst($payment['status']) ?>
                        </span>
                    </td>
                    <td><?= date('M j, Y', strtotime($payment['payment_date'])) ?></td>
                    <td><?= htmlspecialchars($payment['reference_number'] ?? 'N/A') ?></td>
                    <td>
                        <small class="text-muted">System</small>
                    </td>
                    <td>
                        <div class="btn-group">
                            <a href="admin-payment-details.php?id=<?= $payment['id'] ?>" class="btn btn-sm btn-primary">View</a>
                            <button class="btn btn-sm btn-danger delete-payment" data-id="<?= $payment['id'] ?>">Delete</button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    $('.delete-payment').on('click', function() {
        const paymentId = $(this).data('id');
        if (confirm('Are you sure you want to delete this payment? This action cannot be undone.')) {
            alert('In a real application, this would delete the payment from the database.');
        }
    });
</script>
</body>
</html>
