<?php
class ContactsController extends Controller {
//     public function index() {
//     session_start();

//     if (!isset($_SESSION['user_id'])) {
//         header("Location: " . BASE_URL . "/LoginController/index");
//         exit;
//     }

//     $userId = $_SESSION['user_id'];
//     $role = $_SESSION['user_role'];

//     $contactModel = $this->model('Contact');
//     $contacts = $contactModel->getAllContacts($userId, $role);

//     // ✅ SEND the contacts and role to the view
//     $this->view('contacts/index', [
//         'contacts' => $contacts,
//         'role' => $role
//     ]);
// }

    public function index() {
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    $userId = $_SESSION['user_id'];
    $role = $_SESSION['user_role'];

    $contactModel = $this->model('Contact');
    $taskModel = $this->model('Task');

    $limit = 10;
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $offset = ($page - 1) * $limit;

    $contacts = $contactModel->getContactsPaginated($userId, $role, $limit, $offset);
    
    // Add task summaries to each contact
    foreach ($contacts as &$contact) {
        $tasks = $taskModel->getTasksByContactId($contact['id']);
        $contact['task_pending'] = 0;
        $contact['task_completed'] = 0;
    
        foreach ($tasks as $task) {
            if ($task['status'] === 'pending') $contact['task_pending']++;
            if ($task['status'] === 'completed') $contact['task_completed']++;
        }
    }
    
    
    $totalContacts = $contactModel->countContacts($userId, $role);
    $totalPages = ceil($totalContacts / $limit);

    $this->view('contacts/index', [
        'contacts' => $contacts,
        'role' => $role,
        'currentPage' => $page,
        'totalPages' => $totalPages
    ]);
}

    public function add() {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'user_id' => $_SESSION['user_id'],
                'name' => trim($_POST['name']),
                'email' => trim($_POST['email']),
                'phone' => trim($_POST['phone']),
                'company' => trim($_POST['company']),
                'assigned_user_id' => ($_SESSION['user_role'] === 'agent') ? $_SESSION['user_id'] : null
            ];


            $contactModel = $this->model('Contact');
            if ($contactModel->addContact($data)) {
                header("Location: " . BASE_URL . "/contacts");
                exit;
            } else {
                $this->view('contacts/add', ['error' => 'Failed to add contact', 'data' => $data]);
                return;
            }
        }

        $this->view('contacts/add');
    }

    public function edit($id = null) {
        session_start();
        if (!isset($_SESSION['user_id']) || !$id) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $contactModel = $this->model('Contact');
        $contact = $contactModel->getContactById($id);

        if (!$contact) {
            header("Location: " . BASE_URL . "/contacts");
            exit;
        }

        // Check ownership for non-admins
        if ($_SESSION['user_role'] !== 'admin' && $contact['user_id'] != $_SESSION['user_id']) {
            header("Location: " . BASE_URL . "/contacts");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'name' => trim($_POST['name']),
                'email' => trim($_POST['email']),
                'phone' => trim($_POST['phone']),
                'company' => trim($_POST['company'])
            ];

            if ($contactModel->updateContact($id, $data)) {
                header("Location: " . BASE_URL . "/contacts");
                exit;
            } else {
                $this->view('contacts/edit', ['error' => 'Failed to update contact', 'contact' => $contact]);
                return;
            }
        }

        $this->view('contacts/edit', ['contact' => $contact]);
    }

    public function delete($id = null) {
    session_start();
    if (!isset($_SESSION['user_id']) || !$id) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    $contactModel = $this->model('Contact');
    $contact = $contactModel->getContactById($id);

    if (!$contact) {
        header("Location: " . BASE_URL . "/contacts");
        exit;
    }

    // Check ownership for non-admins
    if ($_SESSION['user_role'] !== 'admin' && $contact['user_id'] != $_SESSION['user_id']) {
        header("Location: " . BASE_URL . "/contacts");
        exit;
    }

    $result = $contactModel->deleteContact($id);

    if (isset($result['error'])) {
        $_SESSION['error'] = $result['error'];
    } else {
        $_SESSION['success'] = '✅ Contact deleted successfully.';
    }

    header("Location: " . BASE_URL . "/contacts");
    exit;
}

    
    public function assign() {
    session_start();
    if ($_SESSION['user_role'] !== 'admin') {
        header("Location: " . BASE_URL . "/DashboardController/agent");
        exit;
    }

    $userModel = $this->model('User');
    $contactModel = $this->model('Contact');

    $agents = $userModel->getAgents();

    $search = $_GET['q'] ?? '';
    $page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
    $perPage = 10;
    $offset = ($page - 1) * $perPage;

    // Fetch paginated results
    $unassignedContacts = $contactModel->getUnassignedContacts($search, $perPage, $offset);

    // Count total results for pagination
    $totalCount = $contactModel->countUnassignedContacts($search);
    $totalPages = ceil($totalCount / $perPage);

    $this->view('contacts/assign', [
        'agents' => $agents,
        'unassignedContacts' => $unassignedContacts,
        'search' => $search,
        'page' => $page,
        'totalPages' => $totalPages
    ]);
}

    public function assignSubmit() {
        session_start();
        if ($_SESSION['user_role'] !== 'admin') {
            header("Location: " . BASE_URL . "/DashboardController/agent");
            exit;
        }
    
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $agentId = $_POST['agent_id'] ?? null;
            $contactIds = $_POST['contact_ids'] ?? [];
    
            $contactModel = $this->model('Contact');
    
            $errors = [];
            foreach ($contactIds as $contactId) {
                $success = $contactModel->assignContact($contactId, $agentId);
                if (!$success) {
                    $errors[] = "Contact ID $contactId already assigned.";
                }
            }
    
            $redirect = BASE_URL . "/contacts/assign?success=1";
            if (!empty($errors)) {
                $redirect .= "&error=" . urlencode(implode(", ", $errors));
            }
    
            header("Location: $redirect");
            exit;
        }
    
        header("Location: " . BASE_URL . "/contacts/assign");
    }

    public function manageAssignments() {
    session_start();

    if ($_SESSION['user_role'] !== 'admin') {
        header("Location: " . BASE_URL . "/DashboardController/agent");
        exit;
    }

    $contactModel = $this->model('Contact');
    $userModel = $this->model('User');

    $agents = $userModel->getAgents();

    $filter = [
        'q' => $_GET['q'] ?? '',
        'agent' => $_GET['agent'] ?? ''
    ];

    // Pagination setup
    $limit = 10;
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $offset = ($page - 1) * $limit;

    $contacts = $contactModel->getAllAssignedContacts($filter, $limit, $offset);
    $total = $contactModel->countAssignedContacts($filter);
    $totalPages = ceil($total / $limit);

    $this->view('contacts/manageAssignments', [
        'contacts' => $contacts,
        'agents' => $agents,
        'filter' => $filter,
        'currentPage' => $page,
        'totalPages' => $totalPages
    ]);
}

    public function bulkReassignAssigned() {
    session_start();
    if ($_SESSION['user_role'] !== 'admin') {
        header("Location: " . BASE_URL . "/DashboardController/agent");
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? 'reassign';
        $contactIds = $_POST['contact_ids'] ?? [];
        $contactModel = $this->model('Contact');

        if ($action === 'unassign') {
            foreach ($contactIds as $contactId) {
                $contactModel->updateAssignment($contactId, null);
            }
        } elseif ($action === 'reassign') {
            $newAgentId = intval($_POST['new_agent_id']);
            foreach ($contactIds as $contactId) {
                $contactModel->updateAssignment($contactId, $newAgentId);
            }
        }

        header("Location: " . BASE_URL . "/contacts/manageAssignments?success=1");
        exit;
    }

    header("Location: " . BASE_URL . "/contacts/manageAssignments");
    exit;
}

    public function notes($id = null) {
    session_start();

    if (!isset($_SESSION['user_id']) || !$id) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    $contactModel = $this->model('Contact');
    $noteModel = $this->model('Note'); // ⬅️ Create this if not yet created

    $contact = $contactModel->getContactById($id);

    if (!$contact) {
        header("Location: " . BASE_URL . "/contacts");
        exit;
    }

    // Check ownership if not admin
    if ($_SESSION['user_role'] !== 'admin' && $contact['user_id'] != $_SESSION['user_id']) {
        header("Location: " . BASE_URL . "/contacts");
        exit;
    }

    // ✅ Handle POST for adding a note
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['note_content'])) {
        $noteContent = trim($_POST['note_content']);
        $userId = $_SESSION['user_id'];

        if (!empty($noteContent)) {
            $noteModel->addNote([
                'contact_id' => $id,
                'user_id' => $userId,
                'content' => $noteContent
            ]);
        }

        header("Location: " . BASE_URL . "/contacts/notes/$id");
        exit;
    }

    // ✅ Load notes for this contact
    $notes = $noteModel->getNotesByContactId($id);

    $this->view('contacts/notes', [
        'contact' => $contact,
        'notes' => $notes
    ]);
}

    public function editNote($id = null) {
    session_start();
    $noteModel = $this->model('Note');
    $note = $noteModel->getNoteById($id);

    if (!$note || $note['user_id'] != $_SESSION['user_id']) {
        header("Location: " . BASE_URL . "/contacts");
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $newContent = trim($_POST['note_content']);
        $noteModel->updateNote($id, $_SESSION['user_id'], $newContent);
        header("Location: " . BASE_URL . "/contacts/notes/" . $note['contact_id']);
        exit;
    }

    $this->view('contacts/editNote', ['note' => $note]);
}

    public function deleteNote($id) {
    session_start();
    $noteModel = $this->model('Note');
    $note = $noteModel->getNoteById($id);

    if ($note && $note['user_id'] == $_SESSION['user_id']) {
        $noteModel->deleteNote($id, $_SESSION['user_id']);
    }

    header("Location: " . BASE_URL . "/contacts/notes/" . $note['contact_id']);
    exit;
}




    


}
