<?php
require_once '../../config.php';
require_once '../../functions.php';

header('Content-Type: application/json');

// Helper to send json response
// Moved to functions.php

// Basic Auth Check
if (!isset($_SESSION['user_id']) && !isset($_SESSION['admin_id'])) {
    json_response('error', 'Unauthorized');
}

$action = $_POST['action'] ?? '';

// Determine Owner info
// Use same logic as send_sms.php: Prioritize Admin if set (assuming admins might impersonate or just have higher privs)
$owner_type = isset($_SESSION['admin_id']) ? 'admin' : 'user';
$owner_id = isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : $_SESSION['user_id'];
$group_id = $_POST['group_id'] ?? null;

try {
    if ($action === 'create_group' || $action === 'update_group') {
        $name = trim($_POST['name'] ?? '');
        $status = $_POST['status'] ?? 'active';
        $contact_numbers = $_POST['contacts'] ?? []; // Array of numbers
        $custom_number = trim($_POST['custom_number'] ?? '');
        $custom_numbers_array = $_POST['custom_numbers'] ?? [];

        // Handle Select2 tag input (array)
        if (!empty($custom_numbers_array) && is_array($custom_numbers_array)) {
            foreach ($custom_numbers_array as $num) {
                if (!empty(trim($num))) {
                    $contact_numbers[] = trim($num);
                }
            }
        }

        // Handle legacy textarea input (string)
        if (!empty($custom_number)) {
            // Split by comma, newline, carriage return, or space
            $extras = preg_split('/[\s,]+/', $custom_number);
            $extras = array_filter($extras, function ($v) {
                return !empty(trim($v));
            });

            foreach ($extras as $num) {
                $contact_numbers[] = trim($num);
            }
        }

        if (empty($name)) {
            json_response('error', 'Group Name is required');
        }

        $pdo->beginTransaction();

        if ($action === 'create_group') {
            $stmt = $pdo->prepare("INSERT INTO contact_groups (name, owner_type, owner_id, status) VALUES (?, ?, ?, ?)");
            $stmt->execute([$name, $owner_type, $owner_id, $status]);
            $group_id = $pdo->lastInsertId();
        } else {
            // update_group - $group_id should already be set from POST
            if (empty($group_id)) {
                json_response('error', 'Group ID is required for update');
            }

            if ($owner_type === 'admin') {
                $stmt = $pdo->prepare("UPDATE contact_groups SET name = ?, status = ? WHERE id = ?");
                $stmt->execute([$name, $status, $group_id]);
            } else {
                // Verify ownership
                $stmt = $pdo->prepare("UPDATE contact_groups SET name = ?, status = ? WHERE id = ? AND owner_type = ? AND owner_id = ?");
                $stmt->execute([$name, $status, $group_id, $owner_type, $owner_id]);
            }
            // Clear existing members to re-add (Simple approach)
            $pdo->prepare("DELETE FROM contact_group_members WHERE group_id = ?")->execute([$group_id]);
        }

        // Add Members
        if (!empty($contact_numbers)) {
            $insertStmt = $pdo->prepare("INSERT INTO contact_group_members (group_id, phone_number) VALUES (?, ?)");
            foreach ($contact_numbers as $phone) {
                $phone = trim($phone);
                if (!empty($phone)) {
                    try {
                        $insertStmt->execute([$group_id, $phone]);
                    } catch (PDOException $e) {
                        // Log but continue with other numbers
                        error_log("Failed to insert number {$phone} for group {$group_id}: " . $e->getMessage());
                    }
                }
            }
        }

        $pdo->commit();
        json_response('success', 'Group saved successfully');

    } elseif ($action === 'delete_group') {
        if ($owner_type === 'admin') {
            $stmt = $pdo->prepare("DELETE FROM contact_groups WHERE id = ?");
            if ($stmt->execute([$group_id])) {
                json_response('success', 'Group deleted');
            }
        } else {
            $stmt = $pdo->prepare("DELETE FROM contact_groups WHERE id = ? AND owner_type = ? AND owner_id = ?");
            if ($stmt->execute([$group_id, $owner_type, $owner_id])) {
                json_response('success', 'Group deleted');
            }
        }
        json_response('error', 'Failed to delete group');

    } elseif ($action === 'toggle_status') {
        // $group_id is already set at top
        $status = $_POST['status']; // 'active' or 'inactive'
        $stmt = $pdo->prepare("UPDATE contact_groups SET status = ? WHERE id = ?");
        $stmt->execute([$status, $group_id]);
        json_response('success', 'Status updated');

    } elseif ($action === 'fetch_available_numbers') {
        // Fetch unique numbers from SMS Logs
        // Also check if they belong to other groups to add Pills

        // 1. Get all unique numbers from logs
        // 1. Get all unique numbers from contacts table
        if ($owner_type === 'admin') {
            // Admin: Group by phone to get unique list across system
            $stmt = $pdo->query("SELECT phone_number, MAX(name) as name FROM contacts GROUP BY phone_number ORDER BY phone_number ASC");
        } else {
            // User: Get own unique list
            $stmt = $pdo->prepare("SELECT phone_number, name FROM contacts WHERE owner_type = ? AND owner_id = ? ORDER BY phone_number ASC");
            $stmt->execute([$owner_type, $owner_id]);
        }
        $contact_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Map to simple array of phones for existing pill logic, or refactor logic below
        // The logic below iterates $numbers (array of strings). 
        // Let's create $numbers array from $contact_rows for minimal refactor
        $numbers = array_column($contact_rows, 'phone_number');
        // We can associate names to phones if we want to pass them
        $names = array_column($contact_rows, 'name', 'phone_number');

        // 2. Get Group assignments
        $assignments = [];
        if ($owner_type === 'admin') {
            // Admin sees pills for ALL groups
            $stmt = $pdo->query("
                SELECT m.phone_number, g.name 
                FROM contact_group_members m 
                JOIN contact_groups g ON m.group_id = g.id 
            ");
        } else {
            $stmt = $pdo->prepare("
                SELECT m.phone_number, g.name 
                FROM contact_group_members m 
                JOIN contact_groups g ON m.group_id = g.id 
                WHERE g.owner_type = ? AND g.owner_id = ?
            ");
            $stmt->execute([$owner_type, $owner_id]);
        }
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($rows as $row) {
            $assignments[$row['phone_number']][] = substr($row['name'], 0, 2);
        }

        $result = [];
        foreach ($numbers as $num) {
            $pills = $assignments[$num] ?? [];
            $result[] = [
                'phone' => $num,
                'name' => $names[$num] ?? '',
                'pills' => $pills
            ];
        }

        json_response('success', 'Numbers fetched', $result);

    } elseif ($action === 'remove_member') {
        if (empty($group_id) || empty($_POST['phone'])) {
            json_response('error', 'Group ID and Phone are required');
        }
        $phone = $_POST['phone'];

        // Verify ownership if not admin (standard check)
        if ($owner_type !== 'admin') {
            $checkStmt = $pdo->prepare("SELECT id FROM contact_groups WHERE id = ? AND owner_type = ? AND owner_id = ?");
            $checkStmt->execute([$group_id, $owner_type, $owner_id]);
            if (!$checkStmt->fetch()) {
                json_response('error', 'Unauthorized or Group not found');
            }
        }

        $stmt = $pdo->prepare("DELETE FROM contact_group_members WHERE group_id = ? AND phone_number = ?");
        if ($stmt->execute([$group_id, $phone])) {
            json_response('success', 'Member removed');
        } else {
            json_response('error', 'Failed to remove member');
        }

    } elseif ($action === 'fetch_group_members') {
        //$group_id is set at top
        $stmt = $pdo->prepare("SELECT phone_number FROM contact_group_members WHERE group_id = ?");
        $stmt->execute([$group_id]);
        $members = $stmt->fetchAll(PDO::FETCH_COLUMN);
        json_response('success', 'Members fetched', $members);
    }

} catch (Exception $e) {
    if ($pdo->inTransaction())
        $pdo->rollBack();
    json_response('error', $e->getMessage());
}
?>