<?php
session_start();
require_once "config.php"; // db connection

header("Content-Type: application/json");

// Ensure agent is logged in
if (!isset($_SESSION["user_id"])) {
    echo json_encode(["success" => false, "message" => "You must be logged in to add a property."]);
    exit;
}

$user_id = $_SESSION["user_id"];
$title = trim($_POST["title"] ?? "");
$type = $_POST["type"] ?? "";
$category = $_POST["category"] ?? "";
$description = trim($_POST["description"] ?? "");
$location = trim($_POST["location"] ?? "");

// Price fields
$price = $_POST["price"] ?? null;
$monthly_fee = $_POST["monthly_fee"] ?? null;
$yearly_fee = $_POST["yearly_fee"] ?? null;
$agency_fee = $_POST["agency_fee"] ?? null;
$other_fees = $_POST["other_fees"] ?? null;
$total_package = $_POST["total_package"] ?? null;

// Validation
if ($title === "" || $type === "" || $category === "" || $location === "") {
    echo json_encode(["success" => false, "message" => "Please fill in all required fields."]);
    exit;
}

$serviceCharge = 200.00; // NGN
$currency = "NGN";
$admin_id = 1; // Admin user ID

try {
    // Start DB transaction
    $conn->begin_transaction();

    // Get agent balance
    $stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($balance);
    if (!$stmt->fetch()) {
        throw new Exception("User not found.");
    }
    $stmt->close();

    // Check balance
    if ($balance < $serviceCharge) {
        throw new Exception("Insufficient balance. A service charge of ₦200 is required to upload a property.");
    }

    // Deduct from agent
    $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $stmt->bind_param("di", $serviceCharge, $user_id);
    $stmt->execute();
    $stmt->close();

    // Credit admin
    $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
    $stmt->bind_param("di", $serviceCharge, $admin_id);
    $stmt->execute();
    $stmt->close();

    // Log transaction (agent debit)
    $reference = uniqid("txn_");
    $status = "completed";
    $desc = "Property upload";
    $stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, reference, status) 
                            VALUES (?, 'debit', ?, ?, ?, ?, ?)");
    $stmt->bind_param("idssss", $user_id, $serviceCharge, $currency, $desc, $reference, $status);
    $stmt->execute();
    $stmt->close();

    // Log transaction (admin credit)
    $reference_admin = uniqid("txn_");
    $stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, reference, status) 
                            VALUES (?, 'credit', ?, ?, ?, ?, ?)");
    $stmt->bind_param("idssss", $admin_id, $serviceCharge, $currency, $desc, $reference_admin, $status);
    $stmt->execute();
    $stmt->close();

    // Insert into properties
    $stmt = $conn->prepare("INSERT INTO properties 
        (user_id, title, description, type, category, price, monthly_fee, yearly_fee, agency_fee, other_fees, total_package, location) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param(
        "isssssddddds",
        $user_id,
        $title,
        $description,
        $type,
        $category,
        $price,
        $monthly_fee,
        $yearly_fee,
        $agency_fee,
        $other_fees,
        $total_package,
        $location
    );
    $stmt->execute();
    $property_id = $stmt->insert_id;
    $stmt->close();

    // Handle Images (max 5)
    if (!empty($_FILES["images"]["name"][0])) {
        $uploadDir = "uploads/properties/images/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        foreach ($_FILES["images"]["tmp_name"] as $key => $tmpName) {
            if ($_FILES["images"]["error"][$key] === UPLOAD_ERR_OK) {
                $ext = pathinfo($_FILES["images"]["name"][$key], PATHINFO_EXTENSION);
                $fileName = uniqid("img_") . "." . strtolower($ext);
                $filePath = $uploadDir . $fileName;

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

    // Handle Video (optional)
    if (!empty($_FILES["video"]["name"])) {
        $uploadDir = "uploads/properties/videos/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        if ($_FILES["video"]["error"] === UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES["video"]["name"], PATHINFO_EXTENSION);
            $fileName = uniqid("vid_") . "." . strtolower($ext);
            $filePath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES["video"]["tmp_name"], $filePath)) {
                $stmt = $conn->prepare("INSERT INTO property_videos (property_id, video_path) VALUES (?, ?)");
                $stmt->bind_param("is", $property_id, $filePath);
                $stmt->execute();
                $stmt->close();
            }
        }
    }

    // Commit transaction
    $conn->commit();

    echo json_encode(["success" => true, "message" => "Property added successfully! Service charge ₦200 deducted."]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
}
?>
