<?php
session_start();
require_once __DIR__ . '/db/config.php';

// Get installation ID from URL
$id = $_GET['id'] ?? null;
if (!$id) {
    header("Location: index.php");
    exit;
}

// Fetch installation data
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM installations WHERE id = ?");
$stmt->execute([$id]);
$installation = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$installation) {
    $_SESSION['message'] = 'Instalação não encontrada.';
    $_SESSION['message_type'] = 'danger';
    header("Location: index.php");
    exit;
}

// Fetch images for this installation
$img_stmt = $pdo->prepare("SELECT * FROM installation_images WHERE installation_id = ?");
$img_stmt->execute([$id]);
$images = $img_stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Instalação #<?php echo htmlspecialchars($installation['id']); ?> - iload net Solutions</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>

    <div class="sidebar">
        <a class="navbar-brand" href="index.php">iload net Solutions</a>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="index.php">
                    <i class="bi bi-grid-1x2-fill"></i> Painel de Controle
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="add_installation.php">
                    <i class="bi bi-plus-circle-fill"></i> Adicionar Instalação
                </a>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <nav class="top-navbar navbar navbar-expand">
            <div class="container-fluid">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-person-circle me-1"></i> Administrador
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="#">Perfil</a></li>
                            <li><a class="dropdown-item" href="#">Sair</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="container-fluid">
            <div class="row justify-content-center">
                <div class="col-lg-8 col-md-10">
                    <div class="card shadow-sm mb-4">
                        <div class="card-header py-3">
                            <h1 class="h3 mb-0 text-gray-800">Editar Instalação #<?php echo htmlspecialchars($installation['id']); ?></h1>
                        </div>
                        <div class="card-body">
                            <form action="update_installation.php" method="POST" enctype="multipart/form-data">
                                <input type="hidden" name="id" value="<?php echo htmlspecialchars($installation['id']); ?>">
                                
                                <div class="mb-3">
                                    <label for="client_name" class="form-label">Nome do Cliente</label>
                                    <input type="text" class="form-control" id="client_name" name="client_name" value="<?php echo htmlspecialchars($installation['client_name'] ?? ''); ?>" required style="width: 100%;">
                                </div>
                                <div class="mb-3">
                                    <label for="address" class="form-label">Endereço</label>
                                    <input type="text" class="form-control" id="address" name="address" value="<?php echo htmlspecialchars($installation['address'] ?? ''); ?>" required style="width: 100%;">
                                </div>
                                <div class="mb-3">
                                    <label for="technician_name" class="form-label">Nome do Técnico</label>
                                    <input type="text" class="form-control" id="technician_name" name="technician_name" value="<?php echo htmlspecialchars($installation['technician_name'] ?? ''); ?>" required style="width: 100%;">
                                </div>
                                <div class="mb-3">
                                    <label for="installation_date" class="form-label">Data da Instalação</label>
                                    <?php
                                    $installation_date_formatted = '';
                                    if (!empty($installation['installation_date'])) {
                                        $timestamp = strtotime($installation['installation_date']);
                                        if ($timestamp && $timestamp > 0) {
                                            $installation_date_formatted = date('Y-m-d', $timestamp);
                                        }
                                    }
                                    ?>
                                    <input type="date" class="form-control" id="installation_date" name="installation_date" value="<?php echo htmlspecialchars($installation_date_formatted); ?>" style="width: 100%;">
                                </div>

                                <hr>
                                <h5 class="mb-3">Dados Elétricos</h5>

                                <div class="mb-3">
                                    <label for="voltage" class="form-label">Tensão (V)</label>
                                    <input type="text" class="form-control" id="voltage" name="voltage" value="<?php echo htmlspecialchars($installation['voltage'] ?? ''); ?>" style="width: 100%;">
                                </div>
                                <div class="mb-3">
                                    <label for="phase_neutral_ground" class="form-label">Fase-Neutro-Terra</label>
                                    <input type="text" class="form-control" id="phase_neutral_ground" name="phase_neutral_ground" value="<?php echo htmlspecialchars($installation['phase_neutral_ground'] ?? ''); ?>" style="width: 100%;">
                                </div>
                                <div class="mb-3">
                                    <label for="breaker_output" class="form-label">Saída do Disjuntor</label>
                                    <input type="text" class="form-control" id="breaker_output" name="breaker_output" value="<?php echo htmlspecialchars($installation['breaker_output'] ?? ''); ?>" style="width: 100%;">
                                </div>
                                <div class="mb-3">
                                    <label for="observations" class="form-label">Observações</label>
                                    <textarea class="form-control" id="observations" name="observations" rows="3" style="width: 100%;"><?php echo htmlspecialchars($installation['observations'] ?? ''); ?></textarea>
                                </div>

                                <div class="mb-3">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status" style="width: 100%;">
                                        <option value="ativo" <?php echo ($installation['status'] === 'ativo') ? 'selected' : ''; ?>>Ativo</option>
                                        <option value="Manutencao" <?php echo ($installation['status'] === 'Manutencao') ? 'selected' : ''; ?>>Manutenção</option>
                                        <option value="Manutenção Parcial" <?php echo ($installation['status'] === 'Manutenção Parcial') ? 'selected' : ''; ?>>Manutenção Parcial</option>
                                        <option value="inativo" <?php echo ($installation['status'] === 'inativo') ? 'selected' : ''; ?>>Inativo</option>
                                    </select>
                                </div>

                                <hr>
                                <h5 class="mb-3">Imagens</h5>
                                <div class="mb-3">
                                    <label for="images" class="form-label">Adicionar Novas Imagens</label>
                                    <input type="file" class="form-control" id="images" name="images[]" multiple accept="image/*" style="width: 100%;">
                                </div>
                                
                                <?php if (!empty($images)): ?>
                                <p>Imagens existentes:</p>
                                <div class="row">
                                    <?php foreach ($images as $image): ?>
                                        <div class="col-md-3 mb-3">
                                            <img src="<?php echo htmlspecialchars($image['image_path']); ?>" class="img-thumbnail" alt="Imagem da instalação">
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php else: ?>
                                    <p class="text-muted">Nenhuma imagem existente.</p>
                                <?php endif; ?>


                                <hr class="my-4">
                                <div class="d-flex justify-content-end">
                                    <a href="index.php" class="btn btn-secondary me-2">Cancelar</a>
                                    <button type="submit" class="btn btn-primary">Salvar Alterações</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
