<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\EmailList;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ContactController extends Controller
{
    public function index(EmailList $list)
    {
        $contacts = $list->contacts()->paginate(20);
        return view('contacts.index', compact('list','contacts'));
    }

    public function create(EmailList $list)
    {
        return view('contacts.create', compact('list'));
    }

    public function store(Request $request, EmailList $list)
    {
        $request->validate(['email' => 'required|email']);
        $list->contacts()->create($request->only('name','email'));
        return back()->with('success', 'Contact added.');
    }

    public function import(Request $request, EmailList $list)
    {
        $request->validate(['file' => 'required|mimes:csv,txt,xlsx']);
        $path = $request->file('file')->getRealPath();
        $data = array_map('str_getcsv', file($path));

        foreach ($data as $row) {
            if (filter_var($row[0], FILTER_VALIDATE_EMAIL)) {
                $list->contacts()->firstOrCreate(['email' => $row[0]], ['name' => $row[1] ?? null]);
            }
        }

        return back()->with('success', 'Contacts imported successfully.');
    }
}
