<?php

namespace Bookingor\Backend\Controller\Location;

use Bookingor\Backend\Controller\LocationTimeSheet\LocationTimeSheetControl;

/**
 * Manages location-related operations such as adding, retrieving, updating, and deleting locations in the database.
 *
 * Includes functions for adding a new location, retrieving location data by ID, updating location details,
 * viewing all locations, and deleting a location.
 */


class LocationControl
{
    private static $bookingorDb;
    /**
     * Database table prefix for booking-related tables.
     *
     * @var string
     */
    public static $dp_prefix = "bookingor_";
    /**
     * Stores the location data retrieved from the database.
     *
     * @var array|null
     */
    public static $location_get_data;
    /**
     * The ID of the location being used.
     *

     * @var int
     */
    public $location_get_id;
    /**
     * Adds a new location to the database.
     *
     * This function handles the post request sent from the location create form.
     * It retrieves the form data and inserts it into the database table.
     * If the plugin "bookingor-location-timesheet" is active, it also calls the
     * bookingor_add_location_timesheet function to add the time sheet for the
     * newly created location.
     *
     * @return void
     */
    public function bp_add_location()
    {
        global $wpdb;
        $add_location = $wpdb->prefix . self::$dp_prefix . 'location';
        self::$bookingorDb = $wpdb;
        if (isset($_REQUEST['action'])) {


            if (isset($_POST['nonce'])) {
                if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                    $response = [
                        'status' => htmlspecialchars('error'),
                        'message' => htmlspecialchars('Nonce verification failed.')
                    ];
                }
            }
            if (!current_user_can('manage_options')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('You do not have permission.')
                ];
                echo wp_json_encode($response);
                die();
            }

            $location_title = sanitize_text_field(wp_unslash($_POST['bookingor_location_title'] ?? ''));
            $location_icon = sanitize_text_field(wp_unslash($_POST['location_icon_id'] ?? ''));
            $location_address = sanitize_text_field(wp_unslash($_POST['bp_location_streetAddress'] ?? ''));
            
            // Check location limit for free version
            $locations = self::bp_get_location_view();
            $location_count = is_array($locations) ? count($locations) : (is_object($locations) ? count((array)$locations) : 0);
            $is_pro = class_exists('Bookingor\Backend\Controller\LocationTimeSheet\LocationTimeSheetControl');
            
            if ($location_count >= 1 && !$is_pro) {
                $response = [
                    'status' => 'error',
                    'message' => __('The free version allows only 1 location. Upgrade to our Pro plan to add unlimited locations.', 'bookingor')
                ];
                echo wp_json_encode($response);
                exit;
            }

            update_option("bookingor_settings_location_active", "on");
            self::$bookingorDb->insert(
                $add_location,
                array(
                    'location_title' => $location_title,
                    'location_icon' => $location_icon,
                    'location_address' => $location_address,
                )
            );
            $this->location_get_id = $wpdb->insert_id;

            $get_location_name = get_option('bookingor_settings_location_name');
            $response = [
                'status' => htmlspecialchars('success'),
                'message' =>  $get_location_name . htmlspecialchars(' Created Successfully')
            ];
            echo wp_json_encode($response);
            exit;
        }
    }
    /**
     * Retrieves the location data from the database for a given location ID.
     *
     * Expects the location ID to be passed in the request as 'location_id'.
     *
     * @return void
     */
    public static function bp_get_location()
    {
        $response  = new \stdclass();
        $response->success = false;
        global $wpdb;
        $location = $wpdb->prefix . self::$dp_prefix . 'location';

        $location_id = isset($_POST['locations_id']) ? intval($_POST['locations_id']) : 0;


        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('Nonce verification failed.')
                ];
            }
        }


        $response = self::$bookingorDb->get_results($wpdb->prepare("SELECT location_id, location_title, location_icon, location_address, status FROM {$wpdb->prefix}bookingor_location WHERE location_id = %d", $location_id));
        echo wp_json_encode($response);
        die;
    }
    /**
     * Updates the location data in the database for a given location ID.
     *
     * Expects the location ID to be passed in the request as 'location_id'.
     *
     * @return void
     */
    public function bp_update_location()
    {
        global $wpdb;
        $update_location = $wpdb->prefix . self::$dp_prefix . 'location';
        self::$bookingorDb = $wpdb;
        if (isset($_REQUEST['action'])) {


            if (isset($_POST['nonce'])) {
                if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                    $response = [
                        'status' => htmlspecialchars('error'),
                        'message' => htmlspecialchars('Nonce verification failed.')
                    ];
                }
            }
            if (!current_user_can('manage_options')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('You do not have permission.')
                ];
                echo wp_json_encode($response);
                die();
            }

            $location_title = sanitize_text_field(wp_unslash($_POST['bookingor_location_title']  ?? ""));
            $location_id   = sanitize_text_field(wp_unslash($_POST['bookingor_location_id'] ?? ""));
            $location_icon = sanitize_text_field(wp_unslash($_POST['location_icon_id_update'] ?? ""));

            $location_address = sanitize_text_field(wp_unslash($_POST['bp_location_streetAddress'] ?? ""));
            $location_lati = sanitize_text_field(wp_unslash($_POST['bp_location_lati'] ?? ""));
            $location_langi = sanitize_text_field(wp_unslash($_POST['bp_location_langi'] ?? ""));
            self::$bookingorDb->update(
                $update_location,
                array(
                    'location_title' => $location_title,
                    'location_icon' => $location_icon,
                    'location_address' => $location_address,
                    'location_latitude' => $location_lati,
                    'location_longitude' => $location_langi,
                ),
                array('location_id' => $location_id)
            );

            $get_location_name = get_option('bookingor_settings_location_name');
            $response = [
                'status' => htmlspecialchars('success'),
                'message' =>  $get_location_name . htmlspecialchars(' Updated Successfully')
            ];
            echo wp_json_encode($response);
            exit;
        }
    }
    /**
     * Retrieves the location data from the database for all locations.
     *
     * Returns an array of objects, each containing the location ID, country, city, address, phone, latitude, and longitude.
     *
     * @return array
     */
    public static function bp_get_location_view()
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $location = $wpdb->prefix . self::$dp_prefix . 'location';
        $query = "SELECT l.location_id, l.location_title, l.location_country, l.location_city, l.location_address, l.location_phone, l.location_latitude, l.location_longitude
          FROM %1\$s AS l";
        return self::$location_get_data = self::$bookingorDb->get_results(self::$bookingorDb->prepare($query, $location));
    }
    /**
     * Deletes a location from the database.
     *
     * Expects the location ID to be passed in the request as 'id'.
     *
     * @return void
     */
    public function bp_delete_location()
    {
        global $wpdb;
        $delete_location = $wpdb->prefix . self::$dp_prefix . 'location';
        self::$bookingorDb = $wpdb;


        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('Nonce verification failed.')
                ];
            }
        }
        if (!current_user_can('manage_options')) {
            $response = [
                'status' => htmlspecialchars('error'),
                'message' => htmlspecialchars('You do not have permission.')
            ];
            echo wp_json_encode($response);
            die();
        }
        self::$bookingorDb->delete($delete_location, array(
            'location_id' => sanitize_text_field(wp_unslash($_REQUEST["id"] ?? ""))
        ));
    }
}
