<?php
include 'dashboard.php';
require 'db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if (!isset($_GET['id'])) {
    header("Location: my_properties.php");
    exit();
}

$property_id = intval($_GET['id']);
$user_id = $_SESSION['user_id'];

/** =======================
 *  FETCH MAIN PROPERTY
 *  ======================= */
$stmt = $conn->prepare("SELECT * FROM properties WHERE id = ? AND agent_id = ?");
$stmt->bind_param("ii", $property_id, $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows == 0) {
    echo "Property not found!";
    exit();
}

$property = $res->fetch_assoc();

/** =======================
 *  FETCH ALL OTHER IMAGES
 *  ======================= */
$img_stmt = $conn->prepare("SELECT * FROM property_images WHERE property_id = ?");
$img_stmt->bind_param("i", $property_id);
$img_stmt->execute();
$other_images = $img_stmt->get_result();

/* =============================
   DELETE EXTRA IMAGE
============================= */
if (isset($_GET['delete_img'])) {
    $img_id = intval($_GET['delete_img']);

    $get_i = $conn->prepare("SELECT image_path FROM property_images WHERE id = ? AND property_id = ?");
    $get_i->bind_param("ii", $img_id, $property_id);
    $get_i->execute();
    $row_i = $get_i->get_result()->fetch_assoc();

    if ($row_i) {
        if (file_exists($row_i['image_path'])) unlink($row_i['image_path']);
        $del = $conn->prepare("DELETE FROM property_images WHERE id = ?");
        $del->bind_param("i", $img_id);
        $del->execute();
    }

    header("Location: edit_property.php?id=$property_id");
    exit();
}

/* =============================
   UPDATE PROPERTY
============================= */
$errors = [];
$success = "";

if ($_SERVER['REQUEST_METHOD'] == "POST") {

    $title = $_POST['title'];
    $price = $_POST['price'];
    $location = $_POST['location'];
    $description = $_POST['description'];
    $type = $_POST['type'];
    $aos = $_POST['aos'];

    /** MAIN IMAGE UPLOAD */
    $main_image = $property['img']; // keep old if new is not uploaded

    if (!empty($_FILES['property_image']['name'])) {

        $dir = "uploads/";
        if (!is_dir($dir)) mkdir($dir, 0777, true);

        $fileName = time() . "_" . basename($_FILES['property_image']['name']);
        $targetFile = $dir . $fileName;

        if (move_uploaded_file($_FILES['property_image']['tmp_name'], $targetFile)) {

            // delete old image
            if (!empty($property['img']) && file_exists($property['img'])) unlink($property['img']);

            $main_image = $targetFile;

        } else {
            $errors[] = "Main image upload failed.";
        }
    }

    /** UPDATE MAIN PROPERTY */
    if (empty($errors)) {

        $upd = $conn->prepare("
            UPDATE properties
            SET title=?, price=?, location=?, description=?, type=?, aos=?, img=?
            WHERE id=? AND agent_id=?
        ");

        $upd->bind_param(
            "sisssssii",
            $title,
            $price,
            $location,
            $description,
            $type,
            $aos,
            $main_image,
            $property_id,
            $user_id
        );

        if ($upd->execute()) {
            $success = "Property updated successfully!";
        } else {
            $errors[] = "Error updating property: " . $upd->error;
        }
    }

    /** OTHER IMAGES UPLOAD */
    if (!empty($_FILES['other_images']['name'][0])) {

        $dir = "uploads/";
        if (!is_dir($dir)) mkdir($dir, 0777, true);

        foreach ($_FILES['other_images']['name'] as $i => $imgName) {

            $tmp = $_FILES['other_images']['tmp_name'][$i];
            $fileName = time() . "_" . rand(1000,9999) . "_" . $imgName;
            $path = $dir . $fileName;

            if (move_uploaded_file($tmp, $path)) {

                $ins = $conn->prepare("INSERT INTO property_images(property_id, image_path) VALUES (?, ?)");
                $ins->bind_param("is", $property_id, $path);
                $ins->execute();
                $ins->close();
            }
        }
    }

    header("Location: edit_property.php?id=$property_id&updated=1");
    exit();
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Property</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<div class="container mt-5">

    <h3>Edit Property</h3>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger"><?= implode("<br>", $errors) ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= $success ?></div>
    <?php endif; ?>

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

        <div class="mb-3">
            <label>Title</label>
            <input name="title" class="form-control" value="<?= $property['title'] ?>" required>
        </div>

        <div class="mb-3">
            <label>Price</label>
            <input name="price" type="number" class="form-control" value="<?= $property['price'] ?>" required>
        </div>

        <div class="mb-3">
            <label>Location</label>
            <input name="location" class="form-control" value="<?= $property['location'] ?>" required>
        </div>

        <div class="mb-3">
            <label>Property Type</label>
            <select name="type" class="form-control">
                <option value="rent" <?= $property['type']=="rent"?"selected":"" ?>>Rent</option>
                <option value="sale" <?= $property['type']=="sale"?"selected":"" ?>>Sale</option>
                <option value="shortlet" <?= $property['type']=="shortlet"?"selected":"" ?>>Shortlet</option>
            </select>
        </div>

        <div class="mb-3">
            <label>Status</label>
            <select name="aos" class="form-control">
                <option value="available" <?= $property['aos']=="available"?"selected":"" ?>>Available</option>
                <option value="sold" <?= $property['aos']=="sold"?"selected":"" ?>>Sold</option>
            </select>
        </div>

        <div class="mb-3">
            <label>Description</label>
            <textarea name="description" class="form-control" rows="5"><?= $property['description'] ?></textarea>
        </div>

        <div class="mb-3">
            <label>Main Image</label><br>
            <img src="<?= $property['img'] ?>" width="200" class="mb-2">
            <input type="file" name="property_image" class="form-control mt-2">
        </div>

        <div class="mb-3">
            <label>Other Images</label>
            <div class="row">
                <?php while ($img = $other_images->fetch_assoc()): ?>
                    <div class="col-md-3 mb-2">
                        <img src="<?= $img['image_path'] ?>" class="img-fluid mb-1">
                        <a href="edit_property.php?id=<?= $property_id ?>&delete_img=<?= $img['id'] ?>"
                           class="btn btn-danger btn-sm w-100"
                           onclick="return confirm('Delete this image?')">
                            Delete
                        </a>
                    </div>
                <?php endwhile; ?>
            </div>

            <input type="file" name="other_images[]" class="form-control" multiple>
        </div>

        <button class="btn btn-primary">Update Property</button>
        <a href="my_properties.php" class="btn btn-secondary">Cancel</a>

    </form>

</div>
</body>
</html>
