<?php

namespace App\Controllers;

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

class GroupController extends BaseController
{
    /**
     * List all groups for the company
     */
    public function index(Request $request, Response $response)
    {
        $groupModel = new ContactGroup();
        $groups = \App\Core\Database::select(
            "SELECT * FROM contact_groups WHERE company_id = ? ORDER BY id DESC",
            [$request->company_id]
        );

        $response->json([
            'status' => 'success',
            'data' => $groups
        ]);
    }

    /**
     * Create a new contact group
     */
    public function store(Request $request, Response $response)
    {
        $errors = $this->validate($request, ['name' => 'required']);
        if (!empty($errors)) {
            $response->status(400)->json(['status' => 'error', 'errors' => $errors]);
            return;
        }

        $groupModel = new ContactGroup();
        $id = $groupModel->create([
            'company_id' => $request->company_id,
            'name' => $request->getBody()['name']
        ]);

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

    /**
     * Attach a contact to a group
     */
    public function addContact(Request $request, Response $response)
    {
        $errors = $this->validate($request, ['group_id' => 'required', 'contact_id' => 'required']);
        if (!empty($errors)) {
            $response->status(400)->json(['status' => 'error', 'errors' => $errors]);
            return;
        }

        $body = $request->getBody();
        $groupModel = new ContactGroup();
        
        // Note: For absolute security, we should verify that both the group and contact belong to the company_id
        // We assume basic attachment here for Phase 4
        $groupModel->attachContact($body['group_id'], $body['contact_id']);

        $response->json(['status' => 'success', 'message' => 'Contact added to group']);
    }

    /**
     * Attach multiple contacts to a group in bulk
     */
    public function bulkAddContacts(Request $request, Response $response)
    {
        $errors = $this->validate($request, [
            'group_id' => 'required',
            'contact_ids' => 'required'
        ]);
        if (!empty($errors)) {
            $response->status(400)->json(['status' => 'error', 'errors' => $errors]);
            return;
        }

        $body = $request->getBody();
        $groupId = (int)$body['group_id'];
        $contactIds = $body['contact_ids'];

        if (!is_array($contactIds)) {
            $response->status(400)->json(['status' => 'error', 'message' => 'contact_ids must be an array']);
            return;
        }

        $groupModel = new ContactGroup();
        
        $pdo = \App\Core\Database::getConnection();
        try {
            $pdo->beginTransaction();
            foreach ($contactIds as $contactId) {
                $groupModel->attachContact($groupId, (int)$contactId);
            }
            $pdo->commit();
        } catch (\Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $response->status(500)->json(['status' => 'error', 'message' => 'Bulk insert failed: ' . $e->getMessage()]);
            return;
        }

        $response->json(['status' => 'success', 'message' => 'Contacts added to group in bulk']);
    }
}
