<?php
session_start();

if (isset($_SESSION['userid'])) {
    require_once('../../db.php');
    require_once('../../shared/functionsinc.php');

    if (isset($_POST["submitnew"])) {
        $dealer_Id = $_SESSION["userid"];
        $propType = $_POST["proptype"];
        $propName = $_POST["propname"];
        $propAddress = $_POST["propaddress"];
        $propCity = $_POST["propcity"];
        $propState = $_POST["propstate"];
        $propZip = $_POST["propzip"];
        $propContact = $_POST["propCon"];
        $propContactPhone = preg_replace('/\D/', '', $_POST["propConPh"]);
        $proOrgId = $_POST["organization_id"];
        $propDemo = '';// $_POST["propdemo"];
        $propNotes = $_POST["propnotes"];
        $propreferral = $_POST["propreferral"];
        $propLink = $_POST["propLink"]??null;
    
        $imagePath = null;

        $newPropertyState = newProperty($pdo, $propName, $propAddress, $propCity, $propState, $propZip, $propContact, $propContactPhone, $proOrgId, $propType, $imagePath, $propDemo, $propNotes, $propreferral,$propLink);
    
        if (!is_numeric($newPropertyState)) {

            $alertType = "danger";
            switch ($newPropertyState) {
                case 'No Available Slots':
                    $_SESSION['alert'] = [
                        "message" => "No Available Slots",
                        "type" => "warning"
                    ];
                    break;
                case 'Not a Dealer':
                    $_SESSION['alert'] = [
                        "message" => "You must be a Dealer to Create a Property. Please check your Login and try again!",
                        "type" => "danger"
                    ];
                    break;
                default:
                    $_SESSION['alert'] = [
                        "message" => "Failed to create property.",
                        "type" => "danger"
                    ];
                    break;
            }
    
            header("Location: ../../dashboard.php?tab=my_properties");
            exit();
        }
    
        $propertyId = $newPropertyState;

        if (isset($_FILES['propImage']) && $_FILES['propImage']['error'] == 0) {
            $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
            $fileMimeType = $_FILES['propImage']['type'];
            if (!in_array($fileMimeType, $allowedMimeTypes)) {
                die('Invalid image type. Only JPG, PNG, and GIF are allowed.');
            }
    
            $maxFileSize = 4 * 1024 * 1024; // 4MB limit
            if ($_FILES['propImage']['size'] > $maxFileSize) {
                return ["success" => false, "error" => "File size exceeds the 4MB limit."];
            }
    
            $targetDir = '../../../../data/properties/';
            $propertyFolder = $targetDir . 'property_' . $propertyId;
    
            if (!file_exists($propertyFolder)) {
                if (!mkdir($propertyFolder, 0777, true)) {
                    die('Failed to create property folder.');
                }
            }
    
            $imageFileName = 'image_' . time() . '.' . pathinfo($_FILES['propImage']['name'], PATHINFO_EXTENSION);
            $targetFilePath = $propertyFolder . '/' . $imageFileName;
    
            if (move_uploaded_file($_FILES['propImage']['tmp_name'], $targetFilePath)) {
                $imagePath = 'property_' . $propertyId . '/' . $imageFileName;
    
                $updateImageState = $pdo->prepare("UPDATE properties SET image_path = ? WHERE id = ?");
                $updateImageState->execute([$imagePath, $propertyId]);
            } else {
                die('Failed to upload the image.');
            }
        }
    
        $_SESSION['alert'] = [
            "message" => "New Property Successfully Created!",
            "type" => "success"
        ];
        header("Location: ../../dashboard.php?tab=my_properties");
        exit();
    }
    
    if (isset($_POST["getdata"])) {
        $userId = $_SESSION['userid'];
        $userLayer = $_SESSION['layer'];
    
        $data = [];
    
        // Handle properties based on user type
        if ($userLayer === 'sub_dealer' || $userLayer === 'organization admin') {
            // Fetch assigned properties
            $accessEntries = fetchdata('dealer_admins_access', ['dealer_admin_id' => $userId, 'access_type' => 'property']);
            $propertyIds = array_column($accessEntries, 'access_id');
    
            if (!empty($propertyIds)) {
                $propertyIdsList = implode(',', array_map('intval', $propertyIds));
                $query = "SELECT * FROM properties WHERE id IN ($propertyIdsList)";
                $stmt = $pdo->prepare($query);
                $stmt->execute();
                $data['properties'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            } else {
                $data['properties'] = [];
            }
        } else {
            $data['properties'] = getProperty($userId, $userLayer);
        }
    
        // Handle organizations based on user type
        if ($userLayer === 'sub_dealer' || $userLayer === 'organization admin') {
            // Fetch assigned organizations
            $orgAccessEntries = fetchdata('dealer_admins_access', ['dealer_admin_id' => $userId, 'access_type' => 'organization']);
            $orgIds = array_column($orgAccessEntries, 'access_id');
    
            // Also fetch organizations linked to properties
            $propertyOrgIds = array_column($data['properties'], 'organization_id');
            $combinedOrgIds = array_unique(array_merge($orgIds, $propertyOrgIds));
    
            if (!empty($combinedOrgIds)) {
                $orgIdsList = implode(',', array_map('intval', $combinedOrgIds));
                $query = "SELECT * FROM organizations WHERE id IN ($orgIdsList)";
                $stmt = $pdo->prepare($query);
                $stmt->execute();
                $organizations = $stmt->fetchAll(PDO::FETCH_ASSOC);
            } else {
                $organizations = [];
            }
        } else {
            $organizations = getOrg($pdo, $userId, $userLayer);
        }
    
        // Retrieve all dealers once to avoid redundant database calls
        $dealers = getDealers($pdo, $userId, $userLayer);
        $dealerMap = [];
        foreach ($dealers as $dealer) {
            $dealerMap[$dealer['id']] = $dealer;
        }
    
        // Attach dealer info to organizations
        foreach ($organizations as &$org) {
            $dealerId = $org['dealer_id'];
            if (isset($dealerMap[$dealerId])) {
                $org['company_name'] = $dealerMap[$dealerId]['company_name'];
                $org['admin'] = ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin');
            } else {
                $org['company_name'] = 'N/A';
                $org['dealer_name'] = 'Unknown Dealer';
            }
        }
        unset($org);
    
        $data['organizations'] = $organizations;
    
        echo json_encode($data);
    }    

    if (isset($_POST['getupdateimage'])) {
        $currentProp = $_POST['currentProp'];

        $newImage = getPropertyImage($currentProp);
        $propname = getPropName($currentProp);

        echo json_encode([$newImage, $propname]);
        exit();
    }

    if (isset($_POST["editprop"])) {
        $propid = $_POST["propid"];
        $allProps = getProperty($_SESSION['userid'], $_SESSION['layer']);
        $propData = array_filter($allProps, function($prop) use ($propid) {
            return $prop['id'] == $propid;
        });
    
        $propData = array_values($propData);
        $propData = count($propData) > 0 ? $propData[0] : null;
    
        if ($propData) {
            echo json_encode($propData);
        } else {
            echo json_encode(['error' => 'Organization not found']);
        }
        exit();
    }

    if (isset($_POST["updateprop"])) {
        $propId = preg_replace('/\D/', '', $_POST['idstore']);
        $propType = $_POST['uproptype'];
        $propName = $_POST['upropname'];
        $propAddress = $_POST['upropaddress'];
        $propCity = $_POST['upropcity'];
        $propState = $_POST['upropstate'];
        $propZip = $_POST['upropzip'];
        $propContact = $_POST['upropCon'];
        $propContactPhone = preg_replace('/\D/', '', $_POST['upropConPh']);
        // $proporg = $_POST['uorganization_id'];
        $propNotes = $_POST['upropnotes'];
        $propLink = $_POST['upropLink'] ?? null;
    
        $propImage = null;
    
        $targetDir = '../../../../data/properties/';
        $propertyFolder = $targetDir . 'property_' . $propId;
    
        if (isset($_POST['deleteImage']) && $_POST['deleteImage'] === 'true') {
            $existingImage = getPropertyImage($propId);
            if ($existingImage && $existingImage !== 'real-estate-property.jpg') {
                $existingImagePath = $targetDir . $existingImage;
                if (file_exists($existingImagePath)) {
                    unlink($existingImagePath);
                }
            }
            $propImage = '';
        }

        if (isset($_FILES['upropImage']) && $_FILES['upropImage']['error'] == 0) {
            $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $fileMimeType = finfo_file($finfo, $_FILES['upropImage']['tmp_name']);
            finfo_close($finfo);
            if (!in_array($fileMimeType, $allowedMimeTypes)) {
                die('Invalid image type. Only JPG, PNG, and GIF are allowed.');
            }
    
            $maxFileSize = 4 * 1024 * 1024; // 4MB limit
            if ($_FILES['upropImage']['size'] > $maxFileSize) {
                return ["success" => false, "error" => "File size exceeds the 4MB limit."];
            }
    
            if (!file_exists($propertyFolder)) {
                if (!mkdir($propertyFolder, 0755, true)) {
                    error_log("Failed to create property folder: $propertyFolder");
                    $_SESSION['alert'] = [
                        "message" => "Server error while preparing property image folder.",
                        "type" => "danger"
                    ];
                    header("Location: ../../dashboard.php?tab=my_properties");
                    exit();
                }
            }
    
            $imageFileName = 'image_' . time() . '.' . pathinfo($_FILES['upropImage']['name'], PATHINFO_EXTENSION);
            $targetFilePath = $propertyFolder . '/' . $imageFileName;
    
            $existingImage = getPropertyImage($propId);
            if ($existingImage && $existingImage !== 'real-estate-property.jpg') {
                $existingImagePath = $targetDir . $existingImage;
                if (file_exists($existingImagePath)) {
                    unlink($existingImagePath);
                }
            }
    
            if (move_uploaded_file($_FILES['upropImage']['tmp_name'], $targetFilePath)) {
                $propImage = 'property_' . $propId . '/' . $imageFileName;
            } else {
                die('Failed to upload the image.');
            }
        }

        if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
            $proporg = $_POST['uorganization_id'];
            $updateStatus = updateProperty($pdo, $propId, $propImage, $propName, $propAddress, $propCity, $propState, $propZip, $propContact, $propContactPhone, $proporg, $propNotes, $propLink);
        }else {
            $proporg = 'View Only';
            $updateStatus = updateProperty($pdo, $propId, $propImage, $propName, $propAddress, $propCity, $propState, $propZip, $propContact, $propContactPhone, $proporg, $propNotes, $propLink);
        }

    
        $message = "";
        $alertType = "";
        switch ($updateStatus) {
            case false:
                $_SESSION['alert'] = [
                    "message" => "Failed to update Property!",
                    "type" => "danger"
                ];
                break;
            case true:
                $_SESSION['alert'] = [
                    "message" => "Property updated successfully!",
                    "type" => "success"
                ];
                break;
            default:
                break;
        }
        header("Location: ../../dashboard.php?tab=my_properties");
        exit();
    }    

    if (isset($_POST['deleteImage']) && $_POST['deleteImage'] === 'yes') {
        $propId = $_POST['propid'];

        $existingImage = getPropertyImage($propId);
        if ($existingImage) {
            $targetDir = '../../../../data/properties/';
            $existingImagePath = $targetDir . $existingImage;
        
            if (file_exists($existingImagePath)) {
                unlink($existingImagePath);
            }
        
            try {

                $updateSuccess = updateTable(
                    'properties',
                    ['image_path' => null],
                    'id = :id',
                    ['id' => $propId]
                );
        
                if ($updateSuccess) {
                    echo json_encode(["status" => "success", "message" => "Image deleted successfully."]);
                } else {
                    echo json_encode(["status" => "error", "message" => "Failed to update the database."]);
                }
            } catch (Exception $e) {
                error_log("Unhandled exception: " . $e->getMessage());
                echo json_encode([
                    "status" => "error",
                    "message" => "An unexpected error occurred. Please try again later."
                ]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "No image found to delete."]);
        }
        
        exit();
    }

    if(isset($_POST['add_voip_setting']) && $_POST['add_voip_setting'] == "yes"){
        $prop_id = $_POST['property_id'];
        $prop_data = fetchDataSingle('properties', ['id' => $prop_id]);
        $organization_data = fetchDataSingle('organizations', ['id' => $prop_data['organization_id']]);

        if(isset($organization_data['dealer_id']) && !empty($organization_data['dealer_id'])){
            $add_voip = create_sub_project($prop_id, $prop_data['name'], $organization_data['dealer_id'], "new");
            if($add_voip != "no"){
                createAuditLog($_SESSION["userid"], "Added Property VOIP Setting", "signalwire_settings", $add_voip, $_SESSION["email"]??null, $prop_id,null, $add_voip, "Added property VOIP setting", "medium", "Property Voip Settings");
            }
            else{
                $add_voip = 3;
            }
            echo json_encode($add_voip);
        }
        else{
            echo json_encode(2);   
        }
    }
    
} else {
    header("location: ../../login.php");
    exit();
}
