<?php
require_once 'config/db.php';

// Handle Bulk Action (Delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && !empty($_POST['selected_enquiries'])) {
    $action = $_POST['bulk_action'];
    $enq_ids = array_map('intval', $_POST['selected_enquiries']);
    $ids_string = implode(',', $enq_ids);
    
    try {
        if ($action === 'delete') {
             $pdo->query("UPDATE enquiries SET status = 'junk' WHERE id IN ($ids_string)");
             $msg = "bulk_deleted";
             header("Location: enquiries.php?msg=$msg");
             exit;
        }
    } catch (PDOException $e) {
        $error = "Bulk Error: " . $e->getMessage();
    }
}

// Handle Single Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("UPDATE enquiries SET status = 'junk' WHERE id = ?");
        $stmt->execute([$id]);
        $msg = "deleted";
        header("Location: enquiries.php?msg=$msg");
        exit;
    } catch (PDOException $e) {
        $error = "Error deleting enquiry: " . $e->getMessage();
    }
}

if (isset($_GET['msg'])) {
    if ($_GET['msg'] === 'deleted') {
        $success = "Enquiry deleted successfully.";
    } elseif ($_GET['msg'] === 'bulk_deleted') {
        $success = "Selected enquiries successfully deleted.";
    }
}

// Fetch all enquiries (only pending ones)
$enquiries = [];
$query = "SELECT * FROM enquiries WHERE status = 'pending' ORDER BY created_at DESC";
$stmt = $pdo->query($query);
if ($stmt) {
    $enquiries = $stmt->fetchAll();
}
if (!$enquiries) {
    $enquiries = [];
}

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-envelope-open-text"></i> Enquiries</h2>
        <p>Manage quotes and messages received from the public website.</p>
    </div>

    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Enquiries Table -->
    <style>
        .btn-3d {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.1s ease;
            position: relative;
            top: 0;
            border: none;
            cursor: pointer;
            margin-left: 8px;
        }
        .btn-3d-view {
            background-color: #3b82f6;
            color: #ffffff;
            box-shadow: 0 4px 0 #2563eb, 0 5px 8px rgba(0,0,0,0.15);
        }
        .btn-3d-view:active {
            top: 4px;
            box-shadow: 0 0 0 #2563eb, 0 1px 2px rgba(0,0,0,0.15);
        }
        .btn-3d-convert {
            background-color: #10b981;
            color: #ffffff;
            box-shadow: 0 4px 0 #059669, 0 5px 8px rgba(0,0,0,0.15);
        }
        .btn-3d-convert:active {
            top: 4px;
            box-shadow: 0 0 0 #059669, 0 1px 2px rgba(0,0,0,0.15);
        }
        .btn-3d-delete {
            background-color: #ef4444;
            color: #ffffff;
            box-shadow: 0 4px 0 #dc2626, 0 5px 8px rgba(0,0,0,0.15);
        }
        .btn-3d-delete:active {
            top: 4px;
            box-shadow: 0 0 0 #dc2626, 0 1px 2px rgba(0,0,0,0.15);
        }
        .custom-checkbox {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: var(--primary);
        }
        
        @media (max-width: 768px) {
            /* Force compact ROW view — override the global card transform */
            .admin-table, .admin-table thead, .admin-table tbody,
            .admin-table th, .admin-table td, .admin-table tr {
                display: revert !important;
            }
            .admin-table { width:100%; border-collapse:collapse; }
            .admin-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
            .admin-table th, .admin-table td {
                padding: 10px 5px !important;
                font-size: 0.78rem !important;
                vertical-align: middle !important;
                min-height: auto !important;
                padding-left: 5px !important;
                border-bottom: 1px solid #f1f5f9 !important;
                border: none !important;
                border-bottom: 1px solid #f1f5f9 !important;
            }
            .admin-table tr {
                border: none !important;
                border-radius: 0 !important;
                margin-bottom: 0 !important;
                padding: 0 !important;
                box-shadow: none !important;
                display: table-row !important;
            }
            .admin-table td:before { display: none !important; content: none !important; }

            .mobile-actions-grid {
                display: flex !important;
                flex-direction: row !important;
                justify-content: flex-end !important;
                align-items: center !important;
                gap: 4px !important;
                padding-right: 8px !important;
                padding-left: 0 !important;
                width: auto !important;
            }
            .mobile-actions-grid .btn-3d { margin: 0 !important; width: 32px !important; height: 32px !important; font-size: 0.75rem !important; }
            .btn-3d { width: 32px !important; height: 32px !important; font-size: 0.75rem !important; margin-left: 3px !important; }
            
            .hide-mobile-text { display: none; }
            .dashboard-content { padding: 10px !important; }
        }
    </style>
    <div class="recent-activity" style="padding: 0;">
        <form action="enquiries.php" method="POST" id="bulkForm">
            <div style="padding: 15px 20px; background: #f8fafc; border-bottom: 2px solid var(--border); display: flex; align-items: center; justify-content: space-between; border-top-left-radius: 12px; border-top-right-radius: 12px;">
                <label style="display: flex; align-items: center; cursor: pointer; font-weight: 700; color: var(--dark); font-size: 0.9rem;">
                    <input type="checkbox" id="selectAll" class="custom-checkbox" style="margin-right: 10px;"> Select All
                </label>
                <div style="display:flex; gap:10px;">
                    <button type="submit" name="bulk_action" value="delete" class="btn-3d btn-3d-delete" style="width: auto; padding: 0 15px; font-weight: 700; font-size: 0.8rem; height: 35px; margin: 0; border-radius:10px;" onclick="return confirm('Permanently junk selected enquiries?');">
                        <i class="fa-solid fa-trash-can"></i> <span class="hide-mobile">Bulk Junk</span>
                    </button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="padding-left: 15px; width: 30px;"></th>
                            <th style="width: 40px;">S.No</th>
                            <th>Contact</th>
                            <th style="padding-right: 15px; text-align: right;"><span class="hide-mobile-text">Actions</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($enquiries) > 0): ?>
                            <?php $sno = 1; foreach ($enquiries as $enq): ?>
                                <?php 
                                // Prepare data for the modal
                                $enq_json = htmlspecialchars(json_encode([
                                    'id' => $enq['id'],
                                    'name' => $enq['full_name'],
                                    'phone' => $enq['phone'],
                                    'email' => $enq['email'] ?? 'N/A',
                                    'service' => $enq['service_type'] ?? 'General Inquiry',
                                    'message' => $enq['message'],
                                    'date' => date('d M Y, h:i A', strtotime($enq['created_at']))
                                ]));
                                ?>
                                <tr>
                                    <td style="padding-left: 20px;" data-label="Select">
                                        <input type="checkbox" name="selected_enquiries[]" value="<?= $enq['id'] ?>" class="custom-checkbox enq-checkbox">
                                    </td>
                                    <td data-label="S.No" style="color:#64748b; font-weight:600;">
                                        #<?= $sno++ ?>
                                    </td>
                                    <td data-label="Contact Number" style="font-weight:800; color:var(--primary); font-size:1.05rem;">
                                        <?= htmlspecialchars($enq['phone']) ?>
                                    </td>
                                    <td style="text-align: right; padding-right: 20px;" class="mobile-actions-grid" data-label="Actions">
                                        <button type="button" class="btn-3d btn-3d-view" title="View Full Details" onclick='openEnqModal(<?= $enq_json ?>)'>
                                            <i class="fa-solid fa-eye"></i>
                                        </button>
                                        <a href="lead_add_edit.php?enquiry_id=<?= $enq['id'] ?>" class="btn-3d btn-3d-convert" title="Edit / Convert to Lead" style="background-color:#18aadf; box-shadow: 0 4px 0 #0e7490, 0 5px 8px rgba(0,0,0,0.15);">
                                            <i class="fa-solid fa-pen-to-square"></i>
                                        </a>
                                        <a href="enquiries.php?delete=<?= $enq['id'] ?>" class="btn-3d btn-3d-delete" title="Junk Enquiry" onclick="return confirm('Junk this enquiry?');">
                                            <i class="fa-solid fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: #94a3b8; padding: 60px 20px;">
                                    <div style="font-size: 3rem; margin-bottom: 20px; color: #e2e8f0;"><i class="fa-solid fa-inbox"></i></div>
                                    <div style="font-weight:700; font-size:1.1rem;">Your inbox is empty.</div>
                                    <div style="font-size:0.9rem;">No pending enquiries to show.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>
</div>

<!-- Enquiry Detail View Modal -->
<div id="enqDetailModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); z-index:9999; align-items:center; justify-content:center; padding:15px; backdrop-filter: blur(4px);">
    <div style="background:#fff; border-radius:20px; width:100%; max-width:550px; box-shadow:0 25px 50px -12px rgba(0,0,0,0.25); overflow:hidden; animation: modalSlideUp 0.3s ease-out;">
        <div style="background:var(--primary); padding:20px 25px; display:flex; justify-content:space-between; align-items:center;">
            <h3 style="margin:0; color:#fff; font-weight:800; font-size:1.2rem;"><i class="fa-solid fa-circle-info" style="margin-right:10px;"></i>Enquiry Details</h3>
            <button onclick="closeEnqModal()" style="background:rgba(255,255,255,0.2); border:none; color:#fff; width:30px; height:30px; border-radius:50%; cursor:pointer; display:flex; align-items:center; justify-content:center; font-size:1.2rem;">&times;</button>
        </div>
        
        <div style="padding:25px; max-height:80vh; overflow-y:auto;">
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px; margin-bottom:25px;">
                <div style="grid-column: 1/-1; background:#f8fafc; padding:15px; border-radius:12px; border:1px solid #e2e8f0;">
                    <div style="font-size:0.7rem; font-weight:800; color:#64748b; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:5px;">Lead Name</div>
                    <div id="m_name" style="font-size:1.15rem; font-weight:800; color:var(--dark);">N/A</div>
                </div>
                <div>
                    <div style="font-size:0.7rem; font-weight:800; color:#64748b; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:5px;">Phone Number</div>
                    <div id="m_phone" style="font-weight:700; color:var(--primary);">N/A</div>
                </div>
                <div>
                    <div style="font-size:0.7rem; font-weight:800; color:#64748b; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:5px;">Email Address</div>
                    <div id="m_email" style="font-weight:600;">N/A</div>
                </div>
                <div>
                    <div style="font-size:0.7rem; font-weight:800; color:#64748b; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:5px;">Service Type</div>
                    <div id="m_service" style="font-weight:700; color:#1e293b;">N/A</div>
                </div>
                <div>
                    <div style="font-size:0.7rem; font-weight:800; color:#64748b; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:5px;">Received On</div>
                    <div id="m_date" style="font-weight:600; color:#64748b;">N/A</div>
                </div>
            </div>
            
            <div style="background:#fff9f2; padding:20px; border-radius:12px; border:1px solid #fde68a;">
                <div style="font-size:0.7rem; font-weight:800; color:#b45309; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:8px;"><i class="fa-solid fa-comment-dots"></i> Message Content</div>
                <div id="m_message" style="line-height:1.6; color:#1e293b; white-space:pre-wrap;">N/A</div>
            </div>
        </div>
        
        <div style="padding:20px 25px; background:#f8fafc; border-top:1px solid #e2e8f0; display:flex; justify-content:flex-end; gap:12px;">
            <button onclick="closeEnqModal()" style="padding:10px 20px; background:#fff; border:1.5px solid #e2e8f0; border-radius:10px; font-weight:700; color:#64748b; cursor:pointer;">Close</button>
            <a id="m_convert_link" href="#" style="padding:10px 20px; background:var(--primary); color:#fff; text-decoration:none; border-radius:10px; font-weight:700; box-shadow: 0 4px 10px rgba(24, 170, 223, 0.3);">Edit / Convert</a>
        </div>
    </div>
</div>

<style>
@keyframes modalSlideUp {
    from { transform: translateY(30px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}
@media (max-width: 600px) {
    .hide-mobile { display: none; }
}
</style>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.enq-checkbox');
    checkboxes.forEach(cb => cb.checked = this.checked);
});

function openEnqModal(data) {
    document.getElementById('m_name').textContent = data.name || 'N/A';
    document.getElementById('m_phone').textContent = data.phone || 'N/A';
    document.getElementById('m_email').textContent = data.email || 'N/A';
    document.getElementById('m_service').textContent = data.service || 'Inquiry';
    document.getElementById('m_message').textContent = data.message || 'No message provided.';
    document.getElementById('m_date').textContent = data.date || 'N/A';
    
    document.getElementById('m_convert_link').href = 'lead_add_edit.php?enquiry_id=' + data.id;
    
    document.getElementById('enqDetailModal').style.display = 'flex';
}

function closeEnqModal() {
    document.getElementById('enqDetailModal').style.display = 'none';
}
</script>

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