<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    require_once __DIR__ . '/../includes/config.php';
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erro de configuração: ' . $e->getMessage()]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$admin = requireAuth();

try {
    switch ($method) {
        case 'GET':
            handleGet();
            break;
        case 'POST':
            handlePost($admin);
            break;
        case 'PUT':
            handlePut();
            break;
        case 'DELETE':
            handleDelete();
            break;
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Método não permitido']);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erro no banco de dados: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erro: ' . $e->getMessage()]);
}

function handleGet() {
    global $pdo;
    
    if (isset($_GET['action']) && $_GET['action'] === 'ranking') {
        $period = $_GET['period'] ?? 'month';
        $startDate = '';
        $endDate = date('Y-m-d');
        
        switch ($period) {
            case 'month':
                $startDate = date('Y-m-01');
                break;
            case 'semester':
                $month = date('n');
                $startMonth = $month <= 6 ? 1 : 7;
                $startDate = date('Y') . '-' . str_pad($startMonth, 2, '0', STR_PAD_LEFT) . '-01';
                break;
            case 'year':
                $startDate = date('Y-01-01');
                break;
            default:
                $startDate = date('Y-m-01');
        }
        
        $stmt = $pdo->prepare("
            SELECT 
                e.id,
                e.name,
                e.cpf,
                COALESCE(SUM(CASE WHEN a.absence_type = 'justified' THEN 1 ELSE 0 END), 0) as justified_count,
                COALESCE(SUM(CASE WHEN a.absence_type = 'unjustified' THEN 1 ELSE 0 END), 0) as unjustified_count,
                COUNT(a.id) as total_absences
            FROM employees e
            LEFT JOIN absences a ON e.id = a.employee_id 
                AND a.absence_date >= ? AND a.absence_date <= ?
            WHERE e.active = 1
            GROUP BY e.id, e.name, e.cpf
            ORDER BY total_absences ASC, e.name ASC
        ");
        $stmt->execute([$startDate, $endDate]);
        $ranking = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode($ranking);
        return;
    }
    
    if (isset($_GET['id'])) {
        $stmt = $pdo->prepare("
            SELECT a.*, e.name as employee_name 
            FROM absences a 
            JOIN employees e ON a.employee_id = e.id 
            WHERE a.id = ?
        ");
        $stmt->execute([$_GET['id']]);
        $absence = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($absence) {
            echo json_encode($absence);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Falta não encontrada']);
        }
        return;
    }
    
    $period = $_GET['period'] ?? 'month';
    $startDate = '';
    $endDate = date('Y-m-d');
    
    switch ($period) {
        case 'month':
            $startDate = date('Y-m-01');
            break;
        case 'semester':
            $month = date('n');
            $startMonth = $month <= 6 ? 1 : 7;
            $startDate = date('Y') . '-' . str_pad($startMonth, 2, '0', STR_PAD_LEFT) . '-01';
            break;
        case 'year':
            $startDate = date('Y-01-01');
            break;
        default:
            $startDate = date('Y-m-01');
    }
    
    $stmt = $pdo->prepare("
        SELECT a.*, e.name as employee_name 
        FROM absences a 
        JOIN employees e ON a.employee_id = e.id 
        WHERE a.absence_date >= ? AND a.absence_date <= ?
        ORDER BY a.absence_date DESC
    ");
    $stmt->execute([$startDate, $endDate]);
    $absences = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($absences);
}

function handlePost($admin) {
    global $pdo;
    
    $employee_id = $_POST['employee_id'] ?? null;
    $absence_type = $_POST['absence_type'] ?? 'unjustified';
    $absence_date = $_POST['absence_date'] ?? null;
    $description = $_POST['description'] ?? '';
    
    if (!$employee_id || !$absence_date) {
        http_response_code(400);
        echo json_encode(['error' => 'Funcionário e data são obrigatórios']);
        return;
    }
    
    $certificate_path = null;
    if (isset($_FILES['certificate']) && $_FILES['certificate']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../uploads/certificates/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileInfo = pathinfo($_FILES['certificate']['name']);
        $extension = strtolower($fileInfo['extension']);
        $allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif'];
        
        if (!in_array($extension, $allowedExtensions)) {
            http_response_code(400);
            echo json_encode(['error' => 'Tipo de arquivo não permitido. Use PDF, JPG, PNG ou GIF.']);
            return;
        }
        
        $fileName = 'cert_' . bin2hex(random_bytes(16)) . '.' . $extension;
        $filePath = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['certificate']['tmp_name'], $filePath)) {
            $certificate_path = 'uploads/certificates/' . $fileName;
        }
    }
    
    $id = 'abs-' . bin2hex(random_bytes(8));
    
    $stmt = $pdo->prepare("
        INSERT INTO absences (id, employee_id, absence_type, absence_date, description, certificate_path, created_by, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([
        $id,
        $employee_id,
        $absence_type,
        $absence_date,
        $description,
        $certificate_path,
        $admin['id']
    ]);
    
    echo json_encode(['success' => true, 'id' => $id]);
}

function handlePut() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        parse_str(file_get_contents('php://input'), $input);
    }
    
    $id = $input['id'] ?? $_GET['id'] ?? null;
    
    if (!$id) {
        http_response_code(400);
        echo json_encode(['error' => 'ID é obrigatório']);
        return;
    }
    
    $fields = [];
    $params = [];
    
    if (isset($input['employee_id'])) {
        $fields[] = "employee_id = ?";
        $params[] = $input['employee_id'];
    }
    if (isset($input['absence_type'])) {
        $fields[] = "absence_type = ?";
        $params[] = $input['absence_type'];
    }
    if (isset($input['absence_date'])) {
        $fields[] = "absence_date = ?";
        $params[] = $input['absence_date'];
    }
    if (isset($input['description'])) {
        $fields[] = "description = ?";
        $params[] = $input['description'];
    }
    
    if (empty($fields)) {
        http_response_code(400);
        echo json_encode(['error' => 'Nenhum campo para atualizar']);
        return;
    }
    
    $params[] = $id;
    $sql = "UPDATE absences SET " . implode(", ", $fields) . " WHERE id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    echo json_encode(['success' => true]);
}

function handleDelete() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $id = $input['id'] ?? $_GET['id'] ?? null;
    
    if (!$id) {
        http_response_code(400);
        echo json_encode(['error' => 'ID é obrigatório']);
        return;
    }
    
    $stmt = $pdo->prepare("SELECT certificate_path FROM absences WHERE id = ?");
    $stmt->execute([$id]);
    $absence = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($absence && $absence['certificate_path']) {
        $filePath = __DIR__ . '/../' . $absence['certificate_path'];
        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }
    
    $stmt = $pdo->prepare("DELETE FROM absences WHERE id = ?");
    $stmt->execute([$id]);
    
    echo json_encode(['success' => true]);
}
