<?php

/**
 * Contact Controller
 * Handles contact management (CRUD operations)
 */
class ContactController {
    
    private $authController;
    private $contactModel;
    private $userModel;
    
    public function __construct() {
        $this->authController = new AuthController();
        $this->authController->requireAuth();
        
        $this->contactModel = new Contact();
        $this->userModel = new User();
    }
    
    /**
     * List all contacts
     */
    public function index() {
        $pageTitle = 'Contacts';
        
        // Get contacts based on user type
        if (isAdmin()) {
            // Admin can see all contacts
            $contacts = $this->contactModel->getAll();
        } else {
            // Regular user can only see their own contacts
            $contacts = $this->contactModel->getAll(getCurrentUserId());
        }
        
        // No need to get users list - contacts are always for current user unless admin
        
        require_once APP_PATH . '/views/admin/contacts/index.php';
    }
    
    /**
     * Show create contact form
     */
    public function create() {
        $pageTitle = 'Add New Contact';
        
        // No need to get users - contacts are always created for current user
        
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->store();
            return;
        }
        
        require_once APP_PATH . '/views/admin/contacts/create.php';
    }
    
    /**
     * Store new contact
     */
    private function store() {
        // Get and sanitize input
        // Contacts are always created for the current logged-in user
        $userId = getCurrentUserId();
        
        $fullName = sanitize($_POST['full_name'] ?? '');
        $contactNumber = sanitize($_POST['contact_number'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $designation = sanitize($_POST['designation'] ?? '');
        $village = sanitize($_POST['village'] ?? '');
        $dateOfBirth = sanitize($_POST['date_of_birth'] ?? '');
        $note = sanitize($_POST['note'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        
        // Validation
        $errors = [];
        
        if (empty($userId)) {
            $errors[] = 'User session error. Please login again.';
        }
        
        if (empty($fullName)) {
            $errors[] = 'Full name is required';
        }
        
        if (empty($contactNumber)) {
            $errors[] = 'Contact number is required';
        } elseif (!$this->contactModel->validatePhoneNumber($contactNumber)) {
            $errors[] = 'Contact number must be exactly 10 digits';
        }
        
        if (empty($dateOfBirth)) {
            $errors[] = 'Date of birth is required';
        }
        
        // Check for duplicate
        if (!empty($userId) && !empty($contactNumber)) {
            $duplicate = $this->contactModel->checkDuplicate($userId, $contactNumber);
            if ($duplicate) {
                $errors[] = 'This contact number already exists: ' . htmlspecialchars($duplicate->full_name);
            }
        }
        
        if (!empty($errors)) {
            $pageTitle = 'Add New Contact';
            $errorMessage = implode('<br>', $errors);
            require_once APP_PATH . '/views/admin/contacts/create.php';
            return;
        }
        
        // Create contact
        $contactId = $this->contactModel->create([
            'user_id' => $userId,
            'full_name' => $fullName,
            'contact_number' => $contactNumber,
            'email' => $email,
            'designation' => $designation,
            'village' => $village,
            'date_of_birth' => $dateOfBirth,
            'note' => $note,
            'status' => $status
        ]);
        
        if ($contactId) {
            $_SESSION['success'] = 'Contact created successfully';
            redirect(BASE_URL . '/admin/contacts');
        } else {
            $pageTitle = 'Add New Contact';
            $errorMessage = 'Failed to create contact';
            require_once APP_PATH . '/views/admin/contacts/create.php';
        }
    }
    
    /**
     * Show edit contact form
     */
    public function edit($id) {
        $pageTitle = 'Edit Contact';
        
        // Get contact
        $contact = $this->contactModel->findById($id);
        
        if (!$contact) {
            redirect(BASE_URL . '/admin/contacts?error=' . urlencode('Contact not found'));
            return;
        }
        
        // Check if user has permission to edit this contact
        if (!isAdmin() && $contact->user_id != getCurrentUserId()) {
            redirect(BASE_URL . '/admin/contacts?error=' . urlencode('You do not have permission to edit this contact'));
            return;
        }
        
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->update($id);
            return;
        }
        
        require_once APP_PATH . '/views/admin/contacts/edit.php';
    }
    
    /**
     * Update contact
     */
    private function update($id) {
        // Get contact
        $contact = $this->contactModel->findById($id);
        
        if (!$contact) {
            redirect(BASE_URL . '/admin/contacts?error=' . urlencode('Contact not found'));
            return;
        }
        
        // Check if user has permission to edit this contact
        if (!isAdmin() && $contact->user_id != getCurrentUserId()) {
            redirect(BASE_URL . '/admin/contacts?error=' . urlencode('You do not have permission to edit this contact'));
            return;
        }
        
        // Get and sanitize input
        // Keep the original user_id - contacts cannot be reassigned
        $userId = $contact->user_id;
        
        $fullName = sanitize($_POST['full_name'] ?? '');
        $contactNumber = sanitize($_POST['contact_number'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $designation = sanitize($_POST['designation'] ?? '');
        $village = sanitize($_POST['village'] ?? '');
        $dateOfBirth = sanitize($_POST['date_of_birth'] ?? '');
        $note = sanitize($_POST['note'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        
        // Validation
        $errors = [];
        
        if (empty($fullName)) {
            $errors[] = 'Full name is required';
        }
        
        if (empty($contactNumber)) {
            $errors[] = 'Contact number is required';
        } elseif (!$this->contactModel->validatePhoneNumber($contactNumber)) {
            $errors[] = 'Contact number must be exactly 10 digits';
        }
        
        if (empty($dateOfBirth)) {
            $errors[] = 'Date of birth is required';
        }
        
        // Check for duplicate (excluding current contact)
        if (!empty($userId) && !empty($contactNumber)) {
            $duplicate = $this->contactModel->checkDuplicate($userId, $contactNumber, $id);
            if ($duplicate) {
                $errors[] = 'This contact number already exists: ' . htmlspecialchars($duplicate->full_name);
            }
        }
        
        if (!empty($errors)) {
            $pageTitle = 'Edit Contact';
            $errorMessage = implode('<br>', $errors);
            require_once APP_PATH . '/views/admin/contacts/edit.php';
            return;
        }
        
        // Update contact
        $result = $this->contactModel->update($id, [
            'user_id' => $userId,
            'full_name' => $fullName,
            'contact_number' => $contactNumber,
            'email' => $email,
            'designation' => $designation,
            'village' => $village,
            'date_of_birth' => $dateOfBirth,
            'note' => $note,
            'status' => $status
        ]);
        
        if ($result) {
            $_SESSION['success'] = 'Contact updated successfully';
            redirect(BASE_URL . '/admin/contacts');
        } else{
            $pageTitle = 'Edit Contact';
            $errorMessage = 'Failed to update contact';
            require_once APP_PATH . '/views/admin/contacts/edit.php';
        }
    }
    
    /**
     * Delete contact
     */
    public function delete($id) {
        $contact = $this->contactModel->findById($id);
        
        if (!$contact) {
            $_SESSION['error'] = 'Contact not found';
            redirect(BASE_URL . '/admin/contacts');
            return;
        }
        
        // Check if user has permission to delete this contact
        if (!isAdmin() && $contact->user_id != getCurrentUserId()) {
            $_SESSION['error'] = 'You do not have permission to delete this contact';
            redirect(BASE_URL . '/admin/contacts');
            return;
        }
        
        $result = $this->contactModel->delete($id);
        
        if ($result) {
            $_SESSION['success'] = 'Contact deleted successfully';
            redirect(BASE_URL . '/admin/contacts');
        } else {
            $_SESSION['error'] = 'Failed to delete contact';
            redirect(BASE_URL . '/admin/contacts');
        }
    }
}
