<?php
require_once __DIR__ . '/../includes/config.php';

$createdBy = requireAuth();
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                $stmt = $pdo->prepare("
                    SELECT o.*, e.name as employee_name, a.name as created_by_name 
                    FROM overtime_hours o 
                    LEFT JOIN employees e ON o.employee_id = e.id 
                    LEFT JOIN administrators a ON o.created_by = a.id
                    WHERE o.id = ?
                ");
                $stmt->execute([$_GET['id']]);
                $record = $stmt->fetch();
                
                if ($record) {
                    jsonResponse($record);
                } else {
                    jsonResponse(['error' => 'Registro não encontrado'], 404);
                }
            } else {
                $employeeId = $_GET['employee_id'] ?? null;
                $referenceMonth = $_GET['reference_month'] ?? null;
                
                $sql = "
                    SELECT o.*, e.name as employee_name, a.name as created_by_name 
                    FROM overtime_hours o 
                    LEFT JOIN employees e ON o.employee_id = e.id 
                    LEFT JOIN administrators a ON o.created_by = a.id
                ";
                $params = [];
                $conditions = [];
                
                if ($employeeId) {
                    $conditions[] = "o.employee_id = ?";
                    $params[] = $employeeId;
                }
                
                if ($referenceMonth) {
                    $conditions[] = "o.reference_month = ?";
                    $params[] = $referenceMonth;
                }
                
                if (!empty($conditions)) {
                    $sql .= " WHERE " . implode(" AND ", $conditions);
                }
                
                $sql .= " ORDER BY o.overtime_date DESC, o.created_at DESC";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                jsonResponse($stmt->fetchAll());
            }
            break;

        case 'POST':
            $data = getJsonInput();
            
            if (empty($data['employee_id'])) {
                jsonResponse(['error' => 'Funcionário é obrigatório'], 400);
            }
            if (empty($data['hours']) || $data['hours'] <= 0) {
                jsonResponse(['error' => 'Quantidade de horas é obrigatória e deve ser maior que zero'], 400);
            }
            if (empty($data['overtime_date'])) {
                jsonResponse(['error' => 'Data é obrigatória'], 400);
            }
            
            $id = generateId();
            $overtimeDate = $data['overtime_date'];
            $referenceMonth = $data['reference_month'] ?? substr($overtimeDate, 0, 7);
            
            $stmt = $pdo->prepare("
                INSERT INTO overtime_hours (id, employee_id, hours, overtime_date, reason, reference_month, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $id,
                $data['employee_id'],
                $data['hours'],
                $overtimeDate,
                $data['reason'] ?? null,
                $referenceMonth,
                $createdBy
            ]);
            
            $stmt = $pdo->prepare("
                SELECT o.*, e.name as employee_name 
                FROM overtime_hours o 
                LEFT JOIN employees e ON o.employee_id = e.id 
                WHERE o.id = ?
            ");
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch(), 201);
            break;

        case 'PUT':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $data = getJsonInput();
            
            if (empty($data['employee_id'])) {
                jsonResponse(['error' => 'Funcionário é obrigatório'], 400);
            }
            if (empty($data['hours']) || $data['hours'] <= 0) {
                jsonResponse(['error' => 'Quantidade de horas é obrigatória e deve ser maior que zero'], 400);
            }
            if (empty($data['overtime_date'])) {
                jsonResponse(['error' => 'Data é obrigatória'], 400);
            }
            
            $overtimeDate = $data['overtime_date'];
            $referenceMonth = $data['reference_month'] ?? substr($overtimeDate, 0, 7);
            
            $stmt = $pdo->prepare("
                UPDATE overtime_hours 
                SET employee_id = ?, hours = ?, overtime_date = ?, reason = ?, reference_month = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $data['employee_id'],
                $data['hours'],
                $overtimeDate,
                $data['reason'] ?? null,
                $referenceMonth,
                $id
            ]);
            
            $stmt = $pdo->prepare("
                SELECT o.*, e.name as employee_name 
                FROM overtime_hours o 
                LEFT JOIN employees e ON o.employee_id = e.id 
                WHERE o.id = ?
            ");
            $stmt->execute([$id]);
            $result = $stmt->fetch();
            
            if ($result) {
                jsonResponse($result);
            } else {
                jsonResponse(['error' => 'Registro não encontrado'], 404);
            }
            break;

        case 'DELETE':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $stmt = $pdo->prepare("DELETE FROM overtime_hours WHERE id = ?");
            $stmt->execute([$id]);
            
            if ($stmt->rowCount() > 0) {
                jsonResponse(['success' => true, 'message' => 'Registro excluído com sucesso']);
            } else {
                jsonResponse(['error' => 'Registro não encontrado'], 404);
            }
            break;

        default:
            jsonResponse(['error' => 'Método não permitido'], 405);
    }
} catch (PDOException $e) {
    jsonResponse(['error' => 'Erro no banco de dados: ' . $e->getMessage()], 500);
}
