<?php

namespace App\Http\Controllers;

use App\Models\Person\Person;
use Illuminate\Http\Request;

class PersonController extends Controller
{
    //
    public function show(Person $person) {}

    public function create(Request $request) {}

    public function store(Request $request) {}

    public function update(Person $person, Request $request)
    {
        $attributes = $request->validate([
            'full_name' => 'string|max:255',
            'tax_number' => 'nullable|integer',
            'social_security_number' => 'nullable|integer',
            'description' => 'nullable|string|max:500',
            'employer' => 'nullable|string|max:255',
            'birthday' => 'nullable|date',
        ]);

        $person->update($attributes);

        return back()->with('success', 'Person updated')->with('flash_method', 'PUT');

    }

    public function createAddress(Person $person, Request $request)
    {
        $attributes = $request->validate([
            'address' => 'required|string|max:150',
            'country' => 'nullable|string',
            'post_code' => 'nullable|string|max:16',
            'city' => 'nullable|string|max:100',
            'type_id' => 'required|integer|exists:address_types,id',
            'description' => 'nullable|string|max:125',
        ]);

        // Dedup: avoid duplicate address per person by (address, country)
        $address = $person->addresses()->firstOrCreate([
            'address' => $attributes['address'],
            'country' => $attributes['country'] ?? null,
            'post_code' => $attributes['post_code'] ?? null,
            'city' => $attributes['city'] ?? null,
        ], $attributes);

        // Support Inertia form submissions (redirect back) and JSON (for API/axios)
        return back()->with('success', 'Address created')->with('flash_method', 'POST');

    }

    public function updateAddress(Person $person, int $address_id, Request $request)
    {
        $attributes = $request->validate([
            'address' => 'required|string|max:150',
            'country' => 'nullable|string',
            'post_code' => 'nullable|string|max:16',
            'city' => 'nullable|string|max:100',
            'type_id' => 'required|integer|exists:address_types,id',
            'description' => 'nullable|string|max:125',
        ]);

        $address = $person->addresses()->with(['type'])->findOrFail($address_id);

        $address->update($attributes);

        return back()->with('success', 'Address updated')->with('flash_method', 'PUT');

    }

    public function deleteAddress(Person $person, int $address_id, Request $request)
    {
        $address = $person->addresses()->findOrFail($address_id);
        $address->delete(); // soft delete

        return back()->with('success', 'Address deleted')->with('flash_method', 'DELETE');
    }

    public function createPhone(Person $person, Request $request)
    {
        $attributes = $request->validate([
            'nu' => 'required|string|max:50',
            'country_code' => 'nullable|integer',
            'type_id' => 'required|integer|exists:phone_types,id',
            'description' => 'nullable|string|max:125',
            'validated' => 'sometimes|boolean',
            'phone_type' => 'nullable|in:mobile,landline,voip',
        ]);

        // Dedup: avoid duplicate phone per person by (nu, country_code)
        $phone = $person->phones()->firstOrCreate([
            'nu' => $attributes['nu'],
            'country_code' => $attributes['country_code'] ?? null,
        ], $attributes);

        return back()->with('success', 'Phone added successfully')->with('flash_method', 'POST');
    }

    public function updatePhone(Person $person, int $phone_id, Request $request)
    {
        $attributes = $request->validate([
            'nu' => 'required|string|max:50',
            'country_code' => 'nullable|integer',
            'type_id' => 'required|integer|exists:phone_types,id',
            'description' => 'nullable|string|max:125',
            'validated' => 'sometimes|boolean',
            'phone_type' => 'nullable|in:mobile,landline,voip',
        ]);

        $phone = $person->phones()->with(['type'])->findOrFail($phone_id);

        $phone->update($attributes);

        return back()->with('success', 'Phone updated successfully')->with('flash_method', 'PUT');
    }

    public function deletePhone(Person $person, int $phone_id, Request $request)
    {
        $phone = $person->phones()->findOrFail($phone_id);
        $phone->delete(); // soft delete

        return back()->with('success', 'Phone deleted')->with('flash_method', 'DELETE');
    }

    public function createEmail(Person $person, Request $request)
    {
        $attributes = $request->validate([
            'value' => 'required|email:rfc,dns|max:255',
            'label' => 'nullable|string|max:50',
            'is_primary' => 'boolean',
            'is_active' => 'boolean',
            'valid' => 'boolean',
            'failed' => 'boolean',
            'receive_auto_mails' => 'sometimes|boolean',
            'verified_at' => 'nullable|date',
            'preferences' => 'nullable|array',
            'meta' => 'nullable|array',
            'decision_ids' => 'nullable|array',
            'decision_ids.*' => 'integer|exists:decisions,id',
        ]);

        $decisionIds = array_map('intval', $attributes['decision_ids'] ?? []);
        unset($attributes['decision_ids']);
        $attributes['preferences'] = array_merge($attributes['preferences'] ?? [], ['decision_ids' => $decisionIds]);

        // Dedup: avoid duplicate email per person by value
        $email = $person->emails()->firstOrCreate([
            'value' => $attributes['value'],
        ], $attributes);

        return back()->with('success', 'Email added successfully')->with('flash_method', 'POST');
    }

    public function updateEmail(Person $person, int $email_id, Request $request)
    {
        $attributes = $request->validate([
            'value' => 'required|email:rfc,dns|max:255',
            'label' => 'nullable|string|max:50',
            'is_primary' => 'boolean',
            'is_active' => 'boolean',
            'valid' => 'boolean',
            'failed' => 'boolean',
            'receive_auto_mails' => 'sometimes|boolean',
            'verified_at' => 'nullable|date',
            'preferences' => 'nullable|array',
            'meta' => 'nullable|array',
            'decision_ids' => 'nullable|array',
            'decision_ids.*' => 'integer|exists:decisions,id',
        ]);

        $email = $person->emails()->findOrFail($email_id);

        $decisionIds = array_map('intval', $attributes['decision_ids'] ?? []);
        unset($attributes['decision_ids']);
        $attributes['preferences'] = array_merge($email->preferences ?? [], $attributes['preferences'] ?? [], ['decision_ids' => $decisionIds]);

        $email->update($attributes);

        return back()->with('success', 'Email updated successfully')->with('flash_method', 'PUT');
    }

    public function deleteEmail(Person $person, int $email_id, Request $request)
    {
        $email = $person->emails()->findOrFail($email_id);
        $email->delete();

        if ($request->header('X-Inertia')) {
            return back()->with('success', 'Email deleted');
        }

        return back()->with('success', 'Email deleted')->with('flash_method', 'DELETE');
    }

    // TRR (bank account) CRUD
    public function createTrr(Person $person, Request $request)
    {
        $attributes = $request->validate([
            'iban' => 'nullable|string|max:34',
            'bank_name' => 'required|string|max:100',
            'bic_swift' => 'nullable|string|max:11',
            'account_number' => 'nullable|string|max:34',
            'routing_number' => 'nullable|string|max:20',
            'currency' => 'required|string|size:3',
            'country_code' => 'nullable|string|size:2',
            'holder_name' => 'nullable|string|max:125',
            'notes' => 'nullable|string',
            'meta' => 'nullable|array',
        ]);

        // Create without dedup (IBAN may be null or vary); could dedup by IBAN if provided
        $trr = $person->bankAccounts()->create($attributes);

        return back()->with('success', 'TRR added successfully')->with('flash_method', 'POST');

    }

    public function updateTrr(Person $person, int $trr_id, Request $request)
    {
        $attributes = $request->validate([
            'iban' => 'nullable|string|max:34',
            'bank_name' => 'required|string|max:100',
            'bic_swift' => 'nullable|string|max:11',
            'account_number' => 'nullable|string|max:34',
            'routing_number' => 'nullable|string|max:20',
            'currency' => 'required|string|size:3',
            'country_code' => 'nullable|string|size:2',
            'holder_name' => 'nullable|string|max:125',
            'notes' => 'nullable|string',
            'meta' => 'nullable|array',
            'is_active' => 'sometimes|boolean',
        ]);

        $trr = $person->bankAccounts()->findOrFail($trr_id);
        $trr->update($attributes);

        return back()->with('success', 'TRR updated successfully')->with('flash_method', 'PUT');

    }

    public function deleteTrr(Person $person, int $trr_id, Request $request)
    {
        $trr = $person->bankAccounts()->findOrFail($trr_id);
        $trr->delete();

        return back()->with('success', 'TRR deleted')->with('flash_method', 'DELETE');

    }
}
