<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include '../../auth/auth_functions.php';
require_once '../../../db.php';
include '../../helper_functions/data_request.php';

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

    if (isset($_POST['get_streets_request']) && isset($_POST['property_id'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'read')) {
            echo json_encode(['error' => 'Access Denied']);
            exit();
        }
    
        $propertyId = intval($_POST['property_id']);
    
        $streets = fetchData('property_groups', [
            'property_id' => $propertyId
        ]);
    
        echo json_encode([
            'success' => true,
            'data' => $streets
        ]);
        exit();
    }    

    if (isset($_POST['streetname'])) {

        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            echo json_encode(['error' => 'Access Denied']);
            exit();
        }
    
        $street = ucwords(strtolower(trim($_POST['streetname'])));
        $prop = $_SESSION['property'];
        $userid = $_SESSION['userid'];

        if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
            $creator_type = 'users';
        }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
            $creator_type = 'dealer_admins';
        }else {
            $creator_type = 'property_users';
        }
    
        $existing = fetchDataSingle('property_groups', [
            'property_id' => $prop,
            'name' => $street
        ]);
    
        if ($existing) {
            $_SESSION['alert'] = [
                "message" => "Street already exists!",
                "type" => "danger"
            ];
        } else {
            $insertedStreet = insertData('property_groups', [
                'name' => $street,
                'property_id' => $prop,
                'created_by' => $userid,
                'creator_type' => $creator_type
            ]);
            
            $insertedId = $insertedStreet['id'];

            createAuditLog(
                $_SESSION["userid"], 
                "Created Street " . $street, 
                "property_groups", 
                $insertedId, 
                $_SESSION["email"]??null, 
                $_SESSION['property'], 
                null, 
                $street, 
                "Created Street", 
                "high", 
                "streets"
            );
    
            $_SESSION['alert'] = [
                "message" => "Street has been added successfully!",
                "type" => "success"
            ];
        }
        
        $returnUrl = '../../../dashboard.php?tab=property_builder';
        header("Location: $returnUrl");
        exit();
    }    

    if (isset($_POST['delete_street_request'], $_POST['id'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            echo json_encode(['error' => 'Access Denied']);
            exit();
        }
    
        $streetId = intval($_POST['id']);
        $streetname = $_POST['name'];
    
        try {
            $success = deleteData('property_groups', 'id', $streetId);
            createAuditLog(
                $_SESSION["userid"], 
                "Deleted Street " . $streetname, 
                "property_groups", 
                $streetId, 
                $_SESSION["email"]??null, 
                $_SESSION['property'], 
                $streetname, 
                null, 
                "Deleted Street", 
                "high", 
                "streets"
            );

            echo json_encode([
                'success' => $success,
                'message' => $success ? 'Street deleted' : 'Street not found or already deleted'
            ]);
        } catch (Exception $e) {
            error_log("Error occurred: " . $e->getMessage());
            echo json_encode([
                'success' => false,
                'message' => 'An unexpected error occurred. Please try again later.'
            ]);
        }
        exit();
    }    

    if (isset($_POST['edit_street_request'], $_POST['id'], $_POST['name'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            echo json_encode(['error' => 'Access Denied']);
            exit();
        }
    
        $id = intval($_POST['id']);
        $name = ucwords(strtolower(trim($_POST['name'])));
        $propertyId = $_SESSION['property'];
        $origname = $_POST['origname'];
    
        // Check for duplicate street name
        $checkQuery = "SELECT COUNT(*) FROM property_groups WHERE name = :name AND id != :id AND property_id = :property_id";
        $params = [
            'name' => $name,
            'id' => $id,
            'property_id' => $propertyId
        ];
        $count = fetchSingleDataWithJoins($checkQuery, $params)['COUNT(*)'] ?? 0;
    
        if ($count > 0) {
            echo json_encode(['success' => false, 'message' => 'Street already exists']);
            exit();
        }
    
        // Update the street
        $dataToUpdate = ['name' => $name];
        $whereClause = 'id = :id';
        $whereParams = ['id' => $id];
    
        if (updateTable('property_groups', $dataToUpdate, $whereClause, $whereParams)) {
            createAuditLog(
                $_SESSION["userid"], 
                "Street Edited " . $origname, 
                "property_groups", 
                $id, 
                $_SESSION["email"]??null, 
                $_SESSION['property'], 
                $origname, 
                $name, 
                "Edited Street", 
                "high", 
                "streets"
            );
            echo json_encode(['success' => true, 'message' => 'Street updated']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit();
    } 

}