<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\Phonebook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ContactController extends Controller
{
    public function index(Request $request)
    {
        $phonebook_id = $request->query('phonebook_id');
        $phonebook = Phonebook::where('id', $phonebook_id)->where('user_id', Auth::id())->firstOrFail();
        
        $contacts = Contact::where('phonebook_id', $phonebook_id)->paginate(50);
        return view('contacts.index', compact('phonebook', 'contacts'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'phonebook_id' => 'required|exists:phonebooks,id',
            'name' => 'nullable|string|max:255',
            'phone' => 'required|string|max:20'
        ]);

        $phonebook = Phonebook::where('id', $request->phonebook_id)->where('user_id', Auth::id())->firstOrFail();

        Contact::create([
            'phonebook_id' => $phonebook->id,
            'name' => $request->name,
            'phone' => $request->phone
        ]);

        return back()->with('success', 'Contact added successfully.');
    }

    public function destroy(Contact $contact)
    {
        $phonebook = Phonebook::where('id', $contact->phonebook_id)->where('user_id', Auth::id())->firstOrFail();
        $contact->delete();
        return back()->with('success', 'Contact deleted.');
    }

    public function import(Request $request)
    {
        $request->validate([
            'phonebook_id' => 'required|exists:phonebooks,id',
            'csv_file' => 'required|file|mimes:csv,txt'
        ]);

        $phonebook = Phonebook::where('id', $request->phonebook_id)->where('user_id', Auth::id())->firstOrFail();

        $file = $request->file('csv_file');
        $csvData = file_get_contents($file);
        $rows = array_map("str_getcsv", explode("\n", $csvData));
        $header = array_shift($rows);
        
        $count = 0;
        foreach ($rows as $row) {
            if (count($row) >= 1 && !empty(trim($row[0]))) {
                // Assuming format: Phone, Name
                $phone = trim($row[0]);
                $name = isset($row[1]) ? trim($row[1]) : null;
                
                Contact::create([
                    'phonebook_id' => $phonebook->id,
                    'phone' => $phone,
                    'name' => $name
                ]);
                $count++;
            }
        }

        return back()->with('success', "$count contacts imported successfully.");
    }
}
