<?php
session_start();
require_once 'conexion.php';

/* ===============================
   SEGURIDAD
================================ */
if (!isset($_SESSION['rol'], $_SESSION['id_usuario']) || $_SESSION['rol'] !== 'propietario') {
    header("Location: login.php");
    exit;
}

/* ===============================
   VALIDAR ID
================================ */
if (!isset($_GET['id'])) {
    header("Location: propietario_dashboard.php");
    exit;
}

$id_arrendatario = (int)$_GET['id'];

/* ===============================
   OBTENER ARRENDATARIO
================================ */
$stmt = $conn->prepare("SELECT * FROM arrendatarios WHERE id_arrendatario = ?");
$stmt->bind_param("i", $id_arrendatario);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows !== 1) {
    header("Location: propietario_dashboard.php");
    exit;
}
$arr = $res->fetch_assoc();

/* ===============================
   ACOMPAÑANTES
================================ */
$stmt = $conn->prepare("SELECT * FROM acompanantes WHERE id_arrendatario = ?");
$stmt->bind_param("i", $id_arrendatario);
$stmt->execute();
$acompanantes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

/* ===============================
   GUARDAR
================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* ---------- IMAGEN ---------- */
    $imagen_actual = $arr['imagen'];
    $imagen_final = $imagen_actual;

    if (!empty($_FILES['imagen']['name'])) {
        $ext = pathinfo($_FILES['imagen']['name'], PATHINFO_EXTENSION);
        $nombre_img = 'arr_' . time() . '_' . rand(1000,9999) . '.' . $ext;

        if (move_uploaded_file(
            $_FILES['imagen']['tmp_name'],
            'uploads_arrendatarios/' . $nombre_img
        )) {
            $imagen_final = $nombre_img;

            // borrar imagen anterior
            if ($imagen_actual && file_exists('uploads_arrendatarios/' . $imagen_actual)) {
                unlink('uploads_arrendatarios/' . $imagen_actual);
            }
        }
    }

    /* ---------- UPDATE PRINCIPAL ---------- */
    $stmt = $conn->prepare("
        UPDATE arrendatarios SET
            nombre=?, rut=?, direccion=?, celular=?, email=?,
            fecha_inicio=?, fecha_salida=?,
            patente_vehiculo=?, autorizado_visitas=?,
            hora_ingreso=?, hora_salida=?,
            imagen=?, url_externa=?
        WHERE id_arrendatario=?
    ");

    $stmt->bind_param(
        "sssssssssssssi",
        $_POST['nombre'],
        $_POST['rut'],
        $_POST['direccion'],
        $_POST['celular'],
        $_POST['email'],
        $_POST['fecha_inicio'],
        $_POST['fecha_salida'],
        $_POST['patente_vehiculo'],
        $_POST['autorizado_visitas'],
        $_POST['hora_ingreso'],
        $_POST['hora_salida'],
        $imagen_final,
        $_POST['url_externa'],
        $id_arrendatario
    );

    $stmt->execute();

    /* ---------- ACOMPAÑANTES EXISTENTES ---------- */
    if (!empty($_POST['acompanantes'])) {
        foreach ($_POST['acompanantes'] as $id => $a) {
            if ($a['nombre'] && $a['rut']) {
                $u = $conn->prepare("
                    UPDATE acompanantes SET nombre=?, rut=? WHERE id_acompanante=?
                ");
                $u->bind_param("ssi", $a['nombre'], $a['rut'], $id);
                $u->execute();
            } else {
                $d = $conn->prepare("DELETE FROM acompanantes WHERE id_acompanante=?");
                $d->bind_param("i", $id);
                $d->execute();
            }
        }
    }

    /* ---------- NUEVOS ACOMPAÑANTES ---------- */
    if (!empty($_POST['nuevo_acompanantes'])) {
        foreach ($_POST['nuevo_acompanantes'] as $n) {
            if ($n['nombre'] && $n['rut']) {
                $i = $conn->prepare("
                    INSERT INTO acompanantes (id_arrendatario, nombre, rut)
                    VALUES (?, ?, ?)
                ");
                $i->bind_param("iss", $id_arrendatario, $n['nombre'], $n['rut']);
                $i->execute();
            }
        }
    }

    header("Location: propietario_dashboard.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Editar Arrendatario</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
</head>

<body class="hold-transition sidebar-mini">
<div class="wrapper">

<!-- NAVBAR -->
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu"><i class="fas fa-bars"></i></a>
</li>
</ul>
</nav>

<!-- SIDEBAR -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<a class="brand-link text-center">
<span class="brand-text">Sistema Arriendos</span>
</a>
</aside>

<!-- CONTENT -->
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<h1>Editar Arrendatario</h1>
</div>
</section>

<section class="content">
<div class="container-fluid">

<form method="POST" enctype="multipart/form-data">

<!-- DATOS -->
<div class="card card-primary card-outline">
<div class="card-header"><h3 class="card-title">Datos</h3></div>
<div class="card-body row">

<div class="col-md-6 mb-3">
<label>Nombre</label>
<input class="form-control" name="nombre" value="<?= htmlspecialchars($arr['nombre']) ?>" required>
</div>

<div class="col-md-6 mb-3">
<label>RUT</label>
<input class="form-control" name="rut" value="<?= htmlspecialchars($arr['rut']) ?>" required>
</div>

<div class="col-md-12 mb-3">
<label>Dirección</label>
<input class="form-control" name="direccion" value="<?= htmlspecialchars($arr['direccion']) ?>" required>
</div>

<div class="col-md-4 mb-3">
<label>Celular</label>
<input class="form-control" name="celular" value="<?= htmlspecialchars($arr['celular']) ?>">
</div>

<div class="col-md-4 mb-3">
<label>Email</label>
<input type="email" class="form-control" name="email" value="<?= htmlspecialchars($arr['email']) ?>">
</div>

<div class="col-md-4 mb-3">
<label>Patente</label>
<input class="form-control" name="patente_vehiculo" value="<?= htmlspecialchars($arr['patente_vehiculo']) ?>">
</div>

<div class="col-md-3 mb-3">
    <label>Fecha Inicio</label>
    <input type="date" class="form-control"
           name="fecha_inicio"
           value="<?= htmlspecialchars($arr['fecha_inicio']) ?>"
           required>
</div>

<div class="col-md-3 mb-3">
    <label>Hora Ingreso</label>
    <input type="time" class="form-control"
           name="hora_ingreso"
           value="<?= htmlspecialchars($arr['hora_ingreso']) ?>"
           required>
</div>

<div class="col-md-3 mb-3">
    <label>Fecha Salida</label>
    <input type="date" class="form-control"
           name="fecha_salida"
           value="<?= htmlspecialchars($arr['fecha_salida']) ?>"
           required>
</div>

<div class="col-md-3 mb-3">
    <label>Hora Salida</label>
    <input type="time" class="form-control"
           name="hora_salida"
           value="<?= htmlspecialchars($arr['hora_salida']) ?>"
           required>
</div>

<div class="col-md-6 mb-3">
<label>Imagen</label>
<input type="file" name="imagen" class="form-control">
<?php if ($arr['imagen']): ?>
<img src="uploads_arrendatarios/<?= $arr['imagen'] ?>" class="img-thumbnail mt-2" style="max-width:120px">
<?php endif; ?>
</div>

<div class="col-md-6 mb-3">
<label>URL externa</label>
<input class="form-control" name="url_externa" value="<?= htmlspecialchars($arr['url_externa']) ?>">
</div>

</div>
</div>

<!-- ACOMPAÑANTES -->
<div class="card card-secondary card-outline">
<div class="card-header"><h3 class="card-title">Acompañantes</h3></div>
<div class="card-body">

<?php foreach ($acompanantes as $a): ?>
<div class="row mb-2">
<div class="col-md-6">
<input class="form-control" name="acompanantes[<?= $a['id_acompanante'] ?>][nombre]" value="<?= $a['nombre'] ?>">
</div>
<div class="col-md-6">
<input class="form-control" name="acompanantes[<?= $a['id_acompanante'] ?>][rut]" value="<?= $a['rut'] ?>">
</div>
</div>
<?php endforeach; ?>

<button type="button" id="addAcomp" class="btn btn-outline-secondary btn-sm mt-2">
+ Agregar acompañante
</button>
<div id="nuevo"></div>

</div>
</div>

<div class="text-right">
<button class="btn btn-success"><i class="fas fa-save"></i> Guardar</button>
<a href="propietario_dashboard.php" class="btn btn-secondary">Cancelar</a>
</div>

</form>

</div>
</section>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

<script>
let i = 0;
$('#addAcomp').click(() => {
  $('#nuevo').append(`
    <div class="row mt-2">
      <div class="col-md-6">
        <input class="form-control" name="nuevo_acompanantes[${i}][nombre]" placeholder="Nombre">
      </div>
      <div class="col-md-6">
        <input class="form-control" name="nuevo_acompanantes[${i}][rut]" placeholder="RUT">
      </div>
    </div>
  `);
  i++;
});
</script>

</body>
</html>
