<?php
session_start(); // Make sure session is started
require 'db.php';

$errors = [];
$success = "";

// Redirect if user not logged in
if(!isset($_SESSION['user_id'])){
    header("Location: login.php");
    exit;
}

if(isset($_POST['add_property'])){
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $price = trim($_POST['price']);
    $location = trim($_POST['location']);
    $category = trim($_POST['category']);
    $type = trim($_POST['type']);
    $accepted_terms = isset($_POST['terms']);

    if(!$accepted_terms){
        $errors[] = "You must accept the Terms & Conditions before posting.";
    }

    // Upload MAIN IMAGE
    $main_img = "";
    if(!empty($_FILES['property_image']['name'])){
        $targetDir = "uploads/";
        if(!is_dir($targetDir)) mkdir($targetDir, 0777, true);

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

        if(move_uploaded_file($_FILES["property_image"]["tmp_name"], $targetFile)){
            $main_img = $targetFile;
        } else {
            $errors[] = "Failed to upload main image.";
        }
    }

    if(empty($title) || empty($description) || empty($price) 
        || empty($location) || empty($category) || empty($type) || empty($main_img)){
        $errors[] = "All fields are required, including the main image.";
    }

    if(empty($errors)){
        $status = "available";

        // Insert property
        $stmt = $conn->prepare("INSERT INTO properties(agent_id,title,description,price,location,category,type,img,status,created_at) VALUES(?,?,?,?,?,?,?,?,?,NOW())");
        $stmt->bind_param(
            "issssssss",
            $_SESSION['user_id'], // insert logged-in user ID as agent_id
            $title,
            $description,
            $price,
            $location,
            $category,
            $type,
            $main_img,
            $status
        );

        if($stmt->execute()){
            $property_id = $stmt->insert_id;

            // Upload multiple other images
            if(!empty($_FILES['other_images']['name'][0])){
                for($i=0; $i<count($_FILES['other_images']['name']); $i++){
                    $fileTmp = $_FILES['other_images']['tmp_name'][$i];
                    $fileName = time() . "_" . rand(1000,9999) . "_" . $_FILES['other_images']['name'][$i];
                    $targetFile = "uploads/" . $fileName;

                    if(move_uploaded_file($fileTmp, $targetFile)){
                        $imgStmt = $conn->prepare("INSERT INTO property_images(property_id, image_path) VALUES(?,?)");
                        $imgStmt->bind_param("is", $property_id, $targetFile);
                        $imgStmt->execute();
                        $imgStmt->close();
                    }
                }
            }

            $success = "Property added successfully!";
        } else {
            $errors[] = "Failed to add property: " . $stmt->error;
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Post Property</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function validateForm() {
    let terms = document.getElementById("terms");
    if(!terms.checked){
        alert("You must accept the Terms & Conditions before posting.");
        return false;
    }
    return true;
}
</script>
</head>
<body>
<div class="container mt-5">
<h3>Post a Property</h3>

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

<?php if($success) echo '<div class="alert alert-success">'.$success.'</div>'; ?>

<form method="POST" enctype="multipart/form-data" onsubmit="return validateForm()">

  <div class="mb-3">
    <label>Title</label>
    <input type="text" name="title" class="form-control" required>
  </div>

  <div class="mb-3">
    <label>Description</label>
    <textarea name="description" class="form-control" rows="3" required></textarea>
  </div>

  <div class="mb-3">
    <label>Price</label>
    <input type="text" name="price" class="form-control" required>
  </div>

  <div class="mb-3">
    <label>Location</label>
    <input type="text" name="location" class="form-control" required>
  </div>

  <div class="mb-3">
    <label>Property Category</label>
    <select name="category" class="form-control" required>
        <option value="">Select Category</option>
        <option value="house">House</option>
        <option value="land">Land</option>
    </select>
  </div>

  <div class="mb-3">
    <label>Property Type</label>
    <select name="type" class="form-control" required>
        <option value="">Select Type</option>
        <option value="rent">For Rent</option>
        <option value="sale">For Sale</option>
        <option value="shortlet">Shortlet</option>
    </select>
  </div>

  <div class="mb-3">
    <label>Upload Property Image (Main)</label>
    <input type="file" name="property_image" class="form-control" accept="image/*" required>
  </div>

  <div class="mb-3">
    <label>Upload Other Property Images</label>
    <input type="file" name="other_images[]" class="form-control" accept="image/*" multiple>
  </div>

  <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" name="terms" id="terms">
      <label class="form-check-label" for="terms">
          I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">Terms & Conditions</a>
      </label>
  </div>

<button type="submit" name="add_property"style="background-color:#000" class="btn btn-success w-100">Add Property</button>

</form>

<a href="dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>

</div>

<div class="modal fade" id="termsModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-scrollable">
      <div class="modal-content">
          <div class="modal-header">
              <h5 class="modal-title">Terms & Conditions</h5>
              <button class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
              <p><strong>1. Accuracy of Information:</strong> All property details must be truthful.</p>
              <p><strong>2. Ownership:</strong> You are the rightful owner or authorized agent.</p>
              <p><strong>3. No Illegal Content:</strong> No misleading info or fraudulent listings.</p>
              <p><strong>4. Image Usage:</strong> Images must be yours or authorized.</p>
              <p><strong>5. Verification:</strong> We may remove suspicious listings.</p>
              <p><strong>6. Liability:</strong> We are not responsible for disputes or agreements.</p>
              <p><strong>7. Removal Rights:</strong> Listings violating policies may be removed.</p>
          </div>
          <div class="modal-footer">
              <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          </div>
      </div>
  </div>
</div>
</body>
</html>
