<?php
/**
 * Stripe Payments Admin Dashboard
 * Shows all payments with tracking_code from submissions
 */

session_start();
require_once __DIR__ . '/../../common/journal_config_new.php';

// Check admin authentication
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

// Pagination and filters
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query
$where_clauses = ["p.payment_method = 'stripe'"];
$params = [];
$param_types = '';

if ($status_filter && $status_filter !== 'all') {
    $where_clauses[] = "p.status = ?";
    $params[] = strtoupper($status_filter);
    $param_types .= 's';
}

if ($date_from) {
    $where_clauses[] = "DATE(p.created_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if ($date_to) {
    $where_clauses[] = "DATE(p.created_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

if ($search) {
    $where_clauses[] = "(p.tracking_code LIKE ? OR p.payer_email LIKE ? OR p.transaction_id LIKE ? OR s.title LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'ssss';
}

$where_sql = implode(' AND ', $where_clauses);

// Get total count
$count_query = "
    SELECT COUNT(*) as total
    FROM paypal_payments p
    LEFT JOIN submissions s ON p.tracking_code = s.tracking_code
    WHERE $where_sql
";

$count_stmt = $pdo->prepare($count_query);
if (!empty($params)) {
    $count_stmt->execute($params);
} else {
    $count_stmt->execute();
}
$total_records = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];
$total_pages = ceil($total_records / $limit);

// Get payments data
$query = "
    SELECT 
        p.*,
        s.title as paper_title,
        s.fee_paid,
        s.payment_date as submission_payment_date,
        a.name as author_name,
        a.country as author_country,
        j.name as journal_name,
        j.journal_code
    FROM paypal_payments p
    LEFT JOIN submissions s ON p.tracking_code = s.tracking_code
    LEFT JOIN authors a ON s.author_id = a.id
    LEFT JOIN journals j ON s.journal_id = j.id
    WHERE $where_sql
    ORDER BY p.created_at DESC
    LIMIT ? OFFSET ?
";

$stmt = $pdo->prepare($query);
$params[] = $limit;
$params[] = $offset;
$param_types .= 'ii';

$stmt->execute($params);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate statistics
$stats_query = "
    SELECT 
        COUNT(*) as total_count,
        SUM(CASE WHEN status = 'COMPLETED' THEN amount ELSE 0 END) as total_revenue,
        SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as successful_count,
        SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) as failed_count,
        SUM(CASE WHEN status LIKE '%REFUND%' THEN 1 ELSE 0 END) as refunded_count,
        currency
    FROM paypal_payments
    WHERE payment_method = 'stripe'
    GROUP BY currency
";

$stats_stmt = $pdo->query($stats_query);
$stats = $stats_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>Stripe Payments Dashboard - RSIS International</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, sans-serif;
            background: #f6f9fc;
            color: #32325d;
        }
        
        .header {
            background: white;
            padding: 20px 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: #32325d;
            font-size: 24px;
        }
        
        .header .actions {
            display: flex;
            gap: 15px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.2s;
        }
        
        .btn-primary {
            background: #635bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5469d4;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stat-label {
            color: #6b7c93;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
        }
        
        .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: #32325d;
        }
        
        .filters {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .filters form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .filter-group label {
            font-size: 14px;
            color: #6b7c93;
            font-weight: 500;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 10px 12px;
            border: 1px solid #e3e8ee;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background: #f6f9fc;
        }
        
        th {
            text-align: left;
            padding: 15px;
            font-size: 12px;
            font-weight: 600;
            color: #6b7c93;
            text-transform: uppercase;
        }
        
        td {
            padding: 15px;
            border-top: 1px solid #e3e8ee;
            font-size: 14px;
        }
        
        tr:hover {
            background: #f6f9fc;
        }
        
        .status {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            display: inline-block;
        }
        
        .status.completed {
            background: #d4edda;
            color: #155724;
        }
        
        .status.pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status.failed {
            background: #f8d7da;
            color: #721c24;
        }
        
        .pagination {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .pagination a {
            padding: 8px 15px;
            margin: 0 5px;
            border: 1px solid #e3e8ee;
            border-radius: 6px;
            text-decoration: none;
            color: #32325d;
        }
        
        .pagination a:hover,
        .pagination a.active {
            background: #635bff;
            color: white;
            border-color: #635bff;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-credit-card"></i> Stripe Payments Dashboard</h1>
        <div class="actions">
            <a href="admin-panel.php" class="btn btn-primary">
                <i class="fas fa-arrow-left"></i> Back to Admin
            </a>
            <a href="logout.php" class="btn" style="background: #dc3545; color: white;">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
    </div>

    <div class="container">
        <!-- Statistics -->
        <div class="stats">
            <?php foreach ($stats as $stat): ?>
            <div class="stat-card">
                <div class="stat-label">Total Revenue (<?php echo htmlspecialchars($stat['currency']); ?>)</div>
                <div class="stat-value">
                    <?php 
                    $symbol = $stat['currency'] === 'USD' ? '$' : ($stat['currency'] === 'INR' ? '₹' : $stat['currency']);
                    echo $symbol . number_format($stat['total_revenue'], 2); 
                    ?>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Successful Payments</div>
                <div class="stat-value"><?php echo $stat['successful_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Failed Payments</div>
                <div class="stat-value"><?php echo $stat['failed_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Refunded</div>
                <div class="stat-value"><?php echo $stat['refunded_count']; ?></div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Filters -->
        <div class="filters">
            <form method="get">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" name="search" placeholder="Tracking code, email, title..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                
                <div class="filter-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="all">All Statuses</option>
                        <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label>Date From</label>
                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
                </div>
                
                <div class="filter-group">
                    <label>Date To</label>
                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
                </div>
                
                <div class="filter-group">
                    <label>Per Page</label>
                    <select name="limit">
                        <option value="25" <?php echo $limit == 25 ? 'selected' : ''; ?>>25</option>
                        <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50</option>
                        <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100</option>
                    </select>
                </div>
                
                <button type="submit" class="btn btn-primary">Apply Filters</button>
                <a href="?" class="btn" style="background: #6c757d; color: white;">Clear</a>
            </form>
        </div>

        <!-- Payments Table -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Tracking Code</th>
                        <th>Date</th>
                        <th>Paper Title</th>
                        <th>Journal</th>
                        <th>Author</th>
                        <th>Email</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Transaction ID</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($payments) > 0): ?>
                        <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td><code><?php echo htmlspecialchars($payment['tracking_code']); ?></code></td>
                            <td><?php echo date('M d, Y H:i', strtotime($payment['created_at'])); ?></td>
                            <td><?php echo htmlspecialchars(substr($payment['paper_title'] ?? 'N/A', 0, 50)); ?></td>
                            <td><?php echo htmlspecialchars($payment['journal_code'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($payment['author_name'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($payment['payer_email']); ?></td>
                            <td>
                                <?php 
                                $symbol = $payment['currency'] === 'USD' ? '$' : ($payment['currency'] === 'INR' ? '₹' : '');
                                echo $symbol . number_format($payment['amount'], 2) . ' ' . htmlspecialchars($payment['currency']);
                                ?>
                            </td>
                            <td>
                                <span class="status <?php echo strtolower($payment['status']); ?>">
                                    <?php echo htmlspecialchars($payment['status']); ?>
                                </span>
                            </td>
                            <td>
                                <code style="font-size: 11px;"><?php echo htmlspecialchars(substr($payment['transaction_id'], 0, 20)); ?>...</code>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" style="text-align: center; padding: 40px; color: #6b7c93;">
                                No payments found
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <div>
                Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_records); ?> 
                of <?php echo $total_records; ?> payments
            </div>
            <div>
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo ($page - 1); ?>&limit=<?php echo $limit; ?>&status=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                <?php endif; ?>
                
                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                    <a href="?page=<?php echo $i; ?>&limit=<?php echo $limit; ?>&status=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>" 
                       class="<?php echo $i == $page ? 'active' : ''; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo ($page + 1); ?>&limit=<?php echo $limit; ?>&status=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>