<?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 b.*, a.name as created_by_name FROM branches b LEFT JOIN administrators a ON b.created_by = a.id WHERE b.id = ?');
            $stmt->execute([$id]);
            $branch = $stmt->fetch();
            if ($branch) {
                jsonResponse($branch);
            } else {
                jsonResponse(['error' => 'Filial não encontrada'], 404);
            }
        } else {
            $stmt = $pdo->query('SELECT b.*, a.name as created_by_name FROM branches b LEFT JOIN administrators a ON b.created_by = a.id ORDER BY b.name');
            jsonResponse($stmt->fetchAll());
        }
        break;

    case 'POST':
        $data = getJsonInput();
        $id = generateId();
        $stmt = $pdo->prepare('INSERT INTO branches (id, name, address, active, created_by) VALUES (?, ?, ?, ?, ?)');
        $stmt->execute([
            $id,
            $data['name'] ?? '',
            $data['address'] ?? null,
            $data['isActive'] ?? TRUE,
            $createdBy
        ]);
        
        $stmt = $pdo->prepare('SELECT b.*, a.name as created_by_name FROM branches b LEFT JOIN administrators a ON b.created_by = a.id WHERE b.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 branches SET name = ?, address = ?, active = ? WHERE id = ?');
        $stmt->execute([
            $data['name'] ?? '',
            $data['address'] ?? null,
            $data['isActive'] ?? TRUE,
            $id
        ]);
        
        if ($stmt->rowCount() > 0 || true) {
            $stmt = $pdo->prepare('SELECT b.*, a.name as created_by_name FROM branches b LEFT JOIN administrators a ON b.created_by = a.id WHERE b.id = ?');
            $stmt->execute([$id]);
            $branch = $stmt->fetch();
            if ($branch) {
                jsonResponse($branch);
            } else {
                jsonResponse(['error' => 'Filial não encontrada'], 404);
            }
        }
        break;

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

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