<?php
/**
 * Payment Requests Management (for existing admin panel)
 * Location: /admin/payment_requests.php (ensi.online/admin)
 */
require_once 'config.php';

// Check admin authentication
$adminId = requireAdminAuth();
$admin = getCurrentAdmin();
$pageTitle = 'Payment Requests';

// Get database connection
$pdo = getDBConnection();

$message = '';
$messageType = '';

// Handle payment approval/rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $requestId = (int)$_POST['request_id'];
    $action = $_POST['action'];
    $adminNotes = $_POST['admin_notes'] ?? '';
    
    try {
        $pdo->beginTransaction();
        
        if ($action === 'approve') {
            // Get payment request details
            $stmt = $pdo->prepare("
                SELECT pr.*, s.id as subscription_id
                FROM payment_requests pr
                JOIN user_subscriptions s ON pr.subscription_id = s.id
                WHERE pr.id = ? AND pr.status = 'pending'
            ");
            $stmt->execute([$requestId]);
            $request = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($request) {
                // Update payment request
                $stmt = $pdo->prepare("
                    UPDATE payment_requests
                    SET status = 'approved',
                        admin_notes = ?,
                        processed_by = ?,
                        processed_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$adminNotes, $adminId, $requestId]);
                
                // Activate subscription using stored procedure
                $stmt = $pdo->prepare("CALL ActivateSubscription(?, ?)");
                $stmt->execute([$request['subscription_id'], $adminId]);
                
                $message = "Payment approved and subscription activated successfully!";
                $messageType = "success";
            }
            
        } else if ($action === 'reject') {
            // Update payment request
            $stmt = $pdo->prepare("
                UPDATE payment_requests
                SET status = 'rejected',
                    admin_notes = ?,
                    processed_by = ?,
                    processed_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$adminNotes, $adminId, $requestId]);
            
            // Update subscription
            $stmt = $pdo->prepare("
                UPDATE user_subscriptions
                SET status = 'cancelled'
                WHERE id = (SELECT subscription_id FROM payment_requests WHERE id = ?)
            ");
            $stmt->execute([$requestId]);
            
            $message = "Payment request rejected.";
            $messageType = "warning";
        }
        
        $pdo->commit();
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $message = "Error: " . $e->getMessage();
        $messageType = "danger";
    }
}

// Get pending payment requests
$query = "
    SELECT 
        pr.id as request_id,
        pr.amount,
        pr.payment_method,
        pr.payment_screenshot,
        pr.depositor_name,
        pr.deposit_date,
        pr.bank_reference,
        pr.created_at,
        u.id as user_id,
        u.email,
        u.user_name,
        COALESCE(u.full_name, u.user_name, u.email) as display_name,
        p.package_name,
        p.duration_months,
        s.id as subscription_id
    FROM payment_requests pr
    JOIN users u ON pr.user_id = u.id
    JOIN subscription_packages p ON pr.package_id = p.id
    JOIN user_subscriptions s ON pr.subscription_id = s.id
    WHERE pr.status = 'pending'
    ORDER BY pr.created_at ASC
";

$stmt = $pdo->query($query);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Requests - Admin Panel</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h1>💰 Payment Requests</h1>
            <p style="color: #f59e0b;"><?php echo count($requests); ?> Pending Requests</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>" style="margin-bottom: 20px; padding: 15px; border-radius: 8px; background: <?php echo $messageType === 'success' ? '#d1fae5' : ($messageType === 'warning' ? '#fef3c7' : '#fee2e2'); ?>;">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <?php if (empty($requests)): ?>
            <div class="content-card" style="text-align: center; padding: 60px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <h2>✅ All Clear!</h2>
                <p style="font-size: 18px; margin-top: 10px;">No pending payment requests at the moment.</p>
            </div>
        <?php else: ?>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 20px;">
                <?php foreach ($requests as $req): ?>
                    <div class="content-card">
                        <div style="background: #f59e0b; color: white; padding: 15px; margin: -20px -20px 20px -20px; border-radius: 12px 12px 0 0;">
                            <strong>Request #<?php echo $req['request_id']; ?></strong>
                            <span style="float: right;">
                                <?php echo date('M d, Y H:i', strtotime($req['created_at'])); ?>
                            </span>
                        </div>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                            <div>
                                <h4 style="margin-bottom: 10px; color: #1f2937;">User Information</h4>
                                <p style="line-height: 1.6;">
                                    <strong><?php echo htmlspecialchars($req['display_name']); ?></strong><br>
                                    <?php echo htmlspecialchars($req['email']); ?><br>
                                    <small style="color: #666;">User ID: <?php echo $req['user_id']; ?></small>
                                </p>

                                <h4 style="margin: 20px 0 10px; color: #1f2937;">Package</h4>
                                <p>
                                    <strong><?php echo htmlspecialchars($req['package_name']); ?></strong><br>
                                    <span class="badge badge-info"><?php echo $req['duration_months']; ?> Month<?php echo $req['duration_months'] > 1 ? 's' : ''; ?></span>
                                </p>

                                <h4 style="margin: 20px 0 10px; color: #1f2937;">Amount</h4>
                                <p style="color: #10b981; font-size: 24px; font-weight: bold;">
                                    Rs <?php echo number_format($req['amount'], 2); ?>
                                </p>
                            </div>

                            <div>
                                <h4 style="margin-bottom: 10px; color: #1f2937;">Payment Details</h4>
                                <p style="line-height: 1.6;">
                                    <strong>Method:</strong> <?php echo ucwords(str_replace('_', ' ', $req['payment_method'])); ?><br>
                                    <?php if ($req['depositor_name']): ?>
                                        <strong>Depositor:</strong> <?php echo htmlspecialchars($req['depositor_name']); ?><br>
                                    <?php endif; ?>
                                    <?php if ($req['deposit_date']): ?>
                                        <strong>Deposit Date:</strong> <?php echo date('Y-m-d', strtotime($req['deposit_date'])); ?><br>
                                    <?php endif; ?>
                                    <?php if ($req['bank_reference']): ?>
                                        <strong>Reference:</strong> <?php echo htmlspecialchars($req['bank_reference']); ?><br>
                                    <?php endif; ?>
                                </p>

                                <?php if ($req['payment_screenshot']): ?>
                                    <h4 style="margin: 20px 0 10px; color: #1f2937;">Payment Proof</h4>
                                    <a href="https://ensi.lk/uploads/payment_screenshots/<?php echo $req['payment_screenshot']; ?>" 
                                       target="_blank" 
                                       style="display: inline-block; padding: 8px 16px; background: #3b82f6; color: white; text-decoration: none; border-radius: 6px;">
                                        📷 View Screenshot
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>

                        <hr style="margin: 20px 0; border: 0; border-top: 1px solid #e5e7eb;">

                        <form method="POST">
                            <input type="hidden" name="request_id" value="<?php echo $req['request_id']; ?>">
                            
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 500;">Admin Notes</label>
                                <textarea name="admin_notes" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px; font-family: inherit;" rows="2" placeholder="Optional notes..."></textarea>
                            </div>

                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="submit" name="action" value="reject" 
                                        style="padding: 10px 20px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500;"
                                        onclick="return confirm('Are you sure you want to reject this payment?')">
                                    ❌ Reject
                                </button>
                                <button type="submit" name="action" value="approve" 
                                        style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500;"
                                        onclick="return confirm('Approve this payment and activate subscription?')">
                                    ✅ Approve & Activate
                                </button>
                            </div>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
