<?php

/**
 * Import Controller
 *
 * This file is used to register all actions for the Import Controller.
 *
 * @since 1.0.0
 */

namespace LinkFiliate\App\Controllers;

if (! defined('ABSPATH')) {
    exit;
}

use LinkFiliate\App\Models\Import as ImportModel;

class Import
{

    public function csv(\WP_REST_Request $request)
    {
        global $wpdb;

        // Get JSON data
        $params = $request->get_json_params();

        if (empty($params['data']) || !is_array($params['data'])) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => 'Invalid data format.'
            ], 400);
        }

        $table = $wpdb->prefix . 'linkfiliate_campaigns';

        $inserted = 0;
        foreach ($params['data'] as $row) {
            // Sanitize each field
            $name        = isset($row['name']) ? sanitize_text_field($row['name']) : '';
            $slug        = isset($row['slug']) ? sanitize_text_field($row['slug']) : '';
            $target_url        = isset($row['target_url']) ? sanitize_text_field($row['target_url']) : '';
            $description = isset($row['description']) ? sanitize_textarea_field($row['description']) : '';

            $category          = isset($row['category']) ? sanitize_text_field($row['category']) : '';
            $tags              = isset($row['tags']) ? sanitize_text_field($row['tags']) : '';
            $status            = isset($row['status']) ? sanitize_text_field($row['status']) : 'active';

            $created_at        = !empty($row['created_at']) ? sanitize_text_field($row['created_at']) : current_time('mysql');
            $updated_at        = current_time('mysql');

            // Optional: ensure slug starts with "/"
            if ($slug && strpos($slug, '/') !== 0) {
                $slug = '/' . ltrim($slug, '/');
            }

            // Skip empty names/slugs
            if (empty($name) || empty($slug)) {
                continue;
            }

            // Build internal JSON structure for settings
        $settings = [
            "redirect_type"       => isset($row['redirect_type']) ? sanitize_text_field($row['redirect_type']) : "302",
            "no_follow"           => !empty($row['rel_nofollow']) ? true : false,
            "sponsored"           => !empty($row['rel_sponsored']) ? true : false,
            "parameter_forwarding"=> !empty($row['param_forwarding']) ? true : false,
            "tracking"            => !empty($row['track_me']) ? true : false,
        ];
            // Prepare data
            $data = [
                'name'             => $name,
                'slug'             => $slug,
                'target_url'       => $target_url,
                'description'      => $description,

                'settings'    => wp_json_encode($settings),

                // 'category'         => $category,
                // 'tags'             => $tags,
                'status'           => $status,

                'created_at'       => $created_at,
                'updated_at'       => $updated_at,
            ];

            // Optional: avoid duplicates by slug
            $exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i WHERE slug = %s", $table, $slug));
            if ($exists) {
                continue; // skip if already exists
            }

            // Insert to DB
            $inserted += (int) $wpdb->insert($table, $data, ['%s', '%s', '%s', '%s']);
        }

        return new \WP_REST_Response([
            'status'   => 'success',
            'inserted' => $inserted,
            'message'  => "{$inserted} Links inserted successfully."
        ], 200);
    }
}
