<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_auth(['admin']);
header('Content-Type: application/json');

try {
    $db = hw_db();
    
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $perPage = isset($_GET['per_page']) ? min(100, max(1, (int)$_GET['per_page'])) : 20;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $offset = ($page - 1) * $perPage;
    
    // Build query
    $params = [];
    $searchQuery = '';
    
    if ($search) {
        $searchQuery = ' AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR phone LIKE ? OR company LIKE ?)';
        $searchTerm = "%$search%";
        $params = [$searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm];
    }
    
    // Get total count
    $countSql = "SELECT COUNT(*) as total FROM contacts WHERE 1=1" . $searchQuery;
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $total = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get contacts
    $listSql = "SELECT id, first_name, last_name, email, phone, company, labels,
               address_city, address_state, email_subscriber_status,
               last_activity, last_activity_date, created_at
        FROM contacts 
        WHERE 1=1" . $searchQuery . "
        ORDER BY created_at DESC
        LIMIT " . $perPage . " OFFSET " . $offset;
    
    $stmt = $db->prepare($listSql);
    $stmt->execute($params);
    $contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'contacts' => $contacts,
        'pagination' => [
            'page' => $page,
            'per_page' => $perPage,
            'total' => (int)$total,
            'total_pages' => ceil($total / $perPage)
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
