<?php
// process_admin_property.php
session_start();
require_once "config.php"; // Your DB connection

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

    // Get form inputs
    $property_type = $_POST['property_type'] ?? '';
    $description = $_POST['description'] ?? '';
    $price = $_POST['price'] ?? 0;
    $location = $_POST['location'] ?? '';

    // Validate required fields
    if(empty($property_type) || empty($description) || empty($price) || empty($location)){
        die('Please fill all required fields.');
    }

    // Directory to store uploads
    $uploadDir = "uploads/admin_properties/";
    if(!is_dir($uploadDir)){
        mkdir($uploadDir, 0755, true);
    }

    // Handle main property image
    if(isset($_FILES['property_image']) && $_FILES['property_image']['error'] === 0){
        $mainImageName = time() . "_" . basename($_FILES['property_image']['name']);
        $mainImagePath = $uploadDir . $mainImageName;
        move_uploaded_file($_FILES['property_image']['tmp_name'], $mainImagePath);
    } else {
        die('Main property image is required.');
    }

    // Handle additional images (up to 5)
    $additionalImages = [];
    if(isset($_FILES['images'])){
        $files = $_FILES['images'];
        $count = count($files['name']);
        if($count > 5) $count = 5; // Limit to 5 images
        for($i=0; $i<$count; $i++){
            if($files['error'][$i] === 0){
                $imgName = time() . "_add_" . $i . "_" . basename($files['name'][$i]);
                $imgPath = $uploadDir . $imgName;
                move_uploaded_file($files['tmp_name'][$i], $imgPath);
                $additionalImages[] = $imgPath;
            }
        }
    }
    $imagesCSV = implode(",", $additionalImages); // Store as comma-separated string

    // Handle video (optional)
    $videoPath = null;
    if(isset($_FILES['video']) && $_FILES['video']['error'] === 0){
        $videoName = time() . "_" . basename($_FILES['video']['name']);
        $videoPath = $uploadDir . $videoName;
        move_uploaded_file($_FILES['video']['tmp_name'], $videoPath);
    }

    // Insert into database
    $stmt = $conn->prepare("INSERT INTO admin_properties (property_type, description, property_image, images, video, price, location) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssis", $property_type, $description, $mainImagePath, $imagesCSV, $videoPath, $price, $location);

    if($stmt->execute()){
        // Redirect after successful insertion
        header("Location: admin_dash.php?success=1");
        exit;
    } else {
        die("Database error: " . $stmt->error);
    }

} else {
    die('Invalid request.');
}
