<?php
require_once '../src/Database.php';
require_once '../src/Auth.php';
$auth = new Auth();
$auth->requireLogin();

$db = new Database();
$conn = $db->getConnection();

// Handle file upload
$upload_message = '';
$upload_type = '';
$upload_count = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['contact_file'])) {
    $file = $_FILES['contact_file'];
    
    // Check for file upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $upload_message = 'File upload error: ' . $file['error'];
        $upload_type = 'error';
    } else if ($file['size'] == 0) {
        $upload_message = 'File is empty';
        $upload_type = 'error';
    } else {
        $allowed_extensions = ['csv', 'xlsx', 'xls'];
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if (!in_array($file_extension, $allowed_extensions)) {
            $upload_message = 'Only CSV and Excel files are allowed';
            $upload_type = 'error';
        } else {
            try {
                if ($file_extension === 'csv') {
                    $upload_count = processCSV($conn, $file['tmp_name']);
                } else {
                    $upload_count = processExcel($conn, $file['tmp_name']);
                }
                $upload_message = "Successfully imported $upload_count contacts";
                $upload_type = 'success';
            } catch (Exception $e) {
                $upload_message = 'Error uploading file: ' . $e->getMessage();
                $upload_type = 'error';
            }
        }
    }
}

// Process CSV file
function processCSV($conn, $file_path) {
    $count = 0;
    $handle = fopen($file_path, 'r');
    $header = fgetcsv($handle);

    $batch = [];
    while (($row = fgetcsv($handle)) !== false) {
        $phone = sanitizePhone(trim($row[0] ?? ''));
        $name = trim($row[1] ?? 'Unknown');

        if ($phone) {
            $batch[] = ['phone' => $phone, 'name' => $name];
            if (count($batch) >= 100) {
                $count += insertBatch($conn, $batch);
                $batch = [];
            }
        }
    }
    if (!empty($batch)) {
        $count += insertBatch($conn, $batch);
    }
    fclose($handle);
    return $count;
}

// Process Excel file
function processExcel($conn, $file_path) {
    require_once dirname(__DIR__) . '/upload/upload/vendor/autoload.php';
    
    $count = 0;
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_path);
    $sheet = $spreadsheet->getActiveSheet();
    $rows = $sheet->toArray();

    $batch = [];
    foreach ($rows as $index => $row) {
        if ($index === 0) continue; // Skip header
        
        $phone = sanitizePhone(trim($row[0] ?? ''));
        $name = trim($row[1] ?? 'Unknown');

        if ($phone) {
            $batch[] = ['phone' => $phone, 'name' => $name];
            if (count($batch) >= 100) {
                $count += insertBatch($conn, $batch);
                $batch = [];
            }
        }
    }
    if (!empty($batch)) {
        $count += insertBatch($conn, $batch);
    }
    return $count;
}

// Insert batch of contacts
function insertBatch($conn, $batch) {
    $count = 0;
    try {
        $stmt = $conn->prepare('INSERT IGNORE INTO contacts (phone_number, name, created_at) VALUES (?, ?, NOW())');
        if (!$stmt) {
            throw new Exception('Failed to prepare statement: ' . $conn->error);
        }
        
        foreach ($batch as $contact) {
            try {
                if ($stmt->execute([$contact['phone'], $contact['name']])) {
                    $count++;
                }
            } catch (Exception $e) {
                // Log but continue with next contact
                error_log('Error inserting contact: ' . $e->getMessage());
            }
        }
    } catch (Exception $e) {
        error_log('Batch insert error: ' . $e->getMessage());
    }
    return $count;
}

// Sanitize phone number
function sanitizePhone($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    
    if (strlen($phone) == 10 && substr($phone, 0, 1) == "0") {
        return "254" . substr($phone, 1);
    }
    if (strlen($phone) == 9) {
        return "254" . $phone;
    }
    if (strlen($phone) == 12 && substr($phone, 0, 3) == "254") {
        return $phone;
    }
    if (strlen($phone) == 13 && substr($phone, 0, 1) == "+") {
        return substr($phone, 1);
    }
    
    return null;
}

// Get contacts count
$contact_count = 0;
try {
    $stmt = $conn->query('SELECT COUNT(*) as count FROM contacts');
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $contact_count = $result['count'] ?? 0;
} catch (Exception $e) {
    // Table might not exist yet
}

// Get recent contacts
$recent_contacts = [];
try {
    $stmt = $conn->query('SELECT id, phone_number, name, created_at FROM contacts ORDER BY created_at DESC LIMIT 10');
    $recent_contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Table might not exist yet
}

// Delete contact
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_contact') {
    $contact_id = intval($_POST['contact_id'] ?? 0);
    if ($contact_id > 0) {
        try {
            $stmt = $conn->prepare('DELETE FROM contacts WHERE id = ?');
            if ($stmt->execute([$contact_id])) {
                $upload_message = 'Contact deleted successfully';
                $upload_type = 'success';
            }
        } catch (Exception $e) {
            $upload_message = 'Error deleting contact';
            $upload_type = 'error';
        }
    }
}

// Search contacts
$search_results = [];
$search_query = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'search') {
    $search_query = trim($_POST['search_query'] ?? '');
    if (strlen($search_query) >= 3) {
        try {
            $search_term = '%' . $search_query . '%';
            $stmt = $conn->prepare('SELECT id, phone_number, name, created_at FROM contacts WHERE phone_number LIKE ? OR name LIKE ? LIMIT 20');
            $stmt->execute([$search_term, $search_term]);
            $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            // Search error
        }
    }
}

// Clear all contacts
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'clear_all') {
    try {
        $conn->query('TRUNCATE TABLE contacts');
        $upload_message = 'All contacts cleared successfully';
        $upload_type = 'success';
        $contact_count = 0;
    } catch (Exception $e) {
        $upload_message = 'Error clearing contacts';
        $upload_type = 'error';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Whitelist - USSD System</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <?php include 'sidebar.php'; ?>
    <div class="md:ml-64 min-h-screen">
        <!-- Header -->
        <div class="bg-white shadow-md p-4 md:p-6 border-b border-gray-200">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Contact Whitelist</h1>
                <p class="text-gray-600 text-sm mt-1">Manage and upload phone number contacts to the system</p>
            </div>
        </div>

        <!-- Content -->
        <div class="p-4 md:p-8">
            <!-- Messages -->
            <?php if ($upload_message): ?>
            <div class="mb-6 p-4 rounded-lg border-l-4 <?php echo $upload_type === 'success' ? 'bg-green-50 border-green-500 text-green-700' : 'bg-red-50 border-red-500 text-red-700'; ?>">
                <div class="flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                    </svg>
                    <?php echo htmlspecialchars($upload_message); ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm">Total Contacts</p>
                            <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo number_format($contact_count); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-blue-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm">Recent Activity</p>
                            <p class="text-2xl font-bold text-green-600 mt-2"><?php echo count($recent_contacts); ?></p>
                            <p class="text-xs text-gray-500">contacts recently added</p>
                        </div>
                        <svg class="w-12 h-12 text-green-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M12 2a1 1 0 01.894.553l1.659 3.318a1 1 0 00.894.553h3.659a1 1 0 01.917 1.417l-2.852 2.269a1 1 0 00-.364 1.118l1.07 3.292a1 1 0 01-1.539 1.118l-2.852-2.269a1 1 0 00-1.175 0l-2.852 2.269a1 1 0 01-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.323 8.888a1 1 0 01.917-1.417h3.659a1 1 0 00.894-.553l1.659-3.318a1 1 0 01.894-.553h0z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm">Status</p>
                            <p class="text-lg font-bold text-purple-600 mt-2">Ready</p>
                            <p class="text-xs text-gray-500 mt-1">System operational</p>
                        </div>
                        <svg class="w-12 h-12 text-purple-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M10.5 1.5H5.75A2.75 2.75 0 003 4.25v11.5A2.75 2.75 0 005.75 18.5h8.5a2.75 2.75 0 002.75-2.75V6.5"></path>
                            <path d="M7 11h6M7 15h6" stroke="currentColor" stroke-width="1.5" fill="none"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Upload Section -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">Upload Contacts</h2>
                <form method="POST" enctype="multipart/form-data" class="space-y-4">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Select File</label>
                            <input type="file" name="contact_file" accept=".csv,.xlsx,.xls" class="w-full px-4 py-3 border-2 border-dashed border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 cursor-pointer">
                        </div>

                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <h3 class="font-semibold text-blue-900 mb-2">Upload Format:</h3>
                            <ul class="text-sm text-blue-800 space-y-1">
                                <li>✓ Column 1: Phone numbers (0712345678, 254712345678, +254712345678)</li>
                                <li>✓ Column 2: Names (optional)</li>
                                <li>✓ Supported formats: CSV, XLSX, XLS</li>
                                <li>✓ Maximum: 10,000 contacts per file</li>
                            </ul>
                        </div>

                        <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition">
                            <svg class="w-5 h-5 inline-block mr-2" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1v-2zm3.172-5.828a1 1 0 11-1.414-1.414L9.172 9 4.757 4.586a1 1 0 111.414-1.414L10.586 7.758l4.415-4.414a1 1 0 111.414 1.414L12 9.172l4.414 4.414a1 1 0 11-1.414 1.414L10.586 10.586l-4.414 4.414z" clip-rule="evenodd"></path>
                            </svg>
                            Upload Contacts
                        </button>
                    </div>
                </form>
            </div>

            <!-- Search Section -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">Search Contacts</h2>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="search">
                    <div class="flex gap-2">
                        <input type="text" name="search_query" placeholder="Search by phone or name..." value="<?php echo htmlspecialchars($search_query); ?>" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-semibold transition">Search</button>
                    </div>
                </form>

                <?php if (!empty($search_results)): ?>
                <div class="mt-4 overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-gray-50 border-b">
                            <tr>
                                <th class="px-4 py-2 text-left font-semibold">Phone Number</th>
                                <th class="px-4 py-2 text-left font-semibold">Name</th>
                                <th class="px-4 py-2 text-left font-semibold">Added</th>
                                <th class="px-4 py-2 text-left font-semibold">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($search_results as $contact): ?>
                            <tr class="border-b hover:bg-gray-50">
                                <td class="px-4 py-2"><?php echo htmlspecialchars($contact['phone_number']); ?></td>
                                <td class="px-4 py-2"><?php echo htmlspecialchars($contact['name']); ?></td>
                                <td class="px-4 py-2 text-gray-600"><?php echo date('M d, Y', strtotime($contact['created_at'])); ?></td>
                                <td class="px-4 py-2">
                                    <form method="POST" class="inline">
                                        <input type="hidden" name="action" value="delete_contact">
                                        <input type="hidden" name="contact_id" value="<?php echo $contact['id']; ?>">
                                        <button type="submit" class="text-red-600 hover:text-red-800 font-semibold" onclick="return confirm('Delete this contact?')">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>

            <!-- Recent Contacts Section -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-bold text-gray-800">Recent Contacts</h2>
                    <?php if ($contact_count > 0): ?>
                    <form method="POST" class="inline">
                        <input type="hidden" name="action" value="clear_all">
                        <button type="submit" class="text-red-600 hover:text-red-800 text-sm font-semibold" onclick="return confirm('Clear all contacts? This cannot be undone!')">Clear All</button>
                    </form>
                    <?php endif; ?>
                </div>

                <?php if (!empty($recent_contacts)): ?>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-gray-50 border-b">
                            <tr>
                                <th class="px-4 py-2 text-left font-semibold">Phone Number</th>
                                <th class="px-4 py-2 text-left font-semibold">Name</th>
                                <th class="px-4 py-2 text-left font-semibold">Added</th>
                                <th class="px-4 py-2 text-left font-semibold">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_contacts as $contact): ?>
                            <tr class="border-b hover:bg-gray-50">
                                <td class="px-4 py-2 font-mono"><?php echo htmlspecialchars($contact['phone_number']); ?></td>
                                <td class="px-4 py-2"><?php echo htmlspecialchars($contact['name']); ?></td>
                                <td class="px-4 py-2 text-gray-600"><?php echo date('M d, Y H:i', strtotime($contact['created_at'])); ?></td>
                                <td class="px-4 py-2">
                                    <form method="POST" class="inline">
                                        <input type="hidden" name="action" value="delete_contact">
                                        <input type="hidden" name="contact_id" value="<?php echo $contact['id']; ?>">
                                        <button type="submit" class="text-red-600 hover:text-red-800 font-semibold" onclick="return confirm('Delete this contact?')">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center text-gray-500 py-12">
                    <svg class="w-12 h-12 mx-auto mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m0 0h6m-6-6H6"></path>
                    </svg>
                    <p class="text-lg">No contacts yet</p>
                    <p class="text-sm">Upload a file to get started</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Close message after 5 seconds
        window.addEventListener('load', function() {
            const messageElement = document.querySelector('[class*="bg-green-50"], [class*="bg-red-50"]');
            if (messageElement) {
                setTimeout(() => {
                    messageElement.style.display = 'none';
                }, 5000);
            }
        });
    </script>
</body>
</html>
