<?php
session_start();
if (!isset($_SESSION['gym_id'])) {
    header("Location: login.php");
    exit();
}

require_once 'config/database.php';
$db = (new Database())->getConnection();
$gym_id = $_SESSION['gym_id'];

// Current gym کا data fetch کریں sidebar کے لیے
$gym_stmt = $db->prepare("SELECT name, owner_name FROM gyms WHERE id = ?");
$gym_stmt->execute([$gym_id]);
$current_gym = $gym_stmt->fetch(PDO::FETCH_ASSOC);

// Record payment
if ($_POST && isset($_POST['record_payment'])) {
    $member_id = $_POST['member_id'];
    $amount = $_POST['amount'];
    $payment_date = $_POST['payment_date'];
    $payment_method = $_POST['payment_method'];
    $transaction_id = trim($_POST['transaction_id']);
    $notes = trim($_POST['notes']);
    
    $query = "INSERT INTO payments (member_id, amount, payment_date, payment_method, transaction_id, notes, received_by, gym_id) 
              VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $db->prepare($query);
    
    if ($stmt->execute([$member_id, $amount, $payment_date, $payment_method, $transaction_id, $notes, $_SESSION['gym_id'], $gym_id])) {
        $_SESSION['success'] = 'Payment recorded successfully!';
        header("Location: payments.php");
        exit();
    } else {
        $_SESSION['error'] = 'Failed to record payment!';
        header("Location: payments.php");
        exit();
    }
}

// Get all payments - ONLY FOR CURRENT GYM
$query = "SELECT p.*, m.name as member_name, m.member_id as member_code, s.name as received_by_name 
          FROM payments p 
          JOIN members m ON p.member_id = m.id 
          LEFT JOIN staff s ON p.received_by = s.id 
          WHERE p.gym_id = ?
          ORDER BY p.created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute([$gym_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php include 'includes/navbar.php'; ?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="page-header">
            <h3 class="page-title">Payments Management</h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Payments</li>
                </ol>
            </nav>
        </div>

        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-12 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Payment History</h4>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Transaction ID</th>
                                        <th>Member</th>
                                        <th>Amount</th>
                                        <th>Payment Date</th>
                                        <th>Method</th>
                                        <th>Received By</th>
                                        <th>Notes</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($payments as $payment): ?>
                                    <tr>
                                        <td>
                                            <?php if ($payment['transaction_id']): ?>
                                                <span class="text-primary"><?php echo $payment['transaction_id']; ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">N/A</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="fw-semibold"><?php echo $payment['member_name']; ?></div>
                                            <small class="text-muted"><?php echo $payment['member_code']; ?></small>
                                        </td>
                                        <td class="text-success fw-bold">Rs. <?php echo number_format($payment['amount'], 2); ?></td>
                                        <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                        <td>
                                            <label class="badge badge-info">
                                                <?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'])); ?>
                                            </label>
                                        </td>
                                        <td><?php echo $payment['received_by_name']; ?></td>
                                        <td><?php echo $payment['notes'] ?: 'N/A'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($payments)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-muted py-4">
                                            <i class="mdi mdi-credit-card-off display-4 d-block mb-2"></i>
                                            No payments recorded yet.
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'includes/footer.php'; ?>
</div>