<?php 
/**
 * view_connection_requests.php - নতুন কানেকশন রিকোয়েস্ট দেখার পেজ (সার্চ ও ইন-প্রগ্রেস ফিচার সহ)
 */

// যদি এই ফাইলটি সরাসরি ব্রাউজারে ওপেন করা হয় (admin.php ছাড়া), তবেই কেবল db_config ইনক্লুড হবে
if (!isset($conn)) {
    include('db_config.php');
}

// সেশন চেক
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['admin_logged_in'])) {
    header('location: login.php');
    exit();
}

// স্ট্যাটাস এবং নোট আপডেট লজিক
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_status'])) {
    $id = mysqli_real_escape_string($conn, $_POST['request_id']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $admin_note = mysqli_real_escape_string($conn, $_POST['admin_note']);
    
    $update_query = "UPDATE registrations SET status = '$status', admin_note = '$admin_note' WHERE id = '$id'";
    if (mysqli_query($conn, $update_query)) {
        echo "<script>alert('স্ট্যাটাস সফলভাবে আপডেট করা হয়েছে।'); window.location='admin.php?view=connection_requests';</script>";
    }
}

// ডিলিট লজিক
if (isset($_GET['delete_id'])) {
    $id = mysqli_real_escape_string($conn, $_GET['delete_id']);
    $delete_query = "DELETE FROM registrations WHERE id = '$id'";
    if (mysqli_query($conn, $delete_query)) {
        echo "<script>alert('রিকোয়েস্টটি সফলভাবে মুছে ফেলা হয়েছে।'); window.location='admin.php?view=connection_requests';</script>";
    }
}

// ড্যাশবোর্ড রিপোর্ট ডাটা সংগ্রহ
$total_req = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM registrations"))['total'];
$pending_req = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM registrations WHERE status = 'Pending' OR status = '' OR status IS NULL"))['total'];
$progress_req = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM registrations WHERE status = 'In Progress'"))['total'];
$completed_req = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM registrations WHERE status = 'Completed'"))['total'];
$canceled_req = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM registrations WHERE status = 'Canceled'"))['total'];

// ডাটাবেস থেকে সকল রিকোয়েস্ট সংগ্রহ
$sql = "SELECT * FROM registrations ORDER BY created_at DESC";
$result = mysqli_query($conn, $sql);
$total_rows = mysqli_num_rows($result);
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    :root {
        --primary: #00aeef;
        --success: #28a745;
        --warning: #ffc107;
        --info: #17a2b8;
        --danger: #dc3545;
        --dark: #1a1a1a;
    }
    .admin-container {
        padding: 0;
        min-height: 100vh;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    /* Dashboard Stats */
    .dashboard-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 15px;
        margin-bottom: 25px;
    }
    .stat-card {
        background: white;
        padding: 15px;
        border-radius: 15px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        display: flex;
        align-items: center;
        transition: transform 0.3s;
    }
    .stat-card:hover { transform: translateY(-5px); }
    .stat-icon {
        width: 45px;
        height: 45px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
        margin-right: 12px;
    }
    .stat-info h3 { margin: 0; font-size: 1.3rem; color: #333; }
    .stat-info p { margin: 0; color: #777; font-size: 0.8rem; }

    /* Search & Filter */
    .filter-section {
        background: white;
        padding: 15px 25px;
        border-radius: 15px 15px 0 0;
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        align-items: center;
        border-bottom: 1px solid #edf2f7;
    }
    .search-box {
        position: relative;
        flex: 1;
        min-width: 250px;
    }
    .search-box i {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #94a3b8;
    }
    .search-input {
        width: 90%;
        padding: 10px 10px 10px 35px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        outline: none;
    }
    .filter-select {
        padding: 10px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        outline: none;
        min-width: 150px;
    }

    /* Table Design */
    .table-card {
        background: white;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        padding: 0;
        overflow: hidden;
    }
    .table-header {
        padding: 20px 25px;
        border-bottom: 1px solid #edf2f7;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .page-title {
        font-size: 1.4rem;
        font-weight: 700;
        color: var(--dark);
        margin: 0;
    }
    .custom-table {
        width: 100%;
        border-collapse: collapse;
    }
    .custom-table th {
        background: #f8fafc;
        padding: 15px 20px;
        text-align: left;
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
        border-bottom: 2px solid #edf2f7;
    }
    .custom-table td {
        padding: 18px 20px;
        border-bottom: 1px solid #f1f5f9;
        vertical-align: middle;
    }
    .custom-table tr:last-child td { border-bottom: none; }
    
    /* Status Badges */
    .status-badge {
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 700;
        display: inline-block;
    }
    .status-pending { background: #fff8e1; color: #f59e0b; }
    .status-in-progress { background: #e0f2fe; color: #0284c7; }
    .status-completed { background: #ecfdf5; color: #10b981; }
    .status-canceled { background: #fef2f2; color: #ef4444; }

    .btn-action {
        width: 35px;
        height: 35px;
        border-radius: 8px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin-right: 5px;
        transition: 0.2s;
        border: none;
        cursor: pointer;
    }
    .btn-edit { background: #f1f5f9; color: #475569; }
    .btn-delete { background: #fee2e2; color: #dc2626; }
    
    /* Modal Styling */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0; top: 0;
        width: 100%; height: 100%;
        background: rgba(0,0,0,0.5);
    }
    .modal-content {
        background: white;
        margin: 10% auto;
        padding: 25px;
        border-radius: 15px;
        width: 90%;
        max-width: 450px;
        box-shadow: 0 20px 50px rgba(0,0,0,0.2);
    }
    .form-control {
        width: 100%;
        padding: 10px;
        margin: 10px 0;
        border: 1px solid #ddd;
        border-radius: 8px;
    }
</style>

<div class="admin-container">
    <div class="container-fluid">
        
        <!-- ড্যাশবোর্ড রিপোর্ট ড্যাশবোর্ড -->
        <div class="dashboard-row">
            <div class="stat-card">
                <div class="stat-icon" style="background: #f1f5f9; color: #475569;"><i class="fas fa-list"></i></div>
                <div class="stat-info"><h3><?php echo $total_req; ?></h3><p>মোট আবেদন</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: #fff8e1; color: #f59e0b;"><i class="fas fa-clock"></i></div>
                <div class="stat-info"><h3><?php echo $pending_req; ?></h3><p>পেন্ডিং</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: #e0f2fe; color: #0284c7;"><i class="fas fa-tools"></i></div>
                <div class="stat-info"><h3><?php echo $progress_req; ?></h3><p>কাজ চলছে</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: #ecfdf5; color: #10b981;"><i class="fas fa-check-circle"></i></div>
                <div class="stat-info"><h3><?php echo $completed_req; ?></h3><p>সম্পন্ন</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: #fef2f2; color: #ef4444;"><i class="fas fa-times-circle"></i></div>
                <div class="stat-info"><h3><?php echo $canceled_req; ?></h3><p>বাতিল</p></div>
            </div>
        </div>

        <div class="table-card">
            <div class="table-header">
                <h2 class="page-title">কানেকশন রিকোয়েস্ট তালিকা</h2>
                <span style="color: #64748b; font-size: 0.9rem;">সর্বমোট: <?php echo $total_rows; ?> টি</span>
            </div>

            <!-- সার্চ ও ফিল্টার এরিয়া -->
            <div class="filter-section">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchInput" class="search-input" placeholder="নাম বা মোবাইল নম্বর দিয়ে খুঁজুন..." onkeyup="filterTable()">
                </div>
                <select id="statusFilter" class="filter-select" onchange="filterTable()">
                    <option value="">সকল স্ট্যাটাস</option>
                    <option value="Pending">পেন্ডিং</option>
                    <option value="In Progress">কাজ চলছে</option>
                    <option value="Completed">সম্পন্ন</option>
                    <option value="Canceled">বাতিল</option>
                </select>
            </div>
            
            <div style="overflow-x: auto;">
                <table class="custom-table" id="requestTable">
                    <thead>
                        <tr>
                            <th>ক্রমিক</th>
                            <th>গ্রাহকের তথ্য</th>
                            <th>যোগাযোগ</th>
                            <th>প্যাকেজ ও সময়</th>
                            <th>ঠিকানা ও লোকেশন</th>
                            <th>অবস্থা</th>
                            <th>অ্যাকশন</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($total_rows > 0): 
                            $serial = $total_rows;
                            while($row = mysqli_fetch_assoc($result)): 
                                $status = $row['status'] ?: 'Pending';
                                $status_display = 'পেন্ডিং';
                                if($status == 'In Progress') $status_display = 'কাজ চলছে';
                                if($status == 'Completed') $status_display = 'সম্পন্ন';
                                if($status == 'Canceled') $status_display = 'বাতিল';
                                
                                $status_class = 'status-' . strtolower(str_replace(' ', '-', $status));
                        ?>
                            <tr class="request-row">
                                <td style="font-weight: bold; color: #94a3b8;"><?php echo str_pad($serial--, 2, "0", STR_PAD_LEFT); ?></td>
                                <td class="search-name">
                                    <div style="font-weight: 700; color: #1e293b;"><?php echo htmlspecialchars($row['name']); ?></div>
                                    <div style="font-size: 0.8rem; color: #64748b; margin-top: 2px;">NID: <?php echo htmlspecialchars($row['nid_number'] ?: 'N/A'); ?></div>
                                    <div style="font-size: 0.75rem; color: var(--primary);">Ref: <?php echo htmlspecialchars($row['reference_user'] ?: 'N/A'); ?></div>
                                </td>
                                <td class="search-phone">
                                    <a href="tel:<?php echo $row['phone']; ?>" style="text-decoration: none; color: #0284c7; font-weight: 600;">
                                        <i class="fas fa-phone-alt" style="font-size: 0.8rem;"></i> <?php echo htmlspecialchars($row['phone']); ?>
                                    </a>
                                </td>
                                <td>
                                    <span style="background: #f1f5f9; padding: 4px 8px; border-radius: 6px; font-size: 0.8rem; font-weight: 600; color: #475569;">
                                        <?php echo htmlspecialchars($row['package']); ?>
                                    </span>
                                    <div style="font-size: 0.75rem; color: #94a3b8; margin-top: 5px;">
                                        <i class="far fa-clock"></i> <?php echo htmlspecialchars($row['contact_time']); ?>
                                    </div>
                                </td>
                                <td style="max-width: 250px;">
                                    <div style="font-size: 0.85rem; line-height: 1.4;"><?php echo nl2br(htmlspecialchars($row['address'])); ?></div>
                                    <?php if(!empty($row['latitude'])): ?>
                                        <a href="https://www.google.com/maps/search/?api=1&query=<?php echo $row['latitude']; ?>,<?php echo $row['longitude']; ?>" 
                                           target="_blank" style="font-size: 0.75rem; color: #4285F4; text-decoration: none; margin-top: 5px; display: inline-block;">
                                            <i class="fas fa-map-marked-alt"></i> ম্যাপে দেখুন
                                        </a>
                                    <?php endif; ?>
                                </td>
                                <td class="search-status" data-status="<?php echo $status; ?>">
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo $status_display; ?>
                                    </span>
                                    <?php if(!empty($row['admin_note'])): ?>
                                        <div style="font-size: 0.7rem; color: #94a3b8; font-style: italic; margin-top: 4px;">
                                            নোট: <?php echo htmlspecialchars($row['admin_note']); ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button class="btn-action btn-edit" title="আপডেট করুন" 
                                            onclick="openStatusModal('<?php echo $row['id']; ?>', '<?php echo $status; ?>', '<?php echo htmlspecialchars($row['admin_note']); ?>')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a href="?delete_id=<?php echo $row['id']; ?>" class="btn-action btn-delete" title="মুছে ফেলুন" 
                                       onclick="return confirm('আপনি কি নিশ্চিত যে এই রিকোয়েস্টটি মুছে ফেলতে চান?')">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" style="text-align: center; padding: 50px; color: #94a3b8;">
                                    <i class="fas fa-folder-open" style="font-size: 3rem; display: block; margin-bottom: 10px; opacity: 0.3;"></i>
                                    কোন নতুন কানেকশন রিকোয়েস্ট পাওয়া যায়নি।
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Status Update Modal -->
<div id="statusModal" class="modal">
    <div class="modal-content">
        <h3 style="margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px;">রিকোয়েস্ট আপডেট</h3>
        <form method="POST">
            <input type="hidden" name="request_id" id="modal_request_id">
            <label style="font-weight: 600; font-size: 0.9rem;">কানেকশন স্ট্যাটাস:</label>
            <select name="status" id="modal_status" class="form-control">
                <option value="Pending">Pending (পেন্ডিং)</option>
                <option value="In Progress">In Progress (কাজ চলছে)</option>
                <option value="Completed">Completed (সম্পন্ন)</option>
                <option value="Canceled">Canceled (বাতিল)</option>
            </select>
            
            <label style="font-weight: 600; font-size: 0.9rem;">অ্যাডমিন নোট:</label>
            <textarea name="admin_note" id="modal_note" class="form-control" rows="3" placeholder="কেন বাতিল বা সম্পন্ন হলো তার নোট..."></textarea>
            
            <div style="display: flex; gap: 10px; margin-top: 15px;">
                <button type="submit" name="update_status" style="flex: 1; padding: 10px; background: var(--success); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold;">সংরক্ষণ করুন</button>
                <button type="button" onclick="closeModal()" style="flex: 1; padding: 10px; background: #e2e8f0; color: #475569; border: none; border-radius: 8px; cursor: pointer;">বন্ধ করুন</button>
            </div>
        </form>
    </div>
</div>

<script>
    function openStatusModal(id, status, note) {
        document.getElementById('modal_request_id').value = id;
        document.getElementById('modal_status').value = status;
        document.getElementById('modal_note').value = note;
        document.getElementById('statusModal').style.display = 'block';
    }

    function closeModal() {
        document.getElementById('statusModal').style.display = 'none';
    }

    // টেবিল ফিল্টার ফাংশন
    function filterTable() {
        let searchValue = document.getElementById('searchInput').value.toLowerCase();
        let statusFilter = document.getElementById('statusFilter').value;
        let rows = document.querySelectorAll('.request-row');

        rows.forEach(row => {
            let name = row.querySelector('.search-name').textContent.toLowerCase();
            let phone = row.querySelector('.search-phone').textContent.toLowerCase();
            let status = row.querySelector('.search-status').getAttribute('data-status');

            let matchesSearch = name.includes(searchValue) || phone.includes(searchValue);
            let matchesStatus = statusFilter === "" || status === statusFilter;

            if (matchesSearch && matchesStatus) {
                row.style.display = "";
            } else {
                row.style.display = "none";
            }
        });
    }

    window.onclick = function(event) {
        let modal = document.getElementById('statusModal');
        if (event.target == modal) {
            closeModal();
        }
    }
</script>