<?php

/**
 * Excel Controller
 * Handles Excel import/export functionality
 */
class ExcelController {
    
    private $excelService;
    private $contactModel;
    private $userModel;
    
    public function __construct() {
        $this->excelService = new ExcelService();
        $this->contactModel = new Contact();
        $this->userModel = new User();
        
        // Require authentication
        $this->requireAuth();
    }
    
    /**
     * Default action - redirect to import page
     */
    public function index() {
        redirect(BASE_URL . '/admin/excel/import');
    }
    
    /**
     * Display import page
     */
    public function import() {
        // Get users based on user type
        // Regular users can only import for themselves
        if (isAdmin()) {
            $users = $this->userModel->getAll();
        } else {
            // For regular users, only show themselves
            $currentUser = $this->userModel->findById(getCurrentUserId());
            $users = $currentUser ? [$currentUser->toArray()] : [];
        }
        
        require_once APP_PATH . '/views/admin/excel/import.php';
    }
    
    /**
     * Process Excel import
     */
    public function processImport() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect(BASE_URL . '/admin/excel/import');
            return;
        }
        
        // Validate file upload
        if (!isset($_FILES['excel_file']) || $_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['error'] = 'Please select a valid Excel file';
            redirect(BASE_URL . '/admin/excel/import');
            return;
        }
        
        // Get user ID - for regular users, force to their own ID
        if (isAdmin()) {
            $userId = intval($_POST['user_id'] ?? 0);
            if ($userId <= 0) {
                $_SESSION['error'] = 'Please select a user';
                redirect(BASE_URL . '/admin/excel/import');
                return;
            }
        } else {
            $userId = getCurrentUserId();
        }
        
        // Process the import
        $result = $this->excelService->importContacts($_FILES['excel_file'], $userId);
        
        if ($result['imported'] > 0 || $result['skipped'] > 0) {
            $_SESSION['success'] = "Import completed! {$result['imported']} contacts imported, {$result['skipped']} skipped";
            if (!empty($result['errors'])) {
                $_SESSION['import_errors'] = $result['errors'];
            }
        } else {
            $_SESSION['error'] = !empty($result['errors']) ? implode(', ', $result['errors']) : 'Import failed';
        }
        
        redirect(BASE_URL . '/admin/excel/import');
    }
    
    /**
     * Display export page
     */
    public function export() {
        // Get users based on user type
        if (isAdmin()) {
            $users = $this->userModel->getAll();
        } else {
            // For regular users, only show themselves
            $currentUser = $this->userModel->findById(getCurrentUserId());
            $users = $currentUser ? [$currentUser->toArray()] : [];
        }
        
        require_once APP_PATH . '/views/admin/excel/export.php';
    }
    
    /**
     * Process Excel export
     */
    public function processExport() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect(BASE_URL . '/admin/excel/export');
            return;
        }
        
        // Get user ID - for regular users, force to their own ID
        if (isAdmin()) {
            $userId = intval($_POST['user_id'] ?? 0); // 0 = all users for admin
        } else {
            $userId = getCurrentUserId();
        }
        
        // Export contacts
        $result = $this->excelService->exportContacts($userId);
        
        if ($result['success']) {
            // Download the file
            $filePath = $result['file'];
            
            if (file_exists($filePath)) {
                // Determine content type
                $extension = pathinfo($filePath, PATHINFO_EXTENSION);
                $contentType = $extension === 'zip' ? 'application/zip' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                
                header('Content-Type: ' . $contentType);
                header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
                header('Content-Length: ' . filesize($filePath));
                header('Cache-Control: max-age=0');
                
                readfile($filePath);
                
                // Delete the file after download
                unlink($filePath);
                exit;
            } else {
                $_SESSION['error'] = 'Export file not found';
                redirect(BASE_URL . '/admin/excel/export');
            }
        } else {
            $_SESSION['error'] = $result['message'] ?? 'Export failed';
            redirect(BASE_URL . '/admin/excel/export');
        }
    }
    
    /**
     * Download sample template
     */
    public function downloadTemplate() {
        $filePath = $this->excelService->createSampleTemplate();
        
        if ($filePath && file_exists($filePath)) {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment; filename="contacts_template.xlsx"');
            header('Content-Length: ' . filesize($filePath));
            header('Cache-Control: max-age=0');
            
            readfile($filePath);
            
            // Delete the file after download
            unlink($filePath);
            exit;
        } else {
            $_SESSION['error'] = 'Failed to create sample template';
            redirect(BASE_URL . '/admin/excel/import');
        }
    }
    
    /**
     * Require authentication
     */
    private function requireAuth() {
        if (!isAuthenticated()) {
            redirect(BASE_URL . '/admin/login');
            exit;
        }
    }
}
