<?php
/**
 * User Payments
 * Manage payments for registered users (based on registration date)
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

initSecureSession();

if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

$current_user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';

// Determine which user's payments to show
$target_user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : $current_user_id;

// Access control
if($user_role == 'user' && $target_user_id != $current_user_id) {
    header('Location: dashboard?error=Access denied');
    exit;
}

if($user_role == 'broker') {
    // Broker can only view payments for their referred clients
    $access_check = $conn->prepare("SELECT id FROM users WHERE id = ? AND referred_by_broker = ?");
    $access_check->bind_param("ii", $target_user_id, $current_user_id);
    $access_check->execute();
    if($target_user_id != $current_user_id && $access_check->get_result()->num_rows == 0) {
        header('Location: dashboard?error=Access denied');
        exit;
    }
}

// Get target user info
$target_user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE id = $target_user_id"));
if(!$target_user) {
    header('Location: dashboard?error=User not found');
    exit;
}

$error = '';
$success = '';
$current_year = date('Y');

// Get payment settings
$settings_result = mysqli_query($conn, "SELECT setting_key, setting_value FROM payment_settings");
$settings = [];
while($s = mysqli_fetch_assoc($settings_result)) {
    $settings[$s['setting_key']] = $s['setting_value'];
}

// Determine fee based on user type
$user_type = $target_user['user_type'] ?? 'basic';
$basic_yearly_fee = $settings['yearly_fee'] ?? 50000;
$premium_yearly_fee = $settings['premium_yearly_fee'] ?? 100000;

// If user has custom premium amount, use that
if($user_type == 'premium' && !empty($target_user['premium_amount'])) {
    $yearly_fee = $target_user['premium_amount'];
} elseif($user_type == 'premium') {
    $yearly_fee = $premium_yearly_fee;
} else {
    $yearly_fee = $basic_yearly_fee;
}

// Calculate registration year for payment tracking
$registration_date = $target_user['subscription_start_date'] ?: date('Y-m-d', strtotime($target_user['created_at']));
$registration_year = date('Y', strtotime($registration_date));

// Handle payment actions (admin only)
if($_SERVER['REQUEST_METHOD'] == 'POST' && $user_role == 'admin') {
    $action = $_POST['action'] ?? '';

    if($action == 'add_payment') {
        $amount = floatval($_POST['amount']);
        $payment_year = intval($_POST['payment_year']);
        $payment_date = mysqli_real_escape_string($conn, $_POST['payment_date']);
        $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
        $reference_number = mysqli_real_escape_string($conn, trim($_POST['reference_number']));
        $notes = mysqli_real_escape_string($conn, trim($_POST['notes']));

        if($amount <= 0) {
            $error = 'Amount must be greater than zero';
        } elseif($payment_year < $registration_year || $payment_year > $current_year + 1) {
            $error = 'Invalid payment year';
        } else {
            $check = mysqli_query($conn, "SELECT id FROM user_payments WHERE user_id = $target_user_id AND payment_year = $payment_year AND status = 'confirmed'");
            if(mysqli_num_rows($check) > 0) {
                $error = "Payment for year $payment_year already exists";
            } else {
                $sql = "INSERT INTO user_payments (user_id, amount, payment_year, payment_date, payment_method, reference_number, notes, status, recorded_by, confirmed_by)
                        VALUES ($target_user_id, $amount, $payment_year, '$payment_date', '$payment_method', '$reference_number', '$notes', 'confirmed', $current_user_id, $current_user_id)";

                if(mysqli_query($conn, $sql)) {
                    $success = 'Payment recorded and confirmed';
                } else {
                    $error = 'Failed to record payment: ' . mysqli_error($conn);
                }
            }
        }
    }

    if($action == 'cancel_payment') {
        $payment_id = intval($_POST['payment_id']);
        mysqli_query($conn, "UPDATE user_payments SET status = 'cancelled' WHERE id = $payment_id");
        $success = 'Payment cancelled';
    }
}

// Get payment history
$payments = mysqli_query($conn, "SELECT up.*, u.full_name as recorded_by_name
                                  FROM user_payments up
                                  LEFT JOIN users u ON up.recorded_by = u.id
                                  WHERE up.user_id = $target_user_id
                                  ORDER BY up.payment_year DESC, up.created_at DESC");

$paid_years = [];
$payments_arr = [];
while($p = mysqli_fetch_assoc($payments)) {
    $payments_arr[] = $p;
    if($p['status'] == 'confirmed') {
        $paid_years[] = $p['payment_year'];
    }
}

$is_current_year_paid = in_array($current_year, $paid_years);
$is_viewing_self = ($target_user_id == $current_user_id);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment History - <?php echo htmlspecialchars($target_user['full_name'] ?: $target_user['username']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; }
        :root {
            --primary: #1a3a6e;
            --secondary: #2d5a3d;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-500: #64748b;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --sidebar-width: 280px;
            --radius: 12px;
        }
        body { background: var(--gray-100); min-height: 100vh; }
        .app-main { margin-left: var(--sidebar-width); padding: 24px; }
        @media (max-width: 1024px) { .app-main { margin-left: 0; padding: 16px; } }

        .back-link {
            display: inline-flex; align-items: center; gap: 8px;
            color: var(--gray-500); text-decoration: none; font-size: 14px; margin-bottom: 16px;
        }
        .back-link:hover { color: var(--primary); }

        .page-header {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            border-radius: 20px; padding: 30px; margin-bottom: 24px; color: white;
        }
        .page-header-content { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }
        .page-title h1 { font-size: 24px; font-weight: 700; margin: 0 0 8px; display: flex; align-items: center; gap: 12px; }
        .page-title p { margin: 0; opacity: 0.9; font-size: 14px; }

        .btn {
            display: inline-flex; align-items: center; gap: 8px;
            padding: 12px 24px; border-radius: var(--radius);
            font-weight: 600; border: none; cursor: pointer;
            text-decoration: none; transition: all 0.2s;
        }
        .btn-white { background: white; color: var(--primary); }
        .btn-white:hover { background: var(--gray-100); }

        .alert {
            padding: 14px 20px; border-radius: var(--radius); margin-bottom: 20px;
            display: flex; align-items: center; gap: 12px; font-size: 14px;
        }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-danger { background: #f8d7da; color: #721c24; }

        .stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
        .stat-card {
            background: white; border-radius: 16px; padding: 20px;
            display: flex; align-items: center; gap: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }
        .stat-icon {
            width: 50px; height: 50px; border-radius: var(--radius);
            display: flex; align-items: center; justify-content: center;
            font-size: 20px; color: white;
        }
        .stat-icon.green { background: linear-gradient(135deg, #22c55e, #16a34a); }
        .stat-icon.blue { background: linear-gradient(135deg, #3b82f6, #2563eb); }
        .stat-icon.purple { background: linear-gradient(135deg, #8b5cf6, #7c3aed); }
        .stat-icon.gold { background: linear-gradient(135deg, #d4af37, #f5d77a); color: #1a3a6e; }
        .stat-content h3 { font-size: 26px; font-weight: 700; color: var(--gray-800); margin: 0; }
        .stat-content p { font-size: 13px; color: var(--gray-500); margin: 4px 0 0; }

        .content-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 24px; }
        @media (max-width: 992px) { .content-grid { grid-template-columns: 1fr; } }

        .card {
            background: white; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden;
        }
        .card-header {
            padding: 20px 24px; border-bottom: 1px solid var(--gray-200);
            display: flex; justify-content: space-between; align-items: center;
        }
        .card-header h3 { font-size: 16px; font-weight: 600; color: var(--gray-800); display: flex; align-items: center; gap: 10px; }
        .card-body { padding: 24px; }

        .payment-timeline { position: relative; padding-left: 24px; }
        .payment-timeline::before {
            content: ''; position: absolute; left: 8px; top: 0; bottom: 0; width: 2px; background: var(--gray-200);
        }
        .payment-item {
            position: relative; margin-bottom: 20px; padding: 16px; background: var(--gray-50); border-radius: var(--radius);
        }
        .payment-item::before {
            content: ''; position: absolute; left: -20px; top: 20px; width: 10px; height: 10px; border-radius: 50%; background: var(--primary);
        }
        .payment-item.confirmed::before { background: var(--success); }
        .payment-item.pending::before { background: var(--warning); }
        .payment-item.cancelled::before { background: var(--danger); }

        .payment-item h4 { font-size: 15px; font-weight: 600; color: var(--gray-800); margin: 0 0 8px; display: flex; align-items: center; gap: 10px; }
        .payment-item p { font-size: 13px; color: var(--gray-600); margin: 4px 0; }
        .payment-item small { font-size: 12px; color: var(--gray-500); }

        .badge {
            display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px;
            border-radius: 20px; font-size: 11px; font-weight: 600;
        }
        .badge-success { background: rgba(34, 197, 94, 0.1); color: var(--success); }
        .badge-warning { background: rgba(245, 158, 11, 0.1); color: var(--warning); }
        .badge-danger { background: rgba(239, 68, 68, 0.1); color: var(--danger); }

        .year-list { list-style: none; }
        .year-list li {
            display: flex; justify-content: space-between; align-items: center;
            padding: 12px 0; border-bottom: 1px solid var(--gray-100);
        }
        .year-list li:last-child { border-bottom: none; }

        /* Modal */
        .modal-backdrop {
            position: fixed; top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0, 0, 0, 0.5); z-index: 9998;
            opacity: 0; visibility: hidden; transition: all 0.3s;
        }
        .modal-backdrop.active { opacity: 1; visibility: visible; }
        .modal {
            position: fixed; top: 50%; left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            background: white; border-radius: 16px; z-index: 9999;
            width: 90%; max-width: 450px; max-height: 90vh; overflow-y: auto;
            opacity: 0; visibility: hidden; transition: all 0.3s;
        }
        .modal.active { opacity: 1; visibility: visible; transform: translate(-50%, -50%) scale(1); }
        .modal-header { padding: 20px 24px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { font-size: 18px; font-weight: 600; margin: 0; }
        .modal-close { background: var(--gray-100); border: none; width: 32px; height: 32px; border-radius: 8px; cursor: pointer; }
        .modal-body { padding: 24px; }
        .modal-footer { padding: 16px 24px; border-top: 1px solid var(--gray-200); display: flex; justify-content: flex-end; gap: 12px; }

        .form-group { margin-bottom: 16px; }
        .form-label { display: block; font-size: 13px; font-weight: 600; color: var(--gray-700); margin-bottom: 6px; }
        .form-control {
            width: 100%; padding: 10px 14px; border: 2px solid var(--gray-200);
            border-radius: var(--radius); font-size: 14px;
        }
        .form-control:focus { outline: none; border-color: var(--primary); }

        .btn-primary { background: var(--primary); color: white; }
        .btn-outline { background: transparent; border: 2px solid var(--gray-200); color: var(--gray-600); }
        .btn-danger { background: var(--danger); color: white; }
        .btn-sm { padding: 6px 12px; font-size: 12px; }

        .empty-state { text-align: center; padding: 40px; }
        .empty-state i { font-size: 48px; color: var(--gray-300); margin-bottom: 16px; }
        .empty-state h4 { color: var(--gray-600); margin-bottom: 8px; }
        .empty-state p { color: var(--gray-500); font-size: 14px; }

        .upgrade-banner {
            background: linear-gradient(135deg, #d4af37 0%, #f5d77a 100%);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 20px;
        }
        .upgrade-content {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        .upgrade-icon {
            width: 56px;
            height: 56px;
            border-radius: 14px;
            background: rgba(26, 58, 110, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: #1a3a6e;
        }
        .upgrade-text h4 {
            font-size: 18px;
            font-weight: 700;
            color: #1a3a6e;
            margin: 0 0 4px;
        }
        .upgrade-text p {
            font-size: 14px;
            color: rgba(26, 58, 110, 0.8);
            margin: 0;
        }
        .btn-upgrade-now {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 14px 28px;
            background: #1a3a6e;
            color: #f5d77a;
            border-radius: var(--radius);
            font-weight: 600;
            text-decoration: none;
            transition: all 0.3s;
        }
        .btn-upgrade-now:hover {
            background: #0f2545;
            color: #f5d77a;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(26, 58, 110, 0.3);
            text-decoration: none;
        }
        @media (max-width: 768px) {
            .upgrade-banner { flex-direction: column; text-align: center; }
            .upgrade-content { flex-direction: column; }
            .btn-upgrade-now { width: 100%; justify-content: center; }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <?php if(!$is_viewing_self): ?>
        <a href="<?php echo url('my-clients'); ?>" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to My Clients
        </a>
        <?php endif; ?>

        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-receipt"></i> Payment History</h1>
                    <p><?php echo $is_viewing_self ? 'Your subscription payments' : htmlspecialchars($target_user['full_name'] ?: $target_user['username']); ?></p>
                </div>
                <?php if($user_role == 'admin'): ?>
                <button class="btn btn-white" onclick="openModal('addPaymentModal')">
                    <i class="fas fa-plus"></i> Record Payment
                </button>
                <?php endif; ?>
            </div>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>
        <?php if($success): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success; ?></div>
        <?php endif; ?>

        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon <?php echo $is_current_year_paid ? 'green' : 'blue'; ?>">
                    <i class="fas fa-<?php echo $is_current_year_paid ? 'check-circle' : 'clock'; ?>"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo $current_year; ?></h3>
                    <p><?php echo $is_current_year_paid ? 'Paid' : 'Unpaid'; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon <?php echo $user_type == 'premium' ? 'gold' : 'blue'; ?>">
                    <i class="fas fa-<?php echo $user_type == 'premium' ? 'crown' : 'user'; ?>"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo ucfirst($user_type); ?></h3>
                    <p>Account Type</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon blue">
                    <i class="fas fa-money-bill"></i>
                </div>
                <div class="stat-content">
                    <h3>TZS <?php echo number_format($yearly_fee); ?></h3>
                    <p>Yearly Fee</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon purple">
                    <i class="fas fa-calendar-alt"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo date('d M Y', strtotime($registration_date)); ?></h3>
                    <p>Registered</p>
                </div>
            </div>
        </div>

        <?php if($is_viewing_self && $user_type == 'basic'): ?>
        <div class="upgrade-banner">
            <div class="upgrade-content">
                <div class="upgrade-icon">
                    <i class="fas fa-crown"></i>
                </div>
                <div class="upgrade-text">
                    <h4>Upgrade to Premium</h4>
                    <p>Get access to image uploads, priority support, and more exclusive features!</p>
                </div>
            </div>
            <a href="<?php echo url('upgrade-premium'); ?>" class="btn-upgrade-now">
                <i class="fas fa-arrow-up"></i> Upgrade Now
            </a>
        </div>
        <?php endif; ?>

        <div class="content-grid">
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-history"></i> Payment History</h3>
                </div>
                <div class="card-body">
                    <?php if(count($payments_arr) == 0): ?>
                    <div class="empty-state">
                        <i class="fas fa-receipt"></i>
                        <h4>No Payments Yet</h4>
                        <p>No payment records found for this account.</p>
                    </div>
                    <?php else: ?>
                    <div class="payment-timeline">
                        <?php foreach($payments_arr as $payment): ?>
                        <div class="payment-item <?php echo $payment['status']; ?>">
                            <h4>
                                Year <?php echo $payment['payment_year']; ?>
                                <span class="badge badge-<?php echo $payment['status'] == 'confirmed' ? 'success' : ($payment['status'] == 'pending' ? 'warning' : 'danger'); ?>">
                                    <?php echo ucfirst($payment['status']); ?>
                                </span>
                            </h4>
                            <p><strong>Amount:</strong> TZS <?php echo number_format($payment['amount'], 2); ?></p>
                            <p><i class="fas fa-calendar"></i> <?php echo date('d M Y', strtotime($payment['payment_date'])); ?> | <?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'])); ?></p>
                            <?php if($payment['reference_number']): ?>
                            <p><small>Ref: <?php echo htmlspecialchars($payment['reference_number']); ?></small></p>
                            <?php endif; ?>
                            <small>Recorded by: <?php echo htmlspecialchars($payment['recorded_by_name'] ?: 'System'); ?></small>

                            <?php if($user_role == 'admin' && $payment['status'] != 'cancelled'): ?>
                            <form method="POST" style="display:inline; margin-left: 10px;" onsubmit="return confirm('Cancel this payment?')">
                                <input type="hidden" name="action" value="cancel_payment">
                                <input type="hidden" name="payment_id" value="<?php echo $payment['id']; ?>">
                                <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-times"></i></button>
                            </form>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-chart-bar"></i> Payment Years</h3>
                </div>
                <div class="card-body">
                    <ul class="year-list">
                        <?php for($y = $current_year + 1; $y >= $registration_year; $y--):
                            $is_paid = in_array($y, $paid_years);
                        ?>
                        <li>
                            <span><?php echo $y; ?></span>
                            <?php if($is_paid): ?>
                            <span class="badge badge-success"><i class="fas fa-check"></i> Paid</span>
                            <?php else: ?>
                            <span class="badge badge-danger">Unpaid</span>
                            <?php endif; ?>
                        </li>
                        <?php endfor; ?>
                    </ul>
                </div>
            </div>
        </div>
    </main>

    <?php if($user_role == 'admin'): ?>
    <!-- Modal Backdrop -->
    <div class="modal-backdrop" id="modalBackdrop" onclick="closeModal()"></div>

    <!-- Add Payment Modal -->
    <div class="modal" id="addPaymentModal">
        <div class="modal-header">
            <h3><i class="fas fa-plus"></i> Record Payment</h3>
            <button class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="add_payment">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Amount (TZS) *</label>
                    <input type="number" name="amount" class="form-control" value="<?php echo $yearly_fee; ?>" required min="1">
                </div>
                <div class="form-group">
                    <label class="form-label">Payment Year *</label>
                    <select name="payment_year" class="form-control" required>
                        <?php for($y = $current_year + 1; $y >= $registration_year; $y--): ?>
                        <option value="<?php echo $y; ?>" <?php echo $y == $current_year ? 'selected' : ''; ?>><?php echo $y; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Payment Date *</label>
                    <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Payment Method</label>
                    <select name="payment_method" class="form-control">
                        <option value="cash">Cash</option>
                        <option value="bank_transfer">Bank Transfer</option>
                        <option value="mobile_money">Mobile Money</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Reference Number</label>
                    <input type="text" name="reference_number" class="form-control" placeholder="Transaction ID">
                </div>
                <div class="form-group">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Payment</button>
            </div>
        </form>
    </div>

    <script>
        function openModal(id) {
            document.getElementById('modalBackdrop').classList.add('active');
            document.getElementById(id).classList.add('active');
        }
        function closeModal() {
            document.getElementById('modalBackdrop').classList.remove('active');
            document.querySelectorAll('.modal').forEach(m => m.classList.remove('active'));
        }
        document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
    </script>
    <?php endif; ?>
</body>
</html>
