<?php

use PHPUnit\Framework\TestCase;

require_once __DIR__ . '/../../api/models/Project.php';

class ProjectModelTest extends TestCase
{
    private $project;
    
    protected function setUp(): void
    {
        $this->project = new Project();
    }

    public function testValidateProjectData()
    {
        $validData = [
            'nombre_proyecto' => 'Inventario Finca El Pinar',
            'nombre_finca' => 'Finca El Pinar',
            'departamento' => 'Guatemala',
            'municipio' => 'San José Pinula',
            'aldea' => 'El Pinar',
            'nombre_propietario' => 'Carlos Mendoza',
            'nombre_regente_forestal' => 'Ing. María García'
        ];
        
        $result = $this->project->validateProjectData($validData);
        $this->assertTrue($result['valid']);
        $this->assertEmpty($result['errors']);
    }

    public function testValidateProjectDataWithMissingFields()
    {
        $incompleteData = [
            'nombre_proyecto' => 'Inventario Finca El Pinar',
            'nombre_finca' => 'Finca El Pinar'
            // Faltan campos requeridos
        ];
        
        $result = $this->project->validateProjectData($incompleteData);
        $this->assertFalse($result['valid']);
        $this->assertGreaterThan(0, count($result['errors']));
    }

    public function testValidateProjectDataWithInvalidDepartment()
    {
        $invalidData = [
            'nombre_proyecto' => 'Inventario Finca El Pinar',
            'nombre_finca' => 'Finca El Pinar',
            'departamento' => 'Departamento Inexistente',
            'municipio' => 'San José Pinula',
            'aldea' => 'El Pinar',
            'nombre_propietario' => 'Carlos Mendoza',
            'nombre_regente_forestal' => 'Ing. María García'
        ];
        
        $result = $this->project->validateProjectData($invalidData);
        $this->assertFalse($result['valid']);
        $this->assertContains('Departamento inválido', $result['errors']);
    }

    public function testSanitizeProjectData()
    {
        $dirtyData = [
            'nombre_proyecto' => '  Inventario Finca El Pinar  ',
            'nombre_finca' => '  FINCA EL PINAR  ',
            'departamento' => 'guatemala',
            'municipio' => '  san josé pinula  ',
            'aldea' => 'EL PINAR',
            'nombre_propietario' => '  carlos mendoza  ',
            'nombre_regente_forestal' => '  ING. MARÍA GARCÍA  '
        ];
        
        $cleanData = $this->project->sanitizeProjectData($dirtyData);
        
        $this->assertEquals('Inventario Finca El Pinar', $cleanData['nombre_proyecto']);
        $this->assertEquals('Finca El Pinar', $cleanData['nombre_finca']);
        $this->assertEquals('Guatemala', $cleanData['departamento']);
        $this->assertEquals('San José Pinula', $cleanData['municipio']);
        $this->assertEquals('El Pinar', $cleanData['aldea']);
        $this->assertEquals('Carlos Mendoza', $cleanData['nombre_propietario']);
        $this->assertEquals('Ing. María García', $cleanData['nombre_regente_forestal']);
    }

    public function testGetValidDepartments()
    {
        $departments = $this->project->getValidDepartments();
        
        $this->assertIsArray($departments);
        $this->assertContains('Guatemala', $departments);
        $this->assertContains('Alta Verapaz', $departments);
        $this->assertContains('Petén', $departments);
        $this->assertContains('Quetzaltenango', $departments);
        $this->assertGreaterThan(20, count($departments)); // Guatemala tiene 22 departamentos
    }

    public function testValidateDocumentUpload()
    {
        $validFile = [
            'name' => 'documento_tenencia.pdf',
            'type' => 'application/pdf',
            'size' => 1024 * 1024, // 1MB
            'tmp_name' => '/tmp/phptest',
            'error' => UPLOAD_ERR_OK
        ];
        
        $result = $this->project->validateDocumentUpload($validFile);
        $this->assertTrue($result['valid']);
        $this->assertEmpty($result['errors']);
    }

    public function testValidateDocumentUploadWithInvalidType()
    {
        $invalidFile = [
            'name' => 'documento.txt',
            'type' => 'text/plain',
            'size' => 1024,
            'tmp_name' => '/tmp/phptest',
            'error' => UPLOAD_ERR_OK
        ];
        
        $result = $this->project->validateDocumentUpload($invalidFile);
        $this->assertFalse($result['valid']);
        $this->assertContains('Solo se permiten archivos PDF', $result['errors']);
    }

    public function testValidateDocumentUploadWithLargeFile()
    {
        $largeFile = [
            'name' => 'documento_grande.pdf',
            'type' => 'application/pdf',
            'size' => 10 * 1024 * 1024, // 10MB (mayor al límite de 5MB)
            'tmp_name' => '/tmp/phptest',
            'error' => UPLOAD_ERR_OK
        ];
        
        $result = $this->project->validateDocumentUpload($largeFile);
        $this->assertFalse($result['valid']);
        $this->assertContains('El archivo es demasiado grande', $result['errors']);
    }

    public function testGenerateProjectCode()
    {
        $projectData = [
            'departamento' => 'Guatemala',
            'municipio' => 'San José Pinula',
            'nombre_finca' => 'Finca El Pinar'
        ];
        
        $code = $this->project->generateProjectCode($projectData);
        
        $this->assertIsString($code);
        $this->assertNotEmpty($code);
        $this->assertStringContainsString('GT', $code); // Guatemala
        $this->assertStringContainsString('SJP', $code); // San José Pinula
    }

    public function testCalculateProjectStats()
    {
        $projectId = 1;
        $mockRodales = [
            ['area_ha' => 2.5],
            ['area_ha' => 3.2],
            ['area_ha' => 1.8]
        ];
        
        $stats = $this->project->calculateProjectStats($projectId, $mockRodales);
        
        $this->assertArrayHasKey('total_rodales', $stats);
        $this->assertArrayHasKey('area_total_ha', $stats);
        $this->assertArrayHasKey('area_promedio_ha', $stats);
        
        $this->assertEquals(3, $stats['total_rodales']);
        $this->assertEquals(7.5, $stats['area_total_ha']);
        $this->assertEquals(2.5, $stats['area_promedio_ha']);
    }

    public function testValidateProjectPermissions()
    {
        // Test admin permissions
        $this->assertTrue($this->project->canUserAccessProject('Administrador', 1, 1));
        
        // Test regente permissions (can access own projects)
        $this->assertTrue($this->project->canUserAccessProject('Regente', 1, 1));
        $this->assertFalse($this->project->canUserAccessProject('Regente', 1, 2));
        
        // Test técnico permissions (read-only access to assigned projects)
        $this->assertTrue($this->project->canUserReadProject('Técnico de Campo', 1));
        $this->assertFalse($this->project->canUserModifyProject('Técnico de Campo', 1));
    }
}