<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

if (!checkAdmin($udata['type'])) {
    echo '<script>window.location="index.php";</script>';
    exit;
}

// Telegram Configuration
if (!defined('TELEGRAM_LL_BOT_TOKEN')) {
    define('TELEGRAM_LL_BOT_TOKEN', '8359738357:AAEGKHLBpR6c9vzD3xfmIn6dRwZnyRuzfeQ');
}

// Handle Status Update
if (isset($_POST['update_status'])) {
    $request_id = intval($_POST['request_id']);
    $action = $_POST['action'];
    $rejection_reason = trim($_POST['rejection_reason'] ?? '');
    
    if ($action == 'reject' && empty($rejection_reason)) {
        echo '<script>Swal.fire("Error", "Rejection reason required!", "error");</script>';
    } else {
        $rec = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM ll_requests WHERE id=$request_id"));
        
        if ($rec) {
            if ($action == 'success') {
                // Handle file upload
                if (isset($_FILES['result_file']) && $_FILES['result_file']['error'] == UPLOAD_ERR_OK) {
                    $file = $_FILES['result_file'];
                    $allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png'];
                    $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                    
                    if (!in_array($fileExtension, $allowedExtensions)) {
                        echo '<script>Swal.fire("Error", "Only PDF/JPG/PNG allowed!", "error");</script>';
                    } else if ($file['size'] > 5 * 1024 * 1024) {
                        echo '<script>Swal.fire("Error", "File too large (Max 5MB)!", "error");</script>';
                    } else {
                        $uploadDir = '../uploads/ll_results/';
                        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                        
                        $fileName = 'LL_' . $rec['order_id'] . '_' . time() . '.' . $fileExtension;
                        $uploadPath = $uploadDir . $fileName;
                        
                        if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                            // Update as success
                            mysqli_query($ahk_conn, "UPDATE ll_requests SET 
                                status='Success', result_file='$fileName', completed_date=NOW() 
                                WHERE id=$request_id");
                            
                            // WhatsApp notification
                            $whamessage = "Dear {$rec['name']},\n\nYour LL Request has been APPROVED!\n\nOrder ID: {$rec['order_id']}\nApp No: {$rec['application_number']}\n\nDownload your result now!";
                            @send_sms($rec['mobile'], $whamessage);
                            
                            echo '<script>
                                Swal.fire("Success", "Request approved & file uploaded!", "success");
                                setTimeout(function(){ location.reload(); }, 1500);
                            </script>';
                        } else {
                            echo '<script>Swal.fire("Error", "File upload failed!", "error");</script>';
                        }
                    }
                } else {
                    echo '<script>Swal.fire("Error", "Please upload result file!", "error");</script>';
                }
                
            } else if ($action == 'reject') {
                // Refund amount
                $userInfo = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='{$rec['user_id']}'"));
                $old_balance = floatval($userInfo['balance']);
                $new_balance = $old_balance + floatval($rec['amount']);
                
                mysqli_query($ahk_conn, "UPDATE users SET balance=$new_balance WHERE phone='{$rec['user_id']}'");
                
                // Insert refund transaction
                $reportSql = "INSERT INTO reports (
                    site_id, user_id, username, name, operator, parent_id, order_id, service, type,
                    account_number, app_type, amount, main_amount, old_balance, new_balance,
                    txn_id, ref_id, description, date_time, status
                ) VALUES (
                    1, '{$rec['user_id']}', '{$rec['username']}', '{$rec['name']}', 'admin', 0,
                    '{$rec['order_id']}', 'LL Request Refund', 'Credit', '{$rec['application_number']}', 'LL Request',
                    {$rec['amount']}, {$rec['amount']}, $old_balance, $new_balance, '{$rec['order_id']}', '{$rec['application_number']}',
                    'LL Request Rejected - Refund Rs.{$rec['amount']}', NOW(), 'Success'
                )";
                mysqli_query($ahk_conn, $reportSql);
                
                // Update as rejected
                mysqli_query($ahk_conn, "UPDATE ll_requests SET 
                    status='Rejected', rejection_reason='$rejection_reason', completed_date=NOW() 
                    WHERE id=$request_id");
                
                // WhatsApp notification
                $whamessage = "Dear {$rec['name']},\n\nYour LL Request has been REJECTED.\n\nOrder ID: {$rec['order_id']}\nReason: $rejection_reason\n\nAmount Rs.{$rec['amount']} refunded to wallet.";
                @send_sms($rec['mobile'], $whamessage);
                
                echo '<script>
                    Swal.fire("Rejected & Refunded", "Amount Rs.' . $rec['amount'] . ' refunded!", "success");
                    setTimeout(function(){ location.reload(); }, 1500);
                </script>';
            }
        }
    }
}

// Filters
$status_filter = $_GET['status'] ?? 'Pending';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 25;
$offset = ($page - 1) * $limit;

$where = "status='$status_filter'";
if (!empty($search)) {
    $where .= " AND (order_id LIKE '%$search%' OR application_number LIKE '%$search%' OR username LIKE '%$search%')";
}

$records = mysqli_query($ahk_conn, "SELECT * FROM ll_requests WHERE $where ORDER BY id DESC LIMIT $limit OFFSET $offset");
$total = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM ll_requests WHERE $where"));

// Statistics
$pendingCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM ll_requests WHERE status='Pending'"));
$successCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM ll_requests WHERE status='Success'"));
$rejectedCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM ll_requests WHERE status='Rejected'"));
$totalCount = $pendingCount + $successCount + $rejectedCount;

$todayCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM ll_requests WHERE DATE(request_date) = CURDATE()"));

include('../template/ahkweb/header.php');
?>

<style>
.stat-box { 
    padding:15px; 
    border-radius:10px; 
    color:#fff; 
    text-align:center; 
    cursor:pointer; 
    transition:transform 0.2s;
}
.stat-box:hover { transform:translateY(-5px); }
.stat-box h3 { margin:0; font-size:28px; font-weight:700; }
.stat-box p { margin:5px 0 0; font-size:12px; }
.stat-total { background:linear-gradient(135deg,#667eea,#764ba2); }
.stat-pending { background:linear-gradient(135deg,#f093fb,#f5576c); }
.stat-success { background:linear-gradient(135deg,#4facfe,#00f2fe); }
.stat-rejected { background:linear-gradient(135deg,#fa709a,#fee140); }
.stat-today { background:linear-gradient(135deg,#30cfd0,#330867); }

.tab-nav { display:flex; gap:10px; margin-bottom:15px; }
.tab-btn { 
    padding:10px 20px; 
    border:none; 
    background:#e0e0e0; 
    border-radius:8px; 
    cursor:pointer; 
    font-weight:600;
    transition:all 0.3s;
}
.tab-btn.active { background:linear-gradient(135deg,#667eea,#764ba2); color:#fff; }
.tab-btn:hover { transform:translateY(-2px); }

.action-panel {
    background:#f8f9fa;
    border-radius:8px;
    padding:15px;
    margin-top:10px;
    display:none;
}
.action-panel.show { display:block; }

.copy-btn {
    background:linear-gradient(135deg,#667eea,#764ba2);
    color:white;
    border:none;
    padding:4px 10px;
    border-radius:5px;
    font-size:11px;
    cursor:pointer;
    margin-left:5px;
}
</style>

<div class="page-wrapper">
    <div class="page-content">
        <!-- Statistics -->
        <div class="row mb-3">
            <div class="col-md-2 mb-2">
                <div class="stat-box stat-total" onclick="window.location='?status=All'">
                    <h3><?php echo $totalCount; ?></h3>
                    <p>📊 Total</p>
                </div>
            </div>
            <div class="col-md-2 mb-2">
                <div class="stat-box stat-pending" onclick="window.location='?status=Pending'">
                    <h3><?php echo $pendingCount; ?></h3>
                    <p>⏳ Pending</p>
                </div>
            </div>
            <div class="col-md-2 mb-2">
                <div class="stat-box stat-success" onclick="window.location='?status=Success'">
                    <h3><?php echo $successCount; ?></h3>
                    <p>✅ Success</p>
                </div>
            </div>
            <div class="col-md-2 mb-2">
                <div class="stat-box stat-rejected" onclick="window.location='?status=Rejected'">
                    <h3><?php echo $rejectedCount; ?></h3>
                    <p>❌ Rejected</p>
                </div>
            </div>
            <div class="col-md-2 mb-2">
                <div class="stat-box stat-today">
                    <h3><?php echo $todayCount; ?></h3>
                    <p>📅 Today</p>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-dark text-white py-2">
                <span><i class="fas fa-graduation-cap"></i> LL Request Management</span>
            </div>
            <div class="card-body p-2">
                <!-- Tabs -->
                <div class="tab-nav">
                    <button class="tab-btn <?php echo $status_filter=='Pending'?'active':''; ?>" onclick="window.location='?status=Pending'">
                        ⏳ Pending (<?php echo $pendingCount; ?>)
                    </button>
                    <button class="tab-btn <?php echo $status_filter=='Success'?'active':''; ?>" onclick="window.location='?status=Success'">
                        ✅ Success (<?php echo $successCount; ?>)
                    </button>
                    <button class="tab-btn <?php echo $status_filter=='Rejected'?'active':''; ?>" onclick="window.location='?status=Rejected'">
                        ❌ Rejected (<?php echo $rejectedCount; ?>)
                    </button>
                </div>

                <!-- Search & Filters -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <form method="GET" class="input-group">
                            <input type="hidden" name="status" value="<?php echo $status_filter; ?>">
                            <input type="text" name="search" class="form-control" placeholder="Search Order ID, App No, Username..." value="<?php echo $search; ?>">
                            <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button>
                        </form>
                    </div>
                    <div class="col-md-3">
                        <select class="form-control" onchange="window.location='?status=<?php echo $status_filter; ?>&limit='+this.value">
                            <option value="25" <?php echo $limit==25?'selected':''; ?>>25 per page</option>
                            <option value="50" <?php echo $limit==50?'selected':''; ?>>50 per page</option>
                            <option value="100" <?php echo $limit==100?'selected':''; ?>>100 per page</option>
                            <option value="99999" <?php echo $limit==99999?'selected':''; ?>>All</option>
                        </select>
                    </div>
                    <div class="col-md-3 text-right">
                        <strong>Total: <?php echo $total; ?> records</strong>
                    </div>
                </div>

                <!-- Table -->
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead class="bg-light">
                            <tr>
                                <th>#</th>
                                <th>Order ID</th>
                                <th>User</th>
                                <th>App Number</th>
                                <th>State</th>
                                <th>DOB</th>
                                <th>Amount</th>
                                <th>Date</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($records) > 0): ?>
                                <?php $sr = $offset + 1; ?>
                                <?php while($rec = mysqli_fetch_assoc($records)): ?>
                                <tr>
                                    <td><?php echo $sr++; ?></td>
                                    <td>
                                        <code><?php echo $rec['order_id']; ?></code>
                                        <button class="copy-btn" onclick="copyText('<?php echo $rec['order_id']; ?>')">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </td>
                                    <td>
                                        <strong><?php echo $rec['username']; ?></strong><br>
                                        <small><?php echo $rec['mobile']; ?></small>
                                    </td>
                                    <td>
                                        <code><?php echo $rec['application_number']; ?></code>
                                        <button class="copy-btn" onclick="copyText('<?php echo $rec['application_number']; ?>')">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </td>
                                    <td><?php echo $rec['state']; ?></td>
                                    <td>
                                        <code><?php echo $rec['dob']; ?></code>
                                        <button class="copy-btn" onclick="copyText('<?php echo $rec['dob']; ?>')">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </td>
                                    <td><strong>₹<?php echo $rec['amount']; ?></strong></td>
                                    <td><small><?php echo date('d M Y', strtotime($rec['request_date'])); ?></small></td>
                                    <td>
                                        <?php if($rec['status']=='Pending'): ?>
                                            <span class="badge badge-warning">Pending</span>
                                        <?php elseif($rec['status']=='Success'): ?>
                                            <span class="badge badge-success">Success</span>
                                        <?php else: ?>
                                            <span class="badge badge-danger">Rejected</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if($rec['status']=='Pending'): ?>
                                            <button class="btn btn-sm btn-primary" onclick="toggleAction(<?php echo $rec['id']; ?>)">
                                                <i class="fas fa-cog"></i>
                                            </button>
                                        <?php elseif($rec['status']=='Success'): ?>
                                            <a href="../uploads/ll_results/<?php echo $rec['result_file']; ?>" target="_blank" class="btn btn-sm btn-success">
                                                <i class="fas fa-download"></i>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-muted" title="<?php echo $rec['rejection_reason']; ?>">
                                                <i class="fas fa-info-circle"></i>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                
                                <?php if($rec['status']=='Pending'): ?>
                                <tr id="action_<?php echo $rec['id']; ?>" style="display:none;">
                                    <td colspan="10">
                                        <div class="action-panel show">
                                            <form method="POST" enctype="multipart/form-data">
                                                <input type="hidden" name="request_id" value="<?php echo $rec['id']; ?>">
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <h6 class="text-success">✅ Approve Request</h6>
                                                        <div class="mb-2">
                                                            <label><small>Upload Result File (PDF/JPG/PNG)</small></label>
                                                            <input type="file" name="result_file" class="form-control form-control-sm" accept=".pdf,.jpg,.jpeg,.png">
                                                        </div>
                                                        <button type="submit" name="update_status" value="submit" class="btn btn-success btn-sm" onclick="this.form.action.value='success'">
                                                            <i class="fas fa-check"></i> Approve
                                                        </button>
                                                        <input type="hidden" name="action" value="">
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <h6 class="text-danger">❌ Reject Request</h6>
                                                        <div class="mb-2">
                                                            <label><small>Rejection Reason</small></label>
                                                            <textarea name="rejection_reason" class="form-control form-control-sm" rows="2" placeholder="Enter reason..."></textarea>
                                                        </div>
                                                        <button type="submit" name="update_status" value="submit" class="btn btn-danger btn-sm" onclick="this.form.action.value='reject'; return confirm('Reject & Refund ₹<?php echo $rec['amount']; ?>?')">
                                                            <i class="fas fa-times"></i> Reject & Refund
                                                        </button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                                
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="10" class="text-center py-4">
                                        <i class="fas fa-inbox fa-3x text-muted mb-2"></i>
                                        <h5 class="text-muted">No Records Found</h5>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if($total > $limit): ?>
                <div class="text-center mt-3">
                    <?php
                    $totalPages = ceil($total / $limit);
                    for($i=1; $i<=$totalPages; $i++):
                    ?>
                        <a href="?status=<?php echo $status_filter; ?>&page=<?php echo $i; ?>&limit=<?php echo $limit; ?>&search=<?php echo $search; ?>" 
                           class="btn btn-sm <?php echo $page==$i?'btn-primary':'btn-outline-primary'; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function toggleAction(id) {
    var row = document.getElementById('action_' + id);
    row.style.display = (row.style.display === 'none') ? 'table-row' : 'none';
}

function copyText(text) {
    navigator.clipboard.writeText(text).then(function() {
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'Copied!',
            showConfirmButton: false,
            timer: 1000
        });
    });
}
</script>

<?php include('../admin/footers.php'); ?>