<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$message = '';
$message_type = '';

// Handle PIN approval using POST then redirect (PRG pattern)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] === 'approve') {
        $request_id = intval($_POST['request_id']);
        $user_id = intval($_POST['user_id']);
        $package_id = intval($_POST['package_id']); // This will be 2500 or 3500
        $quantity = intval($_POST['pin_quantity']);
        
        // Validate package_id is 2500 or 3500
        if (!in_array($package_id, [2500, 3500])) {
            $_SESSION['flash_message'] = 'Invalid package ID! Must be 2500 or 3500.';
            $_SESSION['flash_type'] = 'danger';
            header("Location: pin-requests.php");
            exit();
        }
        
        // Start transaction
        mysqli_begin_transaction($conn);
        
        try {
            // Generate pins
            for ($i = 0; $i < $quantity; $i++) {
                // Generate unique 10-digit PIN
                do {
                    $pin_value = rand(10000, 99999); // 5-digit for demo, you can make it longer
                    $check = mysqli_query($conn, "SELECT id FROM pin WHERE pin_value = $pin_value");
                } while (mysqli_num_rows($check) > 0);
                
                $created_at = date('Y-m-d H:i:s');
                $transferred_at = date('Y-m-d H:i:s');
                
                $stmt = mysqli_prepare($conn, "INSERT INTO pin (pin_value, allcote_user, status, created_at, package_id, transferred_at) VALUES (?, ?, 0, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, "iissi", $pin_value, $user_id, $created_at, $package_id, $transferred_at);
                
                if (!mysqli_stmt_execute($stmt)) {
                    throw new Exception("Failed to generate PIN: " . mysqli_error($conn));
                }
            }
            
            // Update request status to approved (1)
            $stmt = mysqli_prepare($conn, "UPDATE pin_request SET status = 1, payment_status = 1 WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "i", $request_id);
            
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Failed to update request status: " . mysqli_error($conn));
            }
            
            mysqli_commit($conn);
            
            // Set success message in session for PRG pattern
            $_SESSION['flash_message'] = "$quantity PIN(s) of ₹$package_id generated and allocated to user ID: $user_id successfully!";
            $_SESSION['flash_type'] = 'success';
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['flash_message'] = "Error: " . $e->getMessage();
            $_SESSION['flash_type'] = 'danger';
        }
        
        // Redirect to prevent form resubmission
        header("Location: pin-requests.php");
        exit();
    }
    
    elseif ($_POST['action'] === 'reject') {
        $request_id = intval($_POST['request_id']);
        $rejection_reason = sanitize($conn, $_POST['rejection_reason'] ?? 'Request rejected by admin');
        
        // Update request status to rejected (2)
        $stmt = mysqli_prepare($conn, "UPDATE pin_request SET status = 2, message = ? WHERE id = ?");
        mysqli_stmt_bind_param($stmt, "si", $rejection_reason, $request_id);
        
        if (mysqli_stmt_execute($stmt)) {
            $_SESSION['flash_message'] = "PIN request #$request_id has been rejected.";
            $_SESSION['flash_type'] = 'warning';
        } else {
            $_SESSION['flash_message'] = "Error rejecting request: " . mysqli_error($conn);
            $_SESSION['flash_type'] = 'danger';
        }
        
        header("Location: pin-requests.php");
        exit();
    }
}

// Check for flash messages from session
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $message_type = $_SESSION['flash_type'];
    
    // Clear session messages
    unset($_SESSION['flash_message']);
    unset($_SESSION['flash_type']);
}

// Get filter status (pending by default)
$status_filter = isset($_GET['status']) ? intval($_GET['status']) : 0;

// Get all requests with user details
$requests = mysqli_query($conn, "SELECT pr.*, u.name as user_name, u.mobile as user_mobile, u.email 
                                 FROM pin_request pr 
                                 LEFT JOIN users u ON pr.user_id = u.user_id 
                                 WHERE pr.status = $status_filter
                                 ORDER BY pr.id DESC");

// Get statistics
$stats = [];
$result = mysqli_query($conn, "SELECT status, COUNT(*) as count FROM pin_request GROUP BY status");
while ($row = mysqli_fetch_assoc($result)) {
    $stats[$row['status']] = $row['count'];
}
$stats[0] = $stats[0] ?? 0; // Pending
$stats[1] = $stats[1] ?? 0; // Approved
$stats[2] = $stats[2] ?? 0; // Rejected
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>PIN Requests - MLM System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.gstatic.com" rel="preconnect">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
    
    <!-- Lightbox for image viewing -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css" rel="stylesheet">
    
    <style>
        .status-badge-pending { background-color: #ffc107; color: #000; }
        .status-badge-approved { background-color: #28a745; color: #fff; }
        .status-badge-rejected { background-color: #dc3545; color: #fff; }
        .screenshot-thumb { cursor: pointer; transition: transform 0.3s; }
        .screenshot-thumb:hover { transform: scale(1.1); }
        .stats-card {
            border-left: 4px solid;
            transition: all 0.3s;
        }
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .stats-pending { border-left-color: #ffc107; }
        .stats-approved { border-left-color: #28a745; }
        .stats-rejected { border-left-color: #dc3545; }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>PIN Requests Management</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">PIN Requests</li>
                </ol>
            </nav>
        </div>

        <section class="section">
            <div class="row">
                <!-- Statistics Cards -->
                <div class="col-lg-4">
                    <div class="card stats-card stats-pending mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-clock-history fs-1 text-warning"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">Pending</h5>
                                    <h2 class="mb-0"><?php echo $stats[0]; ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <div class="card stats-card stats-approved mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-check-circle fs-1 text-success"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">Approved</h5>
                                    <h2 class="mb-0"><?php echo $stats[1]; ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <div class="card stats-card stats-rejected mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-x-circle fs-1 text-danger"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">Rejected</h5>
                                    <h2 class="mb-0"><?php echo $stats[2]; ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-lg-12">
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Status Filter Tabs -->
                    <ul class="nav nav-tabs mb-3">
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status_filter == 0 ? 'active' : ''; ?>" href="?status=0">
                                Pending <span class="badge bg-warning ms-1"><?php echo $stats[0]; ?></span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status_filter == 1 ? 'active' : ''; ?>" href="?status=1">
                                Approved <span class="badge bg-success ms-1"><?php echo $stats[1]; ?></span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status_filter == 2 ? 'active' : ''; ?>" href="?status=2">
                                Rejected <span class="badge bg-danger ms-1"><?php echo $stats[2]; ?></span>
                            </a>
                        </li>
                    </ul>
                    
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">
                                <?php 
                                if ($status_filter == 0) echo 'Pending ';
                                elseif ($status_filter == 1) echo 'Approved ';
                                else echo 'Rejected ';
                                ?>PIN Requests
                            </h5>
                            
                            <?php if (mysqli_num_rows($requests) > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-striped datatable">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>User ID</th>
                                            <th>Name</th>
                                            <th>Mobile</th>
                                            <th>Package</th>
                                            <th>Price</th>
                                            <th>Qty</th>
                                            <th>Total</th>
                                            <th>Payment Proof</th>
                                            <th>Request Date</th>
                                            <th>Status</th>
                                            <?php if ($status_filter == 0): ?>
                                            <th>Actions</th>
                                            <?php endif; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($row = mysqli_fetch_assoc($requests)): 
                                            // Ensure package_id is set correctly (2500 or 3500)
                                            $package_id = $row['package_id'];
                                            if (!in_array($package_id, [2500, 3500])) {
                                                // Auto-correct based on package_name or price
                                                if (strpos($row['package_name'], '2500') !== false || strpos($row['package_price'], '2500') !== false) {
                                                    $package_id = 2500;
                                                } elseif (strpos($row['package_name'], '3500') !== false || strpos($row['package_price'], '3500') !== false) {
                                                    $package_id = 3500;
                                                } else {
                                                    $package_id = intval($row['package_price']);
                                                }
                                            }
                                        ?>
                                        <tr>
                                            <td><?php echo $row['id']; ?></td>
                                            <td><?php echo $row['user_id']; ?></td>
                                            <td><?php echo htmlspecialchars($row['user_name'] ?: $row['name']); ?></td>
                                            <td><?php echo $row['mob'] ?: $row['user_mobile']; ?></td>
                                            <td>
                                                <?php 
                                                echo htmlspecialchars($row['package_name']);
                                                echo "<strong><br>PRICE: $package_id/-</strong>";
                                                ?>
                                            </td>
                                            <td>₹<?php echo number_format($row['package_price']); ?></td>
                                            <td><?php echo $row['pin_quantity']; ?></td>
                                            <td>₹<?php echo number_format($row['total_amount']); ?></td>
                                            <td>
                                                
                                                    <a href="../uploads/payment_screenshots/<?php echo $row['payment_screenshot']; ?>" data-lightbox="screenshot-<?php echo $row['id']; ?>" data-title="Payment Proof for Request #<?php echo $row['id']; ?>">
                                                        <img src="../uploads/payment_screenshots/<?php echo $row['payment_screenshot']; ?>" 
                                                             class="img-thumbnail screenshot-thumb" 
                                                             style="max-width: 60px; max-height: 60px;"
                                                             alt="Payment Screenshot">
                                                    </a>
                                                
                                            </td>
                                            <td><?php echo date('d M Y H:i', strtotime($row['created_at'] ?: $row['timestamp'])); ?></td>
                                            <td>
                                                <?php 
                                                $status = $row['status'];
                                                if ($status == 0): ?>
                                                    <span class="badge bg-warning">Pending</span>
                                                <?php elseif ($status == 1): ?>
                                                    <span class="badge bg-success">Approved</span>
                                                <?php elseif ($status == 2): ?>
                                                    <span class="badge bg-danger">Rejected</span>
                                                <?php endif; ?>
                                            </td>
                                            
                                            <?php if ($status_filter == 0): ?>
                                            <td>
                                                <!-- Approve Button -->
                                                <button type="button" class="btn btn-sm btn-success mb-1" 
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#approveModal<?php echo $row['id']; ?>"
                                                        style="width: 70px;">
                                                    <i class="bi bi-check-circle"></i> Approve
                                                </button>
                                                
                                                <!-- Reject Button -->
                                                <button type="button" class="btn btn-sm btn-danger mb-1" 
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#rejectModal<?php echo $row['id']; ?>"
                                                        style="width: 70px;">
                                                    <i class="bi bi-x-circle"></i> Reject
                                                </button>
                                                
                                                <!-- Approve Modal (PRG Pattern) -->
                                                <div class="modal fade" id="approveModal<?php echo $row['id']; ?>" tabindex="-1" aria-hidden="true">
                                                    <div class="modal-dialog">
                                                        <div class="modal-content">
                                                            <div class="modal-header bg-success text-white">
                                                                <h5 class="modal-title">Approve PIN Request #<?php echo $row['id']; ?></h5>
                                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <form method="POST" action="pin-requests.php">
                                                                <input type="hidden" name="action" value="approve">
                                                                <input type="hidden" name="request_id" value="<?php echo $row['id']; ?>">
                                                                <input type="hidden" name="user_id" value="<?php echo $row['user_id']; ?>">
                                                                <input type="hidden" name="package_id" value="<?php echo $package_id; ?>">
                                                                <input type="hidden" name="pin_quantity" value="<?php echo $row['pin_quantity']; ?>">
                                                                
                                                                <div class="modal-body">
                                                                    <div class="alert alert-info">
                                                                        <strong>Request Details:</strong>
                                                                        <ul class="mb-0 mt-2">
                                                                            <li><strong>User:</strong> <?php echo $row['user_id']; ?> (<?php echo htmlspecialchars($row['user_name'] ?: $row['name']); ?>)</li>
                                                                            <li><strong>Package:</strong> <?php echo $row['package_name'] .'₹'. number_format($row['package_price']); ?></li>
                                                                            <li><strong>Package ID:</strong> <?php echo $package_id; ?></li>
                                                                            <li><strong>Quantity:</strong> <?php echo $row['pin_quantity']; ?></li>
                                                                            <li><strong>Total Amount:</strong> ₹<?php echo number_format($row['total_amount']); ?></li>
                                                                            <li><strong>Payment Proof:</strong> <img src="../uploads/payment_screenshots/<?php echo $row['payment_screenshot']; ?>" style="width: 258px;"></li>
                                                                        </ul>
                                                                    </div>
                                                                    
                                                                    <p class="mt-3">This will generate <strong><?php echo $row['pin_quantity']; ?> PIN(s)</strong> of <strong>₹<?php echo $package_id; ?></strong> each for the user.</p>
                                                                    
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" id="confirmApprove<?php echo $row['id']; ?>" required>
                                                                        <label class="form-check-label" for="confirmApprove<?php echo $row['id']; ?>">
                                                                            I confirm that the payment proof has been verified and approve this request.
                                                                        </label>
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                    <button type="submit" class="btn btn-success" id="approveBtn<?php echo $row['id']; ?>">
                                                                        <i class="bi bi-check-circle"></i> Approve & Generate PINs
                                                                    </button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <!-- Reject Modal (PRG Pattern) -->
                                                <div class="modal fade" id="rejectModal<?php echo $row['id']; ?>" tabindex="-1" aria-hidden="true">
                                                    <div class="modal-dialog">
                                                        <div class="modal-content">
                                                            <div class="modal-header bg-danger text-white">
                                                                <h5 class="modal-title">Reject PIN Request #<?php echo $row['id']; ?></h5>
                                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <form method="POST" action="pin-requests.php">
                                                                <input type="hidden" name="action" value="reject">
                                                                <input type="hidden" name="request_id" value="<?php echo $row['id']; ?>">
                                                                
                                                                <div class="modal-body">
                                                                    <p>Are you sure you want to reject this PIN request?</p>
                                                                    
                                                                    <div class="mb-3">
                                                                        <label for="rejectionReason<?php echo $row['id']; ?>" class="form-label">Reason for rejection (optional)</label>
                                                                        <textarea class="form-control" id="rejectionReason<?php echo $row['id']; ?>" name="rejection_reason" rows="2" placeholder="Enter rejection reason..."></textarea>
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                    <button type="submit" class="btn btn-danger">
                                                                        <i class="bi bi-x-circle"></i> Reject Request
                                                                    </button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <?php endif; ?>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="bi bi-info-circle"></i> 
                                    No <?php 
                                    if ($status_filter == 0) echo 'pending';
                                    elseif ($status_filter == 1) echo 'approved';
                                    else echo 'rejected';
                                    ?> PIN requests found.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

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

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
    <script src="assets/js/main.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js"></script>
    
    <script>
    // Initialize Lightbox
    lightbox.option({
        'resizeDuration': 200,
        'wrapAround': true,
        'albumLabel': 'Image %1 of %2'
    });
    
    // Disable approve button until checkbox is checked
    document.addEventListener('DOMContentLoaded', function() {
        <?php while ($row = mysqli_fetch_assoc($requests)): ?>
        (function() {
            var checkbox = document.getElementById('confirmApprove<?php echo $row['id']; ?>');
            if (checkbox) {
                var approveBtn = document.getElementById('approveBtn<?php echo $row['id']; ?>');
                approveBtn.disabled = true;
                
                checkbox.addEventListener('change', function() {
                    approveBtn.disabled = !this.checked;
                });
            }
        })();
        <?php 
        mysqli_data_seek($requests, 0); // Reset pointer
        endwhile; 
        ?>
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>