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

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

try {
    $csvFile = $_SERVER['DOCUMENT_ROOT'] . '/atasteofafricanmarketplace/contacts (2).csv';
    
    if (!file_exists($csvFile)) {
        throw new Exception('CSV file not found');
    }
    
    $db = hw_db();
    
    // Read and parse CSV
    $handle = fopen($csvFile, 'r');
    if (!$handle) {
        throw new Exception('Could not open CSV file');
    }
    
    // Get headers
    $headers = fgetcsv($handle);
    
    $imported = 0;
    $skipped = 0;
    
    while (($row = fgetcsv($handle)) !== false) {
        // Skip rows with no email
        if (empty($row[2])) {
            $skipped++;
            continue;
        }
        
        // Parse the row data
        $data = array_combine($headers, $row);
        
        // Check if contact already exists
        $stmt = $db->prepare('SELECT id FROM contacts WHERE email = ?');
        $stmt->execute([$data['Email 1']]);
        
        if ($stmt->fetch()) {
            $skipped++;
            continue;
        }
        
        // Insert contact
        $stmt = $db->prepare('
            INSERT INTO contacts (
                first_name, last_name, email, email_2, phone, phone_2,
                company, labels, address_street, address_city, address_state,
                address_zip, address_country, email_subscriber_status,
                sms_subscriber_status, source, language, last_activity,
                last_activity_date
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ');
        
        $lastActivityDate = null;
        if (!empty($data['Last Activity Date (UTC+0)'])) {
            $lastActivityDate = date('Y-m-d H:i:s', strtotime($data['Last Activity Date (UTC+0)']));
        }
        
        $stmt->execute([
            $data['First Name'] ?? '',
            $data['Last Name'] ?? '',
            $data['Email 1'] ?? '',
            $data['Email 2'] ?? '',
            $data['Phone 1'] ?? '',
            $data['Phone 2'] ?? '',
            $data['Company'] ?? '',
            $data['Labels'] ?? '',
            $data['Address 1 - Street'] ?? '',
            $data['Address 1 - City'] ?? '',
            $data['Address 1 - State/Region'] ?? '',
            $data['Address 1 - Zip'] ?? '',
            $data['Address 1 - Country'] ?? '',
            $data['Email subscriber status'] ?? 'Never subscribed',
            $data['SMS subscriber status'] ?? 'Never subscribed',
            $data['Source'] ?? '',
            $data['Language'] ?? 'en',
            $data['Last Activity'] ?? '',
            $lastActivityDate
        ]);
        
        $imported++;
    }
    
    fclose($handle);
    
    echo json_encode([
        'success' => true,
        'imported' => $imported,
        'skipped' => $skipped,
        'message' => "Imported $imported contacts, skipped $skipped duplicates"
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
