<?php
/**
 * API - SEO Keywords Import/Export
 */

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

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

// Check admin authentication
if (!auth()->isAdminLoggedIn()) {
    jsonError('Unauthorized', 401);
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

// Export Keywords as CSV
if ($action === 'export') {
    $keywords = dbFetchAll("SELECT keyword, search_volume, difficulty, priority, category, target_page, status FROM seo_keywords ORDER BY id");
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="seo_keywords_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header row
    fputcsv($output, ['Keyword', 'Search Volume', 'Difficulty', 'Priority', 'Category', 'Target Page', 'Status']);
    
    // Data rows
    foreach ($keywords as $kw) {
        fputcsv($output, [
            $kw['keyword'],
            $kw['search_volume'],
            $kw['difficulty'],
            $kw['priority'],
            $kw['category'],
            $kw['target_page'],
            $kw['status']
        ]);
    }
    
    fclose($output);
    exit;
}

// Import Keywords from CSV
if ($action === 'import' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        jsonError('No file uploaded or upload error');
    }
    
    $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
    if (!$file) {
        jsonError('Could not open file');
    }
    
    $header = fgetcsv($file); // Skip header row
    $imported = 0;
    $skipped = 0;
    
    while (($row = fgetcsv($file)) !== false) {
        if (count($row) < 1 || empty(trim($row[0]))) {
            continue;
        }
        
        $keyword = trim($row[0]);
        
        // Check if exists
        $exists = dbFetch("SELECT id FROM seo_keywords WHERE keyword = :kw", ['kw' => $keyword]);
        
        if ($exists) {
            // Update existing
            dbUpdate('seo_keywords', [
                'search_volume' => (int)($row[1] ?? 0),
                'difficulty' => (int)($row[2] ?? 50),
                'priority' => $row[3] ?? 'medium',
                'category' => $row[4] ?? 'General',
                'target_page' => $row[5] ?? '',
                'status' => $row[6] ?? 'active'
            ], 'id = :id', ['id' => $exists['id']]);
            $skipped++;
        } else {
            // Insert new
            dbInsert('seo_keywords', [
                'keyword' => $keyword,
                'search_volume' => (int)($row[1] ?? 0),
                'difficulty' => (int)($row[2] ?? 50),
                'priority' => $row[3] ?? 'medium',
                'category' => $row[4] ?? 'General',
                'target_page' => $row[5] ?? '',
                'status' => $row[6] ?? 'active'
            ]);
            $imported++;
        }
    }
    
    fclose($file);
    
    jsonSuccess("Import complete", [
        'imported' => $imported,
        'updated' => $skipped
    ]);
}

// Get Keywords JSON
if ($action === 'list') {
    $category = $_GET['category'] ?? '';
    $priority = $_GET['priority'] ?? '';
    $search = $_GET['search'] ?? '';
    $limit = min(1000, (int)($_GET['limit'] ?? 100));
    $offset = (int)($_GET['offset'] ?? 0);
    
    $where = "1=1";
    $params = [];
    
    if ($category) {
        $where .= " AND category = :cat";
        $params['cat'] = $category;
    }
    if ($priority) {
        $where .= " AND priority = :pri";
        $params['pri'] = $priority;
    }
    if ($search) {
        $where .= " AND keyword LIKE :search";
        $params['search'] = "%{$search}%";
    }
    
    $total = dbFetch("SELECT COUNT(*) as c FROM seo_keywords WHERE {$where}", $params)['c'];
    $keywords = dbFetchAll(
        "SELECT * FROM seo_keywords WHERE {$where} ORDER BY priority DESC, search_volume DESC LIMIT {$limit} OFFSET {$offset}",
        $params
    );
    
    jsonSuccess('Keywords retrieved', [
        'total' => $total,
        'limit' => $limit,
        'offset' => $offset,
        'keywords' => $keywords
    ]);
}

// Get Categories
if ($action === 'categories') {
    $categories = dbFetchAll("SELECT DISTINCT category, COUNT(*) as count FROM seo_keywords GROUP BY category ORDER BY count DESC");
    jsonSuccess('Categories retrieved', ['categories' => $categories]);
}

// Bulk Update
if ($action === 'bulk_update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $ids = $input['ids'] ?? [];
    $field = $input['field'] ?? '';
    $value = $input['value'] ?? '';
    
    if (empty($ids) || !$field) {
        jsonError('IDs and field required');
    }
    
    $allowedFields = ['priority', 'category', 'status', 'target_page'];
    if (!in_array($field, $allowedFields)) {
        jsonError('Invalid field');
    }
    
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $stmt = db()->prepare("UPDATE seo_keywords SET {$field} = ? WHERE id IN ({$placeholders})");
    $stmt->execute(array_merge([$value], $ids));
    
    jsonSuccess('Keywords updated', ['affected' => $stmt->rowCount()]);
}

// Bulk Delete
if ($action === 'bulk_delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $ids = $input['ids'] ?? [];
    
    if (empty($ids)) {
        jsonError('IDs required');
    }
    
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $stmt = db()->prepare("DELETE FROM seo_keywords WHERE id IN ({$placeholders})");
    $stmt->execute($ids);
    
    jsonSuccess('Keywords deleted', ['affected' => $stmt->rowCount()]);
}

jsonError('Invalid action');
