<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Models\Contact;

class ContactController extends BaseController
{
    /**
     * List all decrypted contacts for the company
     */
    public function index(Request $request, Response $response)
    {
        $contactModel = new Contact();
        $contacts = $contactModel->findAllByCompany($request->company_id);
        
        $response->json([
            'status' => 'success',
            'data' => $contacts
        ]);
    }

    /**
     * Store a new contact securely
     */
    public function store(Request $request, Response $response)
    {
        $errors = $this->validate($request, [
            'name' => 'required',
            'phone' => 'required'
        ]);

        if (!empty($errors)) {
            $response->status(400)->json(['status' => 'error', 'errors' => $errors]);
            return;
        }

        $body = $request->getBody();
        $contactModel = new Contact();

        // Strict duplicate check via Blind Index
        $existing = $contactModel->findByPhone($request->company_id, $body['phone']);
        if ($existing) {
            $response->status(409)->json(['status' => 'error', 'message' => 'Phone number already exists in your contacts']);
            return;
        }

        $id = $contactModel->createSecure([
            'company_id' => $request->company_id,
            'name' => $body['name'],
            'phone' => $body['phone'],
            'email' => $body['email'] ?? null,
            'notes' => $body['notes'] ?? null
        ]);

        $response->status(201)->json([
            'status' => 'success',
            'message' => 'Contact created securely',
            'id' => $id
        ]);
    }
}
