<?php
require_once 'connection.php';

$response = array(
    'success' => true,
    'message' => ''
);
$action = isset($_POST['action']) ? $_POST['action'] : '';
if (empty($action)) {
    $response['success'] = false;
    $response['message'] = 'empty action';
    echo json_encode($response);
    die();
}

if($action == 'client-brief') {
    $drg = trim(mysqli_real_escape_string($con, $_POST["drg"]));

    if (empty($drg)) {
        echo \json_encode($response);
        die();
    }

    $fieldName = trim(mysqli_real_escape_string($con, $_POST["field_name"]));
    $fieldValue = trim(mysqli_real_escape_string($con, $_POST["field_value"]));

	error_log(date('Y-m-d H:i:s') . " update drg={$drg} field={$fieldName}" . PHP_EOL, 3, "error.log");

    if ($fieldName == "postal_address" ) {
        $updateval = trim(preg_replace('/\s\s+/', ' ', str_replace('\n', '', $fieldValue) ));

        // Create Seperated Address
        $seperate_address = explode(",", $updateval);
        $postal_address = $_POST["postal_address"];
    	$postal_address_street = substr($seperate_address[0], 0);
        $postal_address_town = substr($seperate_address[1], 1);
        $postal_address_state = substr($seperate_address[2], 1);
        $postal_address_postcode = substr($seperate_address[3], 1);
        $address_result = mysqli_query($con, "INSERT INTO addresses(`drg`, `postal_address`, `postal_address_street`, `postal_address_town`, `postal_address_state`, `postal_address_postcode`) VALUES ('{$drg}', '{$postal_address}', '{$postal_address_street}', '{$postal_address_town}', '{$postal_address_state}', '{$postal_address_postcode}')
    				ON DUPLICATE KEY UPDATE `postal_address` = '{$postal_address}', `postal_address_street` = '{$postal_address_street}', `postal_address_town` = '{$postal_address_town}', `postal_address_state` = '{$postal_address_state}', `postal_address_postcode` = '{$postal_address_postcode}' ");

        //error_log(":" . $postal_address . "," . $postal_address_town . "," . $postal_address_state . "," . $postal_address_postcode . ",", 3, "error.log");
    }
    if ($fieldName == "site_address" ) {
        $updateval = trim(preg_replace('/\s\s+/', ' ', str_replace('\n', '', $fieldValue) ));

        // Create Seperated Address
        $seperate_address = explode(",", $updateval);
        $site_address = $_POST["site_address"];
    	$site_address_street = substr($seperate_address[0], 0);
        $site_address_town = substr($seperate_address[1], 1);
        $site_address_state = substr($seperate_address[2], 1);
        $site_address_postcode = substr($seperate_address[3], 1);
        $address_result = mysqli_query($con, "INSERT INTO addresses(`drg`, `site_address`, `site_address_street`, `site_address_town`, `site_address_state`, `site_address_postcode`) VALUES ('{$drg}', '{$site_address}', '{$site_address_street}', '{$site_address_town}', '{$site_address_state}', '{$site_address_postcode}')
    				ON DUPLICATE KEY UPDATE `site_address` = '{$site_address}', `site_address_street` = '{$site_address_street}', `site_address_town` = '{$site_address_town}', `site_address_state` = '{$site_address_state}', `site_address_postcode` = '{$site_address_postcode}' ");

        //error_log(":" . $site_address . "," . $site_address_town . "," . $site_address_state . "," . $site_address_postcode . ",", 3, "error.log");
    }

    $details = [
        'firstname', 'lastname', 'joint_name', 'client_mobile', 'client_email', 'property_id', 'title_id', 'registered_owner',
    	'design_style', 'build_type', 'council', 'scope', 'planning_zones', 'planning_scheme', 'planning_codes', 'plan_data', 'property_data', 'total_area', 'locality',
    	'budget_low', 'budget_high', 'finance_status',
        'copy_title', 'original_plans', 'concepts_styles', 'loa_signed', 'da_application', 'ba_application',
        '3D_concepts', 'draft_floorPlan', 'fire_report', 'energy_report', 'tender_set', 'quantity_survey', 'vr_concepts', 'render_set', '3d_model', 'details',
    	'signature',
    	'dealId', 'crm_id'
    ];

    $addressesColumns = [
        'postal_address', 'site_address', 'client_mobile', 'client_email', 'site_lat', 'site_lng'
    ];

    $allAllowedColumns = array_merge($details, $addressesColumns);

    if (empty($fieldName)) {
        $response['success'] = false;
        $response['message'] = 'No Field name in database table: ' . $fieldName;
    } elseif (!in_array($fieldName, $allAllowedColumns)) {
        $response['success'] = false;
        $response['message'] = 'Field: ' . $fieldName . ' is not allowed to save';
    } else {
        $tableName = '';

        if (in_array($fieldName, $details)) {
            $tableName = 'details';
        } elseif (in_array($fieldName, $addressesColumns)) {
            $tableName = 'addresses';
        }

        if (!empty($tableName)) {
            $result = mysqli_query($con," SELECT COUNT(1) as cnt FROM {$tableName} WHERE drg = {$drg}");

            $countRow = mysqli_fetch_assoc($result);

            if (empty($countRow['cnt'])) {
                $query = "INSERT INTO {$tableName} SET {$fieldName} = '{$fieldValue}', drg = {$drg}";
            } else {
                $query = "UPDATE {$tableName} SET {$fieldName} = '{$fieldValue}' WHERE drg = {$drg}";
            }

            // $response['query'] = $query;
            $result = mysqli_query($con, $query);

            if (!$result) {
                $response['success'] = false;
                $response['message'] = mysqli_error($con);
            }
        } else {
            $response['success'] = false;
            $response['message'] = 'needed table not found';
        }
    }
} else {
    $response['success'] = false;
    $response['message'] = 'Unknown action';
}

echo json_encode($response);