<?php
define('SECURE_ACCESS', true);

$pageTitle = "Prepaid PINs Manager";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// Helper functions for PIN generation
function generateRandomPIN() {
    $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $pin = '';
    for ($i = 0; $i < 12; $i++) {
        if ($i > 0 && $i % 4 === 0) {
            $pin .= '-';
        }
        $pin .= $chars[rand(0, strlen($chars) - 1)];
    }
    return 'PIN-' . $pin;
}

function generateUniquePIN($pdo) {
    $exists = true;
    $attempts = 0;
    while ($exists && $attempts < 100) {
        $pin = generateRandomPIN();
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM registration_pins WHERE pin = ?");
        $stmt->execute([$pin]);
        if ($stmt->fetchColumn() == 0) {
            return $pin;
        }
        $attempts++;
    }
    throw new Exception("Failed to generate a unique PIN.");
}

// Handle PIN generation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_pins'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = "Security check failed (CSRF). Please try again.";
    } else {
        $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
        $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0.00;
        $event_id = isset($_POST['event_id']) && $_POST['event_id'] !== '' ? (int)$_POST['event_id'] : null;

        if ($quantity < 1 || $quantity > 100) {
            $error = "Quantity must be between 1 and 100.";
        } elseif ($amount <= 0.00) {
            $error = "Amount must be a positive value.";
        } else {
            try {
                $pdo->beginTransaction();
                for ($i = 0; $i < $quantity; $i++) {
                    $pin = generateUniquePIN($pdo);
                    $stmt = $pdo->prepare("INSERT INTO registration_pins (pin, amount, status, created_by, event_id) VALUES (?, ?, 'active', ?, ?)");
                    $stmt->execute([$pin, $amount, $currentUser['id'], $event_id]);
                }
                $pdo->commit();
                $success = "Successfully generated $quantity E-PIN(s) of value ₹" . number_format($amount, 2) . ".";
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $error = "Failed to generate PINs: " . $e->getMessage();
            }
        }
    }
}

// Handle PIN Voiding
if (isset($_GET['action']) && $_GET['action'] === 'void' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
    } else {
        $id = (int)$_GET['id'];
        try {
            $stmt = $pdo->prepare("UPDATE registration_pins SET status = 'void' WHERE id = ? AND status = 'active'");
            $stmt->execute([$id]);
            $_SESSION['flash_success'] = "Prepaid PIN voided successfully.";
        } catch (PDOException $e) {
            $_SESSION['flash_error'] = "Failed to void PIN: " . $e->getMessage();
        }
    }
    header("Location: pins");
    exit();
}

// Filters & Search
$status_filter = trim($_GET['status'] ?? 'all');
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 15;
$offset = ($page - 1) * $limit;

$query_where = " WHERE 1=1";
$params = [];

if ($status_filter !== 'all') {
    $query_where .= " AND p.status = ?";
    $params[] = $status_filter;
}

if (!empty($search)) {
    $query_where .= " AND (p.pin ILIKE ? OR u.username ILIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// Count total
$count_stmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM registration_pins p
    LEFT JOIN users u ON p.used_by = u.id
    $query_where
");
$count_stmt->execute($params);
$total_records = (int)$count_stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// Fetch paginated records
$stmt_list = $pdo->prepare("
    SELECT p.*, e.title as event_title, u.username as used_by_username, c.username as creator_username
    FROM registration_pins p
    LEFT JOIN events e ON p.event_id = e.id
    LEFT JOIN users u ON p.used_by = u.id
    LEFT JOIN users c ON p.created_by = c.id
    $query_where
    ORDER BY p.id DESC
    LIMIT $limit OFFSET $offset
");
$stmt_list->execute($params);
$pins = $stmt_list->fetchAll();

// Fetch statistics
$stats = [
    'active' => 0,
    'used' => 0,
    'void' => 0,
    'total_value' => 0.00
];
try {
    $stmt_stats = $pdo->query("
        SELECT 
            COALESCE(SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END), 0) as active_count,
            COALESCE(SUM(CASE WHEN status = 'used' THEN 1 ELSE 0 END), 0) as used_count,
            COALESCE(SUM(CASE WHEN status = 'void' THEN 1 ELSE 0 END), 0) as void_count,
            COALESCE(SUM(amount), 0.00) as total_val
        FROM registration_pins
    ");
    $stats_row = $stmt_stats->fetch();
    if ($stats_row) {
        $stats['active'] = (int)$stats_row['active_count'];
        $stats['used'] = (int)$stats_row['used_count'];
        $stats['void'] = (int)$stats_row['void_count'];
        $stats['total_value'] = (float)$stats_row['total_val'];
    }
} catch (PDOException $e) {}

// Fetch paid events for restriction dropdown
$paid_events = [];
try {
    $stmt_ev = $pdo->query("SELECT id, title, price FROM events WHERE payment_type = 'paid' AND status = 'published' ORDER BY start_date DESC");
    $paid_events = $stmt_ev->fetchAll();
} catch (PDOException $e) {}

include __DIR__ . '/../../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Prepaid E-PINs Manager</h1>
        <p class="text-muted mb-0">Generate, track, and void system-controlled registration PINs used for event payments.</p>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
        <i class="bi bi-check-circle-fill me-2"></i>
        <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Stats Row -->
<div class="row g-3 mb-4">
    <div class="col-12 col-sm-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center">
                <div class="rounded-circle bg-primary bg-opacity-10 text-primary p-3 me-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                    <i class="bi bi-key fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted small mb-1">Active PINs</h6>
                    <h3 class="fw-bold text-dark mb-0"><?php echo $stats['active']; ?></h3>
                </div>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center">
                <div class="rounded-circle bg-success bg-opacity-10 text-success p-3 me-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                    <i class="bi bi-check-circle fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted small mb-1">Used PINs</h6>
                    <h3 class="fw-bold text-dark mb-0"><?php echo $stats['used']; ?></h3>
                </div>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center">
                <div class="rounded-circle bg-danger bg-opacity-10 text-danger p-3 me-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                    <i class="bi bi-slash-circle fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted small mb-1">Void PINs</h6>
                    <h3 class="fw-bold text-dark mb-0"><?php echo $stats['void']; ?></h3>
                </div>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center">
                <div class="rounded-circle bg-info bg-opacity-10 text-info p-3 me-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                    <i class="bi bi-currency-rupee fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted small mb-1">Total Pool Value</h6>
                    <h3 class="fw-bold text-dark mb-0">₹<?php echo number_format($stats['total_value'], 2); ?></h3>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <!-- Generator Panel (Left) -->
    <div class="col-12 col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-plus-circle-fill me-2 text-primary"></i>Generate E-PINs</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="pins">
                    <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                    
                    <div class="mb-3">
                        <label for="amount" class="form-label fw-semibold text-dark">PIN Value / Amount (₹) <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" step="0.01" min="0.01" class="form-control" id="amount" name="amount" required placeholder="e.g. 100.00">
                        </div>
                        <div class="form-text">The value of each generated PIN in Indian Rupees.</div>
                    </div>

                    <div class="mb-3">
                        <label for="quantity" class="form-label fw-semibold text-dark">Quantity <span class="text-danger">*</span></label>
                        <input type="number" min="1" max="100" class="form-control" id="quantity" name="quantity" value="1" required>
                        <div class="form-text">Generate up to 100 PINs in a single batch.</div>
                    </div>

                    <div class="mb-4">
                        <label for="event_id" class="form-label fw-semibold text-dark">Restricted to Event (Optional)</label>
                        <select class="form-select" id="event_id" name="event_id">
                            <option value="">-- Generic (Any Event) --</option>
                            <?php foreach ($paid_events as $pe): ?>
                                <option value="<?php echo $pe['id']; ?>">
                                    <?php echo htmlspecialchars($pe['title']); ?> (₹<?php echo number_format($pe['price'], 2); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text">Lock the PINs to a specific event only. If left empty, they can be used for any event.</div>
                    </div>

                    <button type="submit" name="generate_pins" class="btn btn-primary w-100 py-2.5 fw-bold shadow-sm">
                        <i class="bi bi-cogs me-1"></i> Bulk Generate PINs
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Listing & Tracking (Right) -->
    <div class="col-12 col-lg-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom py-3 d-flex flex-column flex-sm-row justify-content-between align-sm-center gap-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-list-stars me-2 text-primary"></i>E-PIN Listing</h5>
                <form method="GET" action="pins" class="d-flex gap-2">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status_filter); ?>">
                    <div class="input-group input-group-sm" style="max-width: 250px;">
                        <input type="text" class="form-control" name="search" placeholder="Search PIN or Username..." value="<?php echo htmlspecialchars($search); ?>">
                        <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i></button>
                    </div>
                </form>
            </div>
            
            <!-- Filter Tabs -->
            <div class="bg-light px-3 py-2 border-bottom">
                <ul class="nav nav-pills gap-1" style="font-size: 0.85rem;">
                    <li class="nav-item">
                        <a class="nav-link py-1 px-3 <?php echo $status_filter === 'all' ? 'active' : 'text-secondary'; ?>" href="pins?status=all&search=<?php echo urlencode($search); ?>">All</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link py-1 px-3 <?php echo $status_filter === 'active' ? 'active bg-primary' : 'text-secondary'; ?>" href="pins?status=active&search=<?php echo urlencode($search); ?>">Active</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link py-1 px-3 <?php echo $status_filter === 'used' ? 'active bg-success' : 'text-secondary'; ?>" href="pins?status=used&search=<?php echo urlencode($search); ?>">Used</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link py-1 px-3 <?php echo $status_filter === 'void' ? 'active bg-danger' : 'text-secondary'; ?>" href="pins?status=void&search=<?php echo urlencode($search); ?>">Void</a>
                    </li>
                </ul>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 text-center">
                        <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.72rem;">
                            <tr>
                                <th>PIN Code</th>
                                <th>Amount</th>
                                <th>Constraint</th>
                                <th>Status</th>
                                <th>Used By</th>
                                <th>Used At</th>
                                <th class="text-end pe-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($pins)): ?>
                                <tr>
                                    <td colspan="7" class="text-center py-5 text-muted">
                                        <i class="bi bi-shield-exclamation fs-1 mb-2"></i>
                                        <p class="mb-0">No E-PINs match the filters.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($pins as $p): ?>
                                    <tr>
                                        <td>
                                            <code class="fw-bold text-primary" style="font-size: 0.9rem;"><?php echo htmlspecialchars($p['pin']); ?></code>
                                        </td>
                                        <td>
                                            <strong class="text-dark">₹<?php echo number_format($p['amount'], 2); ?></strong>
                                        </td>
                                        <td>
                                            <?php if ($p['event_id']): ?>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis text-truncate d-inline-block" style="max-width: 140px;" title="<?php echo htmlspecialchars($p['event_title']); ?>">
                                                    Event: <?php echo htmlspecialchars($p['event_title']); ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted small">Generic</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($p['status'] === 'active'): ?>
                                                <span class="badge bg-primary px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.7rem;">Active</span>
                                            <?php elseif ($p['status'] === 'used'): ?>
                                                <span class="badge bg-success px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.7rem;">Used</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.7rem;">Voided</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($p['status'] === 'used'): ?>
                                                <span class="fw-semibold text-dark">@<?php echo htmlspecialchars($p['used_by_username']); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($p['status'] === 'used' && $p['used_at']): ?>
                                                <span class="text-secondary small font-monospace"><?php echo date('Y-m-d H:i', strtotime($p['used_at'])); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end pe-4">
                                            <?php if ($p['status'] === 'active'): ?>
                                                <a href="pins?action=void&id=<?php echo $p['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" 
                                                   class="btn btn-sm btn-outline-danger" 
                                                   onclick="return confirm('Are you sure you want to void this E-PIN? This cannot be undone.');">
                                                    <i class="bi bi-x-circle-fill"></i> Void
                                                </a>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-light border-0" disabled>-</button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Pagination Footer -->
            <?php if ($total_pages > 1): ?>
                <div class="card-footer bg-white border-top py-3 d-flex justify-content-center">
                    <nav aria-label="PIN Pagination">
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="pins?status=<?php echo urlencode($status_filter); ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $page - 1; ?>"><i class="bi bi-chevron-left"></i></a>
                            </li>
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                                    <a class="page-link" href="pins?status=<?php echo urlencode($status_filter); ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="pins?status=<?php echo urlencode($status_filter); ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $page + 1; ?>"><i class="bi bi-chevron-right"></i></a>
                            </li>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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