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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response('error', 'Invalid request method');
}

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

// Basic Auth Check
if (!is_logged_in()) {
    json_response('error', 'Unauthorized');
}

$user_id = $_SESSION['user_id'];
// Determine if Admin (Assuming admin definition from session or functions)
// In this system, admins seem to be in 'admins' table and users in 'users'.
// We check session to see if it's admin or user.
// Based on 'api_settings.php' logic or similar files:
$is_admin = isset($_SESSION['admin_id']); // Adjust if your auth logic differs

try {
    if ($action === 'fetch_contacts') {
        $draw = $_POST['draw'] ?? 1;
        $start = $_POST['start'] ?? 0;
        $length = $_POST['length'] ?? 10;
        $search = $_POST['search']['value'] ?? '';

        // Base Query with Shared Count
        // Admin: Group by phone to show unique list + count
        if ($is_admin) {
            $query = "SELECT MAX(id) as id, phone_number, MAX(name) as name, COUNT(*) as shared_count 
                     FROM contacts WHERE 1=1";
            $params = [];
        } else {
            $query = "SELECT contacts.*, 
                     (SELECT COUNT(*) FROM contacts c2 WHERE c2.phone_number = contacts.phone_number) as shared_count 
                     FROM contacts WHERE user_id = ?";
            $params = [$user_id];
        }

        // Search
        if (!empty($search)) {
            $query .= " AND (phone_number LIKE ? OR name LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }

        // Add Group By for Admin (Must be before ORDER BY)
        if ($is_admin) {
            $query .= " GROUP BY phone_number";
        }

        // Total Filtered Count
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $totalFiltered = $stmt->rowCount();

        // Total Records (Without Filter)
        if ($is_admin) {
            $totalStmt = $pdo->query("SELECT COUNT(DISTINCT phone_number) FROM contacts");
        } else {
            $totalStmt = $pdo->prepare("SELECT COUNT(*) FROM contacts WHERE user_id = ?");
            $totalStmt->execute([$user_id]);
        }
        $totalRecords = $totalStmt->fetchColumn();

        // Pagination
        $query .= " ORDER BY id DESC LIMIT $start, $length";
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            "draw" => intval($draw),
            "recordsTotal" => intval($totalRecords),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        ]);
        exit;

    } elseif ($action === 'add_contact') {
        $phone = trim($_POST['phone'] ?? '');
        $name = trim($_POST['name'] ?? '');

        if (empty($phone)) {
            json_response('error', 'Phone number is required');
        }

        // Check duplicate
        // Check duplicate
        $owner_id = $is_admin ? 0 : $user_id; // 0 for admin owned

        // Fix Owner Type logic: Admins create 'admin' type, Users create 'user' type
        // However, if Admin is creating ON BEHALF of a user context (not implemented here), it might differ.
        // Assuming strict separation:
        $owner_type = $is_admin ? 'admin' : 'user';

        if ($is_admin) {
            // Admin: Check Global Existence
            $check = $pdo->prepare("SELECT id FROM contacts WHERE phone_number = ? LIMIT 1");
            $check->execute([$phone]);
            if ($check->rowCount() > 0) {
                json_response('error', 'Contact already exists in the system (Admin view).');
            }
        } else {
            // User: Check Own List Only
            $check = $pdo->prepare("SELECT id FROM contacts WHERE owner_type = ? AND owner_id = ? AND phone_number = ?");
            $check->execute([$owner_type, $owner_id, $phone]);
            if ($check->rowCount() > 0) {
                json_response('error', 'Contact already exists in your list.');
            }
        }

        // Insert with accurate Owner Info
        $stmt = $pdo->prepare("INSERT INTO contacts (owner_type, owner_id, phone_number, name, user_id) VALUES (?, ?, ?, ?, ?)");

        // Legacy user_id: NULL for admin, user_id for user
        $legacy_uid = $is_admin ? null : $user_id;

        if ($stmt->execute([$owner_type, $owner_id, $phone, $name, $legacy_uid])) {
            json_response('success', 'Contact added successfully');
        } else {
            json_response('error', 'Failed to add contact');
        }

    } elseif ($action === 'update_contact') {
        $id = $_POST['id'] ?? 0;
        $name = trim($_POST['name'] ?? '');
        // User requested "dynamic edit small modal", likely phone number editing too
        $phone = trim($_POST['phone'] ?? '');

        if (empty($id) || empty($phone)) {
            json_response('error', 'Invalid data');
        }

        // Verify ownership
        $verify = "SELECT id FROM contacts WHERE id = ?";
        $vParams = [$id];
        if (!$is_admin) {
            $verify .= " AND user_id = ?";
            $vParams[] = $user_id;
        }

        $chk = $pdo->prepare($verify);
        $chk->execute($vParams);
        if ($chk->rowCount() === 0) {
            json_response('error', 'Contact not found or access denied');
        }

        $stmt = $pdo->prepare("UPDATE contacts SET phone_number = ?, name = ? WHERE id = ?");
        if ($stmt->execute([$phone, $name, $id])) {
            json_response('success', 'Contact updated successfully');
        } else {
            json_response('error', 'Failed to update contact');
        }

    } elseif ($action === 'delete_contact') {
        $id = $_POST['id'] ?? 0;

        // Verify ownership
        $verify = "SELECT id FROM contacts WHERE id = ?";
        $vParams = [$id];
        if (!$is_admin) {
            $verify .= " AND user_id = ?";
            $vParams[] = $user_id;
        }

        $chk = $pdo->prepare($verify);
        $chk->execute($vParams);
        if ($chk->rowCount() === 0) {
            json_response('error', 'Contact not found or access denied');
        }

        $stmt = $pdo->prepare("DELETE FROM contacts WHERE id = ?");
        if ($stmt->execute([$id])) {
            json_response('success', 'Contact deleted successfully');
        } else {
            json_response('error', 'Failed to delete contact');
        }
    }

} catch (PDOException $e) {
    json_response('error', 'Database error: ' . $e->getMessage());
}
?>