<?php
// api/customers/merge.php
header('Content-Type: application/json');

// Auth
require_once __DIR__ . '/../_pdo_db_connect.php';
require_once __DIR__ . '/../middleware/auth_check.php';
require_once __DIR__ . '/../../Controllers/CustomerMergeController.php';

$auth = new AuthCheck();
$user = $auth->requireAuth(); // returns array with id, role, team_id etc.

// Instantiate controller
$merge = new CustomerMergeController($pdo);

// Modes:
// 1) auto -> auto-merge all groups (POST { mode: "auto" })
// 2) manual -> merge provided primary + duplicates (POST { mode:"manual", primary: 12, duplicates: [34,56] })

$input = json_decode(file_get_contents('php://input'), true) ?? [];

$mode = $input['mode'] ?? 'auto';

if ($mode === 'auto') {
    // Only allow Admin or Manager roles to run auto-merge
    if (!in_array($user['role'], ['Admin','StateHead'])) {
        http_response_code(403);
        echo json_encode(['error' => true, 'msg' => 'Insufficient permissions to run auto-merge.']);
        exit;
    }

    $reports = $merge->autoMergeAll($user['id']);
    echo json_encode(['error' => false, 'msg' => 'Auto-merge completed', 'reports' => $reports]);
    exit;
}

if ($mode === 'manual') {
    $primary = isset($input['primary']) ? (int)$input['primary'] : 0;
    $duplicates = isset($input['duplicates']) && is_array($input['duplicates']) ? array_map('intval', $input['duplicates']) : [];

    if (!$primary || empty($duplicates)) {
        http_response_code(400);
        echo json_encode(['error' => true, 'msg' => 'primary and duplicates array required for manual mode.']);
        exit;
    }

    // Permission check: allow creators or Admins; you can adjust this as desired
    // If you need stricter rules (e.g. owner only), change accordingly.
    $report = $merge->mergeIntoPrimary($primary, $duplicates, $user['id']);
    if (!empty($report['error'])) {
        http_response_code(500);
    } else {
        http_response_code(200);
    }
    echo json_encode($report);
    exit;
}

http_response_code(400);
echo json_encode(['error' => true, 'msg' => 'Unknown mode. Use "auto" or "manual".']);
exit;
