<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);  
//------------------------------------------
// dealers
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);

//CONTENT FROM API (POST)
$post_content = json_decode($input,true);


//CHECK IF REQUEST IS FROM DEALERFINDER 
if(isset($post_content['bounds'])){
    //++++++++++++++++++++++
    //Process DEALERFINDER PROCES
    //++++++++++++++++++++++

    //------------------------------------------
    //NEW ARRAY
    //------------------------------------------
    $whereclause = '';
    $criterias = [];   
    $clause = '';

    //------------------------------------------
    //GET THE POST CONTENT
    //------------------------------------------
    if(isset($post_content) && $post_content !=''){

        //ADD STATUS TO POST_CONTENT, active only
        $post_content['status'] = 1;

        //------------------------------------------
        //RUN THROUGH POST CONTENT
        //------------------------------------------
        foreach($post_content as $criteria => $value){

            //HANDLE MAP BOUNDS
            if ($criteria == 'bounds'){
                //GET THE INPUT
                $northEastLat = (float)$value['_northEast']['lat'];
                $northEastLng = (float)$value['_northEast']['lng'];
                $southWestLat = (float)$value['_southWest']['lat'];
                $southWestLng = (float)$value['_southWest']['lng'];
    
                // Handle the case where the map crosses the 180/-180 longitude line
                if ($southWestLng > $northEastLng) {
                    $clause .= " AND (d.lng >= :lng_sw OR d.lng <= :lng_ne)";
                    $criterias['lng_sw'] = $southWestLng;
                    $criterias['lng_ne'] = $northEastLng;

                } else {
                    $clause .= " AND d.lng >= :lng_sw AND d.lng <= :lng_ne";
                    $criterias['lng_sw'] = $southWestLng;
                    $criterias['lng_ne'] = $northEastLng;
                }
                
                // Latitude is simpler as it doesn't wrap around
                $clause .= " AND d.lat >= :lat_sw AND d.lat <= :lat_ne";
                $criterias['lat_sw'] = $southWestLat;
                $criterias['lat_ne'] = $northEastLat;            
            }
            if ($criteria == 'status'){
                $clause .= " AND d.status = :status ";
                $criterias['status'] = $value;            
            }
            
        }   

        //UPDATE THE WHERECLAUSE DEPENDING ON ORIGINAL WHERECLAUSE
        if ($whereclause == '' && $clause !=''){
            $whereclause = 'WHERE '.substr($clause, 4);
        } else {
            $whereclause .= $clause;
        }

    }

    //------------------------------------------
    // SQL
    //------------------------------------------
    $sql = 'SELECT d.*, m.full_path FROM dealers d LEFT JOIN media m ON d.dealer_media = m.rowID '.$whereclause;

    //PREPARE QUERY
    $stmt = $pdo->prepare($sql);

    //------------------------------------------
    // BIND CRITERIAS TO SQL
    //------------------------------------------
    if (!empty($criterias)){
        foreach ($criterias as $key => $value){
            $key_condition = ':'.$key;
            if (str_contains($whereclause, $key_condition)){
                if ($key == 'search'){
                    $search_value = '%'.$value.'%';
                    $stmt->bindValue($key, $search_value, PDO::PARAM_STR);
                }
                elseif ($key == 'p'){
                    //Do nothing (bug)
                }
                else {
                    $stmt->bindValue($key, $value, PDO::PARAM_STR);
                }
            }
        }
    }

    //------------------------------------------
    // EXECUTE QUERY
    //------------------------------------------
    $stmt->execute();
    
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    //------------------------------------------
    // Check if there are 0 rows returned
    //------------------------------------------
    if (empty($messages)) {
        // Calculate the center
        $centerLat = ($southWestLat + $northEastLat) / 2;
        $centerLng = ($southWestLng + $northEastLng) / 2;

        // No rows were returned, execute alternative query
        $sql = 'SELECT
                    d.*,
                    (6371 * acos(
                        cos(radians('.$centerLat.')) * cos(radians(d.lat)) * cos(radians(d.lng) - radians('.$centerLng.')) +
                        sin(radians('.$centerLat.')) * sin(radians(d.lat))
                    )) AS distance_km,
                    m.full_path
                FROM dealers d LEFT JOIN media m ON d.dealer_media = m.rowID
                WHERE d.status = 1
                ORDER BY distance_km
                LIMIT 10';

        $altStmt = $pdo->prepare($sql);
        $altStmt->execute();
        $messages = $altStmt->fetchAll(PDO::FETCH_ASSOC);
    } 

    //------------------------------------------
    //CHANGE ROWID INTO UUID
    //------------------------------------------
    function updateRowID($row) {
        $row['rowID'] = encodeUuid($row['rowID']);
        return $row;
    }
    
    $updatedData = array_map('updateRowID', $messages);
    //------------------------------------------
    //JSON_ENCODE
    //------------------------------------------
    $messages = [
        "results" => $updatedData,
        "total" => count($updatedData)
    ];

    $messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
    //------------------------------------------
    //Send results
    //------------------------------------------
    echo $messages; 

} 
elseif(isset($post_content['dealerfinder'])){
    //++++++++++++++++++++++
    //DEALER FINDER
    //++++++++++++++++++++++

    //remove dealerfinder from post_content
    unset($post_content['dealerfinder']);

    //GET GEOLOCATION
    if ($post_content['range'] && $post_content['lat']!='0' && $post_content['lng']!='0'){
        //INPUT GEOLOCATION USER
        $lat = $post_content['lat'];
        $lng = $post_content['lng'];

        //BUILD GEO-QUERY
        $geo_search_1 = 'ROUND((6371 * acos(cos(radians('.$lat.')) * cos(radians(d.lat)) * cos(radians(d.lng) - radians('.$lng.')) + sin(radians('.$lat.')) * sin(radians(d.lat)))), (2)) AS distance';
        $geo_search_2 = 'HAVING distance < '.$post_content['range']; 
    
        //Build SQL FOR GEO SEARCH
        $sql = 'select d.*,  m.full_path, '.$geo_search_1.' FROM dealers d LEFT JOIN media m ON d.dealer_media = m.rowID WHERE d.status = 1 '.$geo_search_2.' ORDER BY ';
    } 
    else {
        //Use standard
        $sql = 'select d.*, m.full_path FROM dealers d LEFT JOIN media m ON d.dealer_media = m.rowID WHERE d.status = 1 ORDER BY ';
    }
   
    //CHECK ALL THE POSTED ITEMS
    foreach ($post_content as $key => $value){
        //GET FILTER CRITERIA
        if ($key !='submit'  && $key !='city' && $key !='range' && $key !='lat' && $key !='lng' && $value !='C'){
            
            //TRANSLATE RESPONSE TO DATABASE VALUES
            switch ($key) {
                case ($field_question_1 ?? 'budget'): //budget    
                //check value returned and include SQL
                switch ($value) {
                    case '1':
                    $sql .= 'case when d.'.$key.' = 1 then 1 else 0 end +';
                    break;
                        
                    case '0':
                    $sql .= 'case when d.'.$key.' = 0 then 1 else 0 end +';   
                    break;
                }
                //------------------------------------
                break;
            
                case ($field_question_2 ?? 'showroom_quality'): //showroom_quality
                
                //check value returned and include SQL
                switch ($value) {
                    case '2':
                    $sql .= 'case when d.'.$key.' = 2 then 1 else 0 end +';
                    break;
                    
                    case '1':
                    $sql .= 'case when d.'.$key.' = 1 then 1 else 0 end +';
                    break;
                    
                    case '0':
                    $sql .= 'case when d.'.$key.' = 0 then 1 else 0 end +';   
                    break;
                }
                //------------------------------------
                break;

                case ($field_question_3 ?? 'showroom_size'): //showroom_size
                
                //check value returned and include SQL
                switch ($value) {
                    case '2':
                    $sql .= 'case when d.'.$key.' = 2 then 1 else 0 end +';
                    break;
                    
                    case '1':
                    $sql .= 'case when d.'.$key.' = 1 then 1 else 0 end +';
                    break;
                    
                    case '0':
                    $sql .= 'case when d.'.$key.' = 0 then 1 else 0 end +';   
                    break;
                }
                //------------------------------------
                break;

                case ($field_question_4 ?? 'brand_category'): //brand_category
                
                //check value returned and include SQL
                switch ($value) {
                    case '2':
                    $sql .= 'case when d.'.$key.' = 2 then 1 else 0 end +';
                    break;
                    
                    case '1':
                    $sql .= 'case when d.'.$key.' = 1 then 1 else 0 end +';
                    break;
                    
                    case '0':
                    $sql .= 'case when d.'.$key.' = 0 then 1 else 0 end +';   
                    break;
                }
                //------------------------------------
                break;
            }          
        }
    }

    //Replace LAST J
    $sql = removeTrailingElement($sql, ',');
    //REPLACE LAST + with DESC
    $sql = removeTrailingElement($sql, '+').' desc limit 0,4';
    //Prepare statement
    $stmt = $pdo->prepare($sql);
  
    //Excute Query
    $stmt->execute();    
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    //------------------------------------------
    //CHANGE ROWID INTO UUID
    //------------------------------------------
    function updateRowID($row) {
        $row['rowID'] = encodeUuid($row['rowID']);
        return $row;
    }

    $updatedData = array_map('updateRowID', $messages);
    $messages = json_encode($updatedData, JSON_UNESCAPED_UNICODE);
    //------------------------------------------
    //Send results
    //------------------------------------------
    echo $messages; 

}
elseif(isset($post_content['dealer_closeby'])){

    //++++++++++++++++++++++
    //Process FIND CLOSEST DEALERS
    //++++++++++++++++++++++

    //GET GEOLOCATION
    if ((isset($post_content['latitude']) && $post_content['latitude']!='0') && (isset($post_content['longitude']) && $post_content['longitude']!='0')){
        //INPUT GEOLOCATION USER
        $lat = $post_content['latitude'];
        $lng = $post_content['longitude'];

        //Build SQL FOR GEO SEARCH
          $sql = 'SELECT
                    d.rowID,
                    d.name as dealer,
                    d.lat,
                    d.lng,
                    (6371 * acos(
                        cos(radians('.$lat.')) * cos(radians(d.lat)) * cos(radians(d.lng) - radians('.$lng.')) +
                        sin(radians('.$lat.')) * sin(radians(d.lat))
                    )) AS distance_km,
                    m.full_path as imageUrl
                FROM dealers d LEFT JOIN media m ON d.dealer_media = m.rowID
                WHERE d.status = 1
                ORDER BY distance_km
                LIMIT 5';

    //Prepare statement
    $stmt = $pdo->prepare($sql);
 
    //Excute Query
    $stmt->execute();    
 
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    //------------------------------------------
    //CHANGE ROWID INTO UUID
    //------------------------------------------
    function updateRowID($row) {
        $row['rowID'] = encodeUuid($row['rowID']);
        return $row;
    }

    $updatedData = array_map('updateRowID', $messages);
    header('Content-Type: application/json');
    $messages = json_encode($updatedData, JSON_UNESCAPED_UNICODE);
    //------------------------------------------
    //Send results
    //------------------------------------------
    echo $messages; 
    }
    else {
        header('Content-Type: application/json');
        echo json_encode(['error' => "Latitude or longitude not provided."]);
    }
}
else 
{
    //++++++++++++++++++++++
    //STANDAARD PROCESS
    //++++++++++++++++++++++

    //SoldTo is empty
    if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}

    //default whereclause
    list($whereclause,$condition) = getWhereclauselvl2('',$permission,$partner,'');


    //BUILD UP PARTNERHIERARCHY FROM USER
    $partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);

    $id = $post_content['rowID'] ? decodeUuid($post_content['rowID']):''; //check for rowID
    $command = ($id == '')? 'insert' : 'update';  //IF rowID = empty then INSERT
    if (isset($post_content['delete'])){$command = 'delete';} //change command to delete

    //CREATE EMPTY STRINGS
    $clause = '';
    $clause_insert ='';
    $input_insert = '';

    //UPDATE CALCULATED VALUES BUDGET, SHOWROOM_QUALTIY, BRAND_CATEGORY AND UPDATE DEALER_SLUG
    $post_content = processPostContent($post_content);

    if (isset($post_content['opening_hours'])){
        $post_content['opening_hours'] = json_encode($post_content['opening_hours'], JSON_UNESCAPED_UNICODE);
    }

    if ($command == 'update'){
        $post_content['updatedby'] = $username ;
    }
    if ($command == 'insert'){

        //Generate content for missing data
        $keysToCheck = ['short_description', 'long_description', 'usp1', 'usp2', 'usp3'];
    
        foreach ($keysToCheck as $key) {

            $gc = ($post_content['garden_center'] == 0 ? false : true);
            $ml = ($post_content['locations'] == 0 ? false : true);

            //GENERATE DATA
            $generated_content = generateSpaCompanyContent(
                $post_content['name'],    // Company name
                $post_content['city'],           // City
                $gc,                // Garden center (yes/no)
                ${'brand_type_'.$post_content['brand_type']},       // Brand type
                ${'showroom_size_'.$post_content['showroom_size']},              // Showroom size
                ${'focus_offering_'.$post_content['focus_offering']},  // Offering
                ${'dealer_type_'.$post_content['dealer_type']},              // Dealer type
                $ml                 // Multiple locations
            );

            if (isset($post_content[$key]) && (empty($post_content[$key]) || $post_content[$key] == '')) {
                $post_content[$key] = $generated_content[$key]; 
            }
        }
        $post_content['createdby'] = $username;
        $post_content['accounthierarchy'] = $partner_product;
    }

    //CREAT NEW ARRAY AND MAP TO CLAUSE
    if(isset($post_content) && $post_content!=''){   
        foreach ($post_content as $key => $var){
            if ($key == 'submit' || $key == 'rowID'){
                //do nothing
            }
            else {
                $criterias[$key] = $var;
                $clause .= ' , '.$key.' = ?';
                $clause_insert .= ' , '.$key.'';
                $input_insert .= ', ?'; // ? for each insert item
                $execute_input[]= $var; // Build array for input
            }
        }
    }

    //CLEAN UP INPUT
    $clause = substr($clause, 2); //Clean clause - remove first comma
    $clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma
    $input_insert = substr($input_insert, 1); //Clean clause - remove first comma

    //QUERY AND VERIFY ALLOWED
    if ($command == 'update' && isAllowed('dealers',$profile,$permission,'U') === 1){
        $sql = 'UPDATE dealers SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
        $execute_input[] = $id;
        $stmt = $pdo->prepare($sql);
    
        if ($stmt->execute($execute_input)) {
            echo json_encode(array('rowID'=> $id, 'status' => 'updated'));
        }
    } 
    elseif ($command == 'insert' && isAllowed('dealers',$profile,$permission,'C') === 1){
        $sql = 'INSERT INTO dealers ('.$clause_insert.') VALUES ('.$input_insert.')';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);
        // Return ID            
        echo json_encode(array('rowID'=> $pdo->lastInsertId(), 'status' => 'created'));
    }
    elseif ($command == 'delete' && isAllowed('dealers',$profile,$permission,'D') === 1){
        $sql = 'DELETE FROM dealers WHERE rowID = ? '.$whereclause;
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]); 

        //Add deletion to changelog
        changelog($dbname,'dealers',$id,'Delete','Delete',$username);
    } else
    {
        //do nothing
    }
}

?>