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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$id = $_POST['id'] ?? null;
$client_name = trim($_POST['client_name'] ?? '');
$address = trim($_POST['address'] ?? '');
$technician_name = trim($_POST['technician_name'] ?? '');
$installation_date = !empty($_POST['installation_date']) ? trim($_POST['installation_date']) : null;
$status = trim($_POST['status'] ?? 'ativo');
$observations = trim($_POST['observations'] ?? '');
$voltage = trim($_POST['voltage'] ?? null);
$phase_neutral_ground = trim($_POST['phase_neutral_ground'] ?? null);
$breaker_output = trim($_POST['breaker_output'] ?? null);

if (!$id) {
    $_SESSION['message'] = "ID da instalação é inválido.";
    $_SESSION['message_type'] = "danger";
    header('Location: index.php');
    exit;
}

$pdo = db();
try {
    $sql = "UPDATE installations SET client_name = ?, address = ?, technician_name = ?, status = ?, observations = ?, voltage = ?, phase_neutral_ground = ?, breaker_output = ?";
    $params = [
        $client_name,
        $address,
        $technician_name,
        $status,
        $observations,
        $voltage,
        $phase_neutral_ground,
        $breaker_output
    ];

    if ($installation_date) {
        $sql .= ", installation_date = ?";
        $params[] = $installation_date;
    }

    $sql .= " WHERE id = ?";
    $params[] = $id;

    $pdo->beginTransaction();

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    // Handle new image uploads
    if (isset($_FILES['images'])) {
        $upload_dir = __DIR__ . '/assets/uploads/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0775, true);
        }

        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];

        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['images']['name'][$key];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                if (in_array($file_ext, $allowed_ext)) {
                    $new_file_name = time() . '_' . uniqid() . '_' . basename($file_name);
                    $dest_path = $upload_dir . $new_file_name;

                    if (move_uploaded_file($tmp_name, $dest_path)) {
                        $image_path = 'assets/uploads/' . $new_file_name;
                        $img_stmt = $pdo->prepare("INSERT INTO installation_images (installation_id, image_path) VALUES (?, ?)");
                        $img_stmt->execute([$id, $image_path]);
                    } else {
                        throw new Exception('Falha ao mover o arquivo enviado: ' . $file_name);
                    }
                } else {
                    throw new Exception('Tipo de arquivo inválido: ' . $file_name);
                }
            }
        }
    }

    $pdo->commit();
    $_SESSION['message'] = "Instalação #{$id} atualizada com sucesso!";
    $_SESSION['message_type'] = "success";

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    $_SESSION['message'] = "Erro ao atualizar a instalação: " . $e->getMessage();
    $_SESSION['message_type'] = "danger";
    header("Location: edit_installation.php?id={$id}");
    exit;
}

header("Location: index.php");
exit;
