<?php

/**
 * PWA Contact Controller
 * Handles contact management for PWA
 */
class PwaContactController {
    
    private $contactModel;
    
    public function __construct() {
        $this->contactModel = new Contact();
        $this->requireAuth();
    }
    
    /**
     * Show create contact form
     */
    public function create() {
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->store();
            return;
        }
        
        require_once APP_PATH . '/views/pwa/add-contact.php';
    }
    
    /**
     * Store new contact
     */
    private function store() {
        $userId = getCurrentUserId();
        
        $data = [
            'user_id' => $userId,
            'full_name' => sanitize($_POST['full_name'] ?? ''),
            'contact_number' => sanitize($_POST['phone_number'] ?? ''),
            'designation' => sanitize($_POST['designation'] ?? ''),
            'village' => sanitize($_POST['village'] ?? ''),
            'note' => sanitize($_POST['notes'] ?? ''),  // Model uses 'note' (singular)
            'date_of_birth' => sanitize($_POST['date_of_birth'] ?? '')
        ];
        
        // Validate phone number
        if (!preg_match('/^\d{10}$/', $data['contact_number'])) {
            $_SESSION['error'] = 'Phone number must be exactly 10 digits';
            redirect(BASE_URL . '/add-contact');
            return;
        }
        
        // Check for duplicates
        if ($this->contactModel->checkDuplicate($userId, $data['contact_number'])) {
            $_SESSION['error'] = 'Contact with this phone number already exists';
            redirect(BASE_URL . '/add-contact');
            return;
        }
        
        $contactId = $this->contactModel->create($data);
        
        if ($contactId) {
            $_SESSION['success'] = 'Contact created successfully!';
            redirect(BASE_URL . '/home');
        } else {
            $_SESSION['error'] = 'Failed to create contact';
            redirect(BASE_URL . '/add-contact');
        }
    }
    
    /**
     * Search contacts
     */
    public function search() {
        $userId = getCurrentUserId();
        $query = sanitize($_GET['q'] ?? '');
        
        if (!empty($query)) {
            // Search with user filtering based on user type
            if (isAdmin()) {
                $contacts = $this->contactModel->search($query);
            } else {
                $contacts = $this->contactModel->search($query, $userId);
            }
        } else {
            // Get all contacts based on user type
            if (isAdmin()) {
                $contacts = $this->contactModel->getAll();
            } else {
                $contacts = $this->contactModel->getByUser($userId);
            }
        }
        
        // Get user's default template
        $templateModel = new Template();
        $defaultTemplate = $templateModel->getUserDefaultTemplate($userId);
        
        require_once APP_PATH . '/views/pwa/search.php';
    }
    
    /**
     * Require authentication
     */
    private function requireAuth() {
        if (!isAuthenticated()) {
            redirect(BASE_URL . '/login');
            exit;
        }
    }
}
