<?php
// api/members_import.php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

requireRole('admin');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['csv_file'])) {
    echo json_encode(['success' => false, 'message' => 'No file uploaded']);
    exit;
}

$file = $_FILES['csv_file'];

// Validate file type
if ($file['type'] !== 'text/csv' && !str_ends_with($file['name'], '.csv')) {
    echo json_encode(['success' => false, 'message' => 'Please upload a CSV file']);
    exit;
}

// Read CSV
$handle = fopen($file['tmp_name'], 'r');
if (!$handle) {
    echo json_encode(['success' => false, 'message' => 'Failed to read file']);
    exit;
}

// Get header row
$headers = fgetcsv($handle);
$expected_headers = ['full_name', 'email', 'phone', 'address', 'unit', 'branch', 'date_joined', 'status', 'experiences'];

// Validate headers
if ($headers !== $expected_headers) {
    fclose($handle);
    echo json_encode(['success' => false, 'message' => 'Invalid CSV format. Expected headers: ' . implode(', ', $expected_headers)]);
    exit;
}

$imported = 0;
$errors = [];
$line = 1;

try {
    $pdo->beginTransaction();
    
    while (($data = fgetcsv($handle)) !== false) {
        $line++;
        
        if (count($data) !== count($expected_headers)) {
            $errors[] = "Line $line: Invalid number of columns";
            continue;
        }
        
        list($full_name, $email, $phone, $address, $unit, $branch, $date_joined, $status, $experiences) = $data;
        
        // Validate required fields
        if (empty($full_name)) {
            $errors[] = "Line $line: Missing required field (full_name)";
            continue;
        }
        
        // Check if member already exists (only if email is provided)
        if (!empty($email)) {
            $check = $pdo->prepare("SELECT id FROM members WHERE email = ?");
            $check->execute([$email]);
            if ($check->fetch()) {
                $errors[] = "Line $line: Member with email $email already exists";
                continue;
            }
        }
        
        // Insert member
        $sql = "INSERT INTO members (full_name, email, phone, address, unit, branch, date_joined, status, experiences) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$full_name, $email, $phone, $address, $unit, $branch, $date_joined, $status, $experiences])) {
            $imported++;
        } else {
            $errors[] = "Line $line: Failed to insert member";
        }
    }
    
    $pdo->commit();
    fclose($handle);
    
    echo json_encode([
        'success' => true,
        'message' => "Successfully imported $imported members",
        'imported' => $imported,
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    fclose($handle);
    echo json_encode(['success' => false, 'message' => 'Import failed: ' . $e->getMessage()]);
}
