<?php 
include './functions.php';
include '../dbconfig.php';

$uploads_dir = '../assets/images/properties';
$imageName = [];
$id = $_POST['id'];
$imgArray = [];
$image ='';
if($_FILES['images']['name'][0] !==''){
foreach($_FILES['images']['name'] as $key => $file){
    $tmp_name = $_FILES["images"]["tmp_name"][$key];
    $file = str_replace(' ','_',$file);
   move_uploaded_file($tmp_name, "$uploads_dir/$file");
    array_push($imageName,$file);
}
$propertyDetails = getPropertyById($id);
if($propertyDetails['image']){
    $imgArray = explode(",",$propertyDetails['image']);
}
$imageName = array_merge($imgArray,$imageName);
$image = implode(",",$imageName);
}
try {
    $property_name = $_POST['property_name'];
    $description = $_POST['description'];
    $property_type = $_POST['property_type'];
    $lease_outright = $_POST['lease_outright'];
    $bhk = $_POST['bhk'];
    $shop_godown_office = $_POST['shop_godown_office'];
    $price = $_POST['price'];
    
    
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    if(isset($_POST['sq_ft'])){
        
    
        $sq_ft =$_POST['sq_ft'];
        if($image !=''){
            $sql = "UPDATE properties SET property_type='$property_type',`name`='$property_name',`lease_outright`=
            '$lease_outright',`shop_godown_office`='$shop_godown_office',`bhk`='$bhk',`sq_ft`='$sq_ft',`price`='$price',
            `image`='$image',`description`='$description' WHERE id='$id'";
        }else {
            $sql = "UPDATE properties SET property_type='$property_type',`name`='$property_name',`lease_outright`=
            '$lease_outright',`shop_godown_office`='$shop_godown_office',`bhk`='$bhk',`sq_ft`='$sq_ft',`price`='$price',
                `description`='$description' WHERE id='$id'";
        }
    }else{
        if($image !=''){
            $sql = "UPDATE properties SET property_type='$property_type',`name`='$property_name',`lease_outright`=
            '$lease_outright',`shop_godown_office`='$shop_godown_office',`bhk`='$bhk',`price`='$price',
            `image`='$image',`description`='$description' WHERE id='$id'";
        }else {
            $sql = "UPDATE properties SET property_type='$property_type',`name`='$property_name',
            `lease_outright`='$lease_outright',`shop_godown_office`='$shop_godown_office',`bhk`='$bhk',`price`='$price',
                `description`='$description' WHERE id='$id'";
        }
    }


    // use exec() because no results are returned
    $resp = $conn->exec($sql);
    if($resp){
        $_SESSION['success'] = " Property Updated Succesfully";
       header('location:editproperty.php?id='.$id);
    } else {
        echo "some error occured";
    }
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
?>