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

$createdBy = requireAuth();

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;

switch ($method) {
    case 'GET':
        if ($id) {
            $stmt = $pdo->prepare('SELECT p.*, a.name as created_by_name FROM partners p LEFT JOIN administrators a ON p.created_by = a.id WHERE p.id = ?');
            $stmt->execute([$id]);
            $partner = $stmt->fetch();
            if ($partner) {
                jsonResponse($partner);
            } else {
                jsonResponse(['error' => 'Parceiro não encontrado'], 404);
            }
        } else {
            $stmt = $pdo->query('SELECT p.*, a.name as created_by_name FROM partners p LEFT JOIN administrators a ON p.created_by = a.id ORDER BY p.name');
            jsonResponse($stmt->fetchAll());
        }
        break;

    case 'POST':
        $data = getJsonInput();
        $id = generateId();
        $stmt = $pdo->prepare('INSERT INTO partners (id, name, phone, email, active, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $id,
            $data['name'] ?? '',
            $data['phone'] ?? null,
            $data['email'] ?? null,
            $data['isActive'] ?? TRUE,
            $createdBy
        ]);
        
        $stmt = $pdo->prepare('SELECT p.*, a.name as created_by_name FROM partners p LEFT JOIN administrators a ON p.created_by = a.id WHERE p.id = ?');
        $stmt->execute([$id]);
        jsonResponse($stmt->fetch(), 201);
        break;

    case 'PUT':
        if (!$id) jsonResponse(['error' => 'ID obrigatório'], 400);
        $data = getJsonInput();
        $stmt = $pdo->prepare('UPDATE partners SET name = ?, phone = ?, email = ?, active = ? WHERE id = ?');
        $stmt->execute([
            $data['name'] ?? '',
            $data['phone'] ?? null,
            $data['email'] ?? null,
            $data['isActive'] ?? TRUE,
            $id
        ]);
        
        $stmt = $pdo->prepare('SELECT p.*, a.name as created_by_name FROM partners p LEFT JOIN administrators a ON p.created_by = a.id WHERE p.id = ?');
        $stmt->execute([$id]);
        $partner = $stmt->fetch();
        if ($partner) {
            jsonResponse($partner);
        } else {
            jsonResponse(['error' => 'Parceiro não encontrado'], 404);
        }
        break;

    case 'DELETE':
        if (!$id) jsonResponse(['error' => 'ID obrigatório'], 400);
        $stmt = $pdo->prepare('UPDATE partners SET active = FALSE WHERE id = ?');
        $stmt->execute([$id]);
        if ($stmt->rowCount() > 0) {
            jsonResponse(['success' => true]);
        } else {
            jsonResponse(['error' => 'Parceiro não encontrado'], 404);
        }
        break;

    default:
        jsonResponse(['error' => 'Método não permitido'], 405);
}
