<?php
// Initialize the session
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Check if the user is logged in, if not then redirect to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

// Include config file
require_once "includes/config.php";

// Set page title
$page_title = "Manage Contact Submissions";

// Define variables and initialize with empty values
$search = "";
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(isset($_POST['search'])) {
        $search = trim($_POST["search"]);
    }
}

// Prepare a select statement - using the correct table name 'contact_submissions'
$sql = "SELECT id, name, email, phone, message, submission_date, status FROM contact_submissions WHERE 1=1";
$params = array();
$types = "";

// Add search condition
if(!empty($search)){
    $sql .= " AND (name LIKE ? OR email LIKE ? OR message LIKE ?)";
    $search_param = "%$search%";
    $params[] = &$search_param;
    $params[] = &$search_param;
    $params[] = &$search_param;
    $types .= "sss";
}

// Add status filter
if(!empty($status_filter) && in_array($status_filter, ['new', 'read', 'replied'])) {
    $sql .= " AND status = ?";
    $params[] = &$status_filter;
    $types .= "s";
}

$sql .= " ORDER BY submission_date DESC";

// Prepare the statement
$stmt = $conn->prepare($sql);

// Bind parameters if any
if(!empty($params)) {
    $bind_names[] = $types;
    for ($i=0; $i<count($params); $i++) {
        $bind_name = 'bind' . $i;
        $$bind_name = $params[$i];
        $bind_names[] = &$$bind_name;
    }
    call_user_func_array(array($stmt, 'bind_param'), $bind_names);
}

// Execute the statement
$stmt->execute();

// Fetch results using bind_result (instead of get_result)
$stmt->store_result();
$stmt->bind_result($id, $name, $email, $phone, $message, $submission_date, $status);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $page_title; ?> - Real Estate Admin</title>
    
    <!-- Favicon -->
    <link rel="icon" href="../images/favicon.ico">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Custom CSS -->
    <link href="../css/admin.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --info-color: #4895ef;
            --warning-color: #f4a261;
            --danger-color: #e76f51;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --sidebar-width: 250px;
            --header-height: 60px;
        }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f7fb; color: #333; overflow-x: hidden; }
        .sidebar { width: var(--sidebar-width); height: 100vh; position: fixed; left: 0; top: 0; background: linear-gradient(180deg, #2b2d42 0%, #1a1a2e 100%); color: #fff; transition: all 0.3s; z-index: 1000; box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1); }
        .sidebar-brand { padding: 1.5rem 1rem; font-size: 1.25rem; font-weight: 600; color: #fff; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .nav-link { color: rgba(255,255,255,0.8); padding: 0.75rem 1.5rem; margin: 0.25rem 0.5rem; border-radius: 0.5rem; transition: all 0.3s; }
        .nav-link:hover, .nav-link.active { background-color: rgba(255,255,255,0.1); color: #fff; text-decoration: none; }
        .main-content { margin-left: var(--sidebar-width); padding: 2rem; min-height: 100vh; transition: all 0.3s; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; padding-bottom: 1rem; border-bottom: 1px solid #e9ecef; }
        .page-title { font-size: 1.75rem; font-weight: 600; margin: 0; color: #2b2d42; }
        .card { border: none; border-radius: 0.75rem; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); margin-bottom: 1.5rem; transition: transform 0.2s, box-shadow 0.2s; }
        .card:hover { transform: translateY(-2px); box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.1); }
        .table th { border-top: none; font-weight: 600; color: #6c757d; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; background-color: #f8f9fa; }
        .table td { vertical-align: middle; }
        .badge { font-weight: 500; padding: 0.35em 0.65em; font-size: 0.8em; color:#000 !important;}
        .badge-new { background-color: #d1e7dd; color: #0f5132; }
        .badge-read { background-color: #cfe2ff; color: #084298; }
        .badge-replied { background-color: #fff3cd; color: #664d03; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.8rem; }
        @media (max-width: 768px) { .sidebar { left: calc(-1 * var(--sidebar-width)); } .sidebar.show { left: 0; } .main-content { margin-left: 0; } .main-content.active { margin-left: var(--sidebar-width); } }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="d-flex flex-column h-100">
            <div class="sidebar-brand"><span>Real Estate</span></div>
            <div class="sidebar-nav flex-grow-1">
                <ul class="nav flex-column">
                    <li class="nav-item"><a href="index.php" class="nav-link"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
                    <li class="nav-item"><a href="contacts.php" class="nav-link active"><i class="fas fa-envelope"></i> Contact Messages</a></li>
                </ul>
            </div>
            <div class="mt-auto p-3">
                <div class="d-flex align-items-center">
                    <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($_SESSION['username']); ?>" class="rounded-circle me-2" width="40" height="40" alt="User">
                    <div>
                        <div class="fw-bold text-white"><?php echo htmlspecialchars($_SESSION['username']); ?></div>
                        <small class="text-white-50">Admin</small>
                    </div>
                    <a href="logout.php" class="ms-auto text-white-50" title="Logout"><i class="fas fa-sign-out-alt"></i></a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="page-header">
            <h1 class="page-title">Contact Form Submissions</h1>
            <div class="d-flex align-items-center">
                <button class="btn btn-link d-md-none me-2" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            </div>
        </div>

        <!-- Search and Filter Card -->
        <div class="card mb-4">
            <div class="card-body">
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="row g-3">
                    <div class="col-md-8">
                        <div class="input-group">
                            <input type="text" name="search" class="form-control" placeholder="Search by name, email, or message..." value="<?php echo htmlspecialchars($search); ?>">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
                            <a href="contacts.php" class="btn btn-outline-secondary"><i class="fas fa-sync-alt me-1"></i> Reset</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

      <!-- Contact Submissions Table -->
<div class="card">
    <div class="card-body">
        <?php
        if($stmt->num_rows > 0) {
            echo "<div class='table-responsive'>";
            echo "<table class='table table-bordered table-striped table-hover'>";
            echo "<thead><tr>
                <th>#</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Message</th>
                <th>Date</th>
                <th>Status</th>
                <th>Actions</th>
            </tr></thead><tbody>";
            
            $count = 1;
            while($stmt->fetch()) {
                echo "<tr>";
                echo "<td>{$count}</td>";
                echo "<td>" . htmlspecialchars($name) . "</td>";
                echo "<td><a href='mailto:" . htmlspecialchars($email) . "'>" . htmlspecialchars($email) . "</a></td>";
                echo "<td>" . ($phone ? htmlspecialchars($phone) : '-') . "</td>";
                echo "<td>" . nl2br(htmlspecialchars(substr($message, 0, 100))) . (strlen($message) > 100 ? '...' : '') . "</td>";
                echo "<td>" . date('M d, Y h:i A', strtotime($submission_date)) . "</td>";

                $status_class = '';
                switch($status) {
                    case 'new': $status_class = 'badge-new'; break;
                    case 'read': $status_class = 'badge-read'; break;
                    case 'replied': $status_class = 'badge-replied'; break;
                }
                echo "<td><span class='badge {$status_class}'>{$status}</span></td>";

                // Actions with POST form for delete
                echo "<td>
                    <a href='view_contact.php?id={$id}' class='btn btn-sm btn-info' title='View'><i class='fas fa-eye'></i></a>
                    <a href='mailto:" . htmlspecialchars($email) . "' class='btn btn-sm btn-success' title='Reply'><i class='fas fa-reply'></i></a>
                    <form action='delete_contact.php' method='post' style='display:inline;' onsubmit='return confirm(\"Are you sure you want to delete this submission?\")'>
                        <input type='hidden' name='id' value='{$id}'>
                        <button type='submit' class='btn btn-sm btn-danger'><i class='fas fa-trash'></i></button>
                    </form>
                </td>";

                echo "</tr>";
                $count++;
            }

            echo "</tbody></table></div>";
        } else {
            echo "<div class='alert alert-info'>No contact form submissions found.</div>";
        }

        $stmt->close();
        ?>
    </div>
</div>

    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('show');
            document.querySelector('.main-content').classList.toggle('active');
        });
    </script>
</body>
</html>
