<?php
/**
 * Yatoon Booking System - Multi-Location Support v2.4.0
 *
 * Usage:
 *   [yatoon_booking]                     - default location
 *   [yatoon_booking location="2"]        - by ID
 *   [yatoon_booking location="downtown"] - by slug
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class YATOON_Locations {

    public static function init() {
        add_action( 'admin_menu',  array( __CLASS__, 'add_menu' ), 25 );
        add_action( 'wp_ajax_yatoon_save_location',   array( __CLASS__, 'ajax_save_location' ) );
        add_action( 'wp_ajax_yatoon_delete_location', array( __CLASS__, 'ajax_delete_location' ) );
        add_action( 'wp_ajax_yatoon_get_location',    array( __CLASS__, 'ajax_get_location' ) );
    }

    public static function add_menu() {
        // Only show Locations menu when multi-location mode is enabled
        if ( get_option( 'yatoon_multi_location_enabled', '0' ) !== '1' ) {
            return;
        }
        add_submenu_page(
            'yatoon-booking-system',
            __( 'Locations', 'yatoon-booking-system' ),
            __( 'Locations', 'yatoon-booking-system' ),
            'manage_options',
            'yatoon-locations',
            array( __CLASS__, 'render_admin_page' )
        );
    }

    public static function get_table() {
        global $wpdb;
        return $wpdb->prefix . 'yatoon_locations';
    }

    /**
     * Add extra columns introduced in v2.4.0 if they don't exist yet.
     */
    public static function maybe_upgrade_table() {
        global $wpdb;
        $table = self::get_table();
        $cols  = $wpdb->get_col( "DESCRIBE {$table}", 0 ); // phpcs:ignore
        $add   = array(
            'slug'         => "varchar(255) NOT NULL DEFAULT ''",
            'email'        => "varchar(255) NOT NULL DEFAULT ''",
            'description'  => "text",
            'color_accent' => "varchar(20) NOT NULL DEFAULT ''",
            'is_default'   => "tinyint(1) NOT NULL DEFAULT 0",
        );
        foreach ( $add as $col => $def ) {
            if ( ! in_array( $col, $cols, true ) ) {
                $wpdb->query( "ALTER TABLE {$table} ADD COLUMN `{$col}` {$def}" ); // phpcs:ignore
            }
        }
    }

    /**
     * Resolve shortcode attribute to a location row.
     * Returns null if nothing found (caller falls back to global settings).
     */
    public static function resolve( $attr = '' ) {
        global $wpdb;
        $table = self::get_table();

        if ( $attr === '' || $attr === null ) {
            $loc = $wpdb->get_row( "SELECT * FROM {$table} WHERE is_active = 1 AND is_default = 1 LIMIT 1" ); // phpcs:ignore
            if ( ! $loc ) {
                $loc = $wpdb->get_row( "SELECT * FROM {$table} WHERE is_active = 1 ORDER BY id ASC LIMIT 1" ); // phpcs:ignore
            }
            return $loc;
        }

        if ( is_numeric( $attr ) ) {
            return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d AND is_active = 1 LIMIT 1", (int) $attr ) ); // phpcs:ignore
        }

        return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE slug = %s AND is_active = 1 LIMIT 1", sanitize_title( $attr ) ) ); // phpcs:ignore
    }

    public static function get_all( $active_only = false ) {
        global $wpdb;
        $table = self::get_table();
        $where = $active_only ? 'WHERE is_active = 1' : '';
        return $wpdb->get_results( "SELECT * FROM {$table} {$where} ORDER BY is_default DESC, name ASC" ); // phpcs:ignore
    }

    // -- AJAX ------------------------------------------------------------------

    public static function ajax_save_location() {
        check_ajax_referer( 'yatoon_locations_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => 'Permission denied.' ) );

        global $wpdb;
        $table = self::get_table();

        $id          = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
        $name        = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );
        $address     = sanitize_textarea_field( wp_unslash( $_POST['address'] ?? '' ) );
        $phone       = sanitize_text_field( wp_unslash( $_POST['phone'] ?? '' ) );
        $email       = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
        $description = sanitize_textarea_field( wp_unslash( $_POST['description'] ?? '' ) );
        $square_id   = sanitize_text_field( wp_unslash( $_POST['square_id'] ?? '' ) );
        $timezone    = sanitize_text_field( wp_unslash( $_POST['timezone'] ?? '' ) );
        $is_active   = ! empty( $_POST['is_active'] ) ? 1 : 0;
        $is_default  = ! empty( $_POST['is_default'] ) ? 1 : 0;
        $color_accent = sanitize_hex_color( wp_unslash( $_POST['color_accent'] ?? '' ) ) ?: '';
        $slug        = sanitize_title( $name );

        if ( empty( $name ) ) wp_send_json_error( array( 'message' => 'Location name is required.' ) );

        if ( $is_default ) {
            $wpdb->update( $table, array( 'is_default' => 0 ), array( 'is_default' => 1 ), array( '%d' ), array( '%d' ) ); // phpcs:ignore
        }

        $data = array(
            'name' => $name, 'slug' => $slug, 'address' => $address,
            'phone' => $phone, 'email' => $email, 'description' => $description,
            'square_id' => $square_id, 'timezone' => $timezone,
            'is_active' => $is_active, 'is_default' => $is_default,
            'color_accent' => $color_accent,
        );
        $fmt = array( '%s','%s','%s','%s','%s','%s','%s','%s','%d','%d','%s' );

        if ( $id > 0 ) {
            $wpdb->update( $table, $data, array( 'id' => $id ), $fmt, array( '%d' ) ); // phpcs:ignore
            wp_send_json_success( array( 'message' => 'Location updated.', 'id' => $id ) );
        } else {
            $wpdb->insert( $table, $data, $fmt ); // phpcs:ignore
            wp_send_json_success( array( 'message' => 'Location created.', 'id' => $wpdb->insert_id ) );
        }
    }

    public static function ajax_delete_location() {
        check_ajax_referer( 'yatoon_locations_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
        global $wpdb;
        $id = absint( $_POST['id'] ?? 0 );
        if ( ! $id ) wp_send_json_error( array( 'message' => 'Invalid ID.' ) );
        $wpdb->delete( self::get_table(), array( 'id' => $id ), array( '%d' ) ); // phpcs:ignore
        wp_send_json_success( array( 'message' => 'Location deleted.' ) );
    }

    public static function ajax_get_location() {
        check_ajax_referer( 'yatoon_locations_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
        global $wpdb;
        $id  = absint( $_POST['id'] ?? 0 );
        $loc = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}yatoon_locations WHERE id = %d LIMIT 1", $id ) ); // phpcs:ignore
        if ( $loc ) wp_send_json_success( $loc );
        else        wp_send_json_error( array( 'message' => 'Not found.' ) );
    }

    // -- Admin page ------------------------------------------------------------

    public static function render_admin_page() {
        if ( ! current_user_can( 'manage_options' ) ) return;
        self::maybe_upgrade_table();
        $locations = self::get_all();
        $nonce     = wp_create_nonce( 'yatoon_locations_nonce' );
        $timezones = timezone_identifiers_list();
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Locations', 'yatoon-booking-system' ); ?></h1>
            <p style="color:#6b7280;margin-top:0;">
                <?php esc_html_e( 'Add a booking page per location using:', 'yatoon-booking-system' ); ?>
                <code>[yatoon_booking location="<em>id</em>"]</code>
                <?php esc_html_e( 'or', 'yatoon-booking-system' ); ?>
                <code>[yatoon_booking location="<em>slug</em>"]</code>
            </p>

            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width:40px;">ID</th>
                        <th><?php esc_html_e( 'Name', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Slug', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Address', 'yatoon-booking-system' ); ?></th>
                        <th style="width:70px;"><?php esc_html_e( 'Status', 'yatoon-booking-system' ); ?></th>
                        <th style="width:70px;"><?php esc_html_e( 'Default', 'yatoon-booking-system' ); ?></th>
                        <th style="width:180px;"><?php esc_html_e( 'Shortcode', 'yatoon-booking-system' ); ?></th>
                        <th style="width:110px;"><?php esc_html_e( 'Actions', 'yatoon-booking-system' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if ( empty( $locations ) ) : ?>
                    <tr><td colspan="8" style="text-align:center;padding:20px;color:#6b7280;"><?php esc_html_e( 'No locations yet. Create one below.', 'yatoon-booking-system' ); ?></td></tr>
                <?php else : ?>
                    <?php foreach ( $locations as $loc ) : ?>
                    <tr>
                        <td><?php echo esc_html( $loc->id ); ?></td>
                        <td>
                            <strong><?php echo esc_html( $loc->name ); ?></strong>
                            <?php if ( ! empty( $loc->color_accent ) ) : ?>
                            <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:<?php echo esc_attr( $loc->color_accent ); ?>;margin-left:6px;vertical-align:middle;border:1px solid #ddd;"></span>
                            <?php endif; ?>
                        </td>
                        <td><code><?php echo esc_html( $loc->slug ?: sanitize_title( $loc->name ) ); ?></code></td>
                        <td><?php echo esc_html( $loc->address ); ?></td>
                        <td><?php echo $loc->is_active ? '<span style="color:#16a34a;font-weight:600;">Active</span>' : '<span style="color:#9ca3af;">Inactive</span>'; ?></td>
                        <td><?php echo $loc->is_default ? '<span style="color:#2563eb;font-weight:600;">&#10003; Default</span>' : '&mdash;'; ?></td>
                        <td><code style="font-size:11px;">[yatoon_booking location="<?php echo esc_attr( $loc->id ); ?>"]</code></td>
                        <td>
                            <button class="button button-small yloc-edit" data-id="<?php echo esc_attr( $loc->id ); ?>"><?php esc_html_e( 'Edit', 'yatoon-booking-system' ); ?></button>
                            <button class="button button-small yloc-delete" data-id="<?php echo esc_attr( $loc->id ); ?>" style="color:#dc2626;" <?php echo $loc->is_default ? 'disabled title="Cannot delete default location"' : ''; ?>><?php esc_html_e( 'Delete', 'yatoon-booking-system' ); ?></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>

            <!-- Add / Edit form -->
            <div id="yloc-form-wrap" style="background:#fff;border:1px solid #dcdcde;border-radius:4px;padding:20px;margin-top:24px;max-width:720px;">
                <h2 id="yloc-form-title" style="margin-top:0;"><?php esc_html_e( 'Add New Location', 'yatoon-booking-system' ); ?></h2>
                <input type="hidden" id="yloc-id" value="">
                <table class="form-table" style="margin-top:0;">
                    <tr>
                        <th><label for="yloc-name"><?php esc_html_e( 'Location Name', 'yatoon-booking-system' ); ?> *</label></th>
                        <td><input type="text" id="yloc-name" class="regular-text" placeholder="e.g. Downtown Studio"></td>
                    </tr>
                    <tr>
                        <th><label for="yloc-address"><?php esc_html_e( 'Address', 'yatoon-booking-system' ); ?></label></th>
                        <td><textarea id="yloc-address" class="regular-text" rows="2"></textarea></td>
                    </tr>
                    <tr>
                        <th><label for="yloc-phone"><?php esc_html_e( 'Phone', 'yatoon-booking-system' ); ?></label></th>
                        <td><input type="text" id="yloc-phone" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th><label for="yloc-email"><?php esc_html_e( 'Email', 'yatoon-booking-system' ); ?></label></th>
                        <td><input type="email" id="yloc-email" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th><label for="yloc-description"><?php esc_html_e( 'Description', 'yatoon-booking-system' ); ?></label></th>
                        <td><textarea id="yloc-description" class="regular-text" rows="2"></textarea></td>
                    </tr>
                    <tr>
                        <th><label for="yloc-square-id"><?php esc_html_e( 'Square Location ID', 'yatoon-booking-system' ); ?></label></th>
                        <td>
                            <input type="text" id="yloc-square-id" class="regular-text" placeholder="e.g. LXXX000000000000">
                            <p class="description"><?php esc_html_e( 'Pro only: overrides the global Square Location ID for live availability sync.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="yloc-timezone"><?php esc_html_e( 'Timezone', 'yatoon-booking-system' ); ?></label></th>
                        <td>
                            <select id="yloc-timezone" class="regular-text">
                                <option value=""><?php esc_html_e( '- Same as WordPress default -', 'yatoon-booking-system' ); ?></option>
                                <?php foreach ( $timezones as $tz ) : ?>
                                <option value="<?php echo esc_attr( $tz ); ?>"><?php echo esc_html( $tz ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="yloc-color"><?php esc_html_e( 'Accent Color', 'yatoon-booking-system' ); ?></label></th>
                        <td>
                            <input type="color" id="yloc-color" value="#008a00" style="height:36px;width:60px;">
                            <p class="description"><?php esc_html_e( 'Optional: overrides the primary button color on the booking form for this location.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e( 'Active', 'yatoon-booking-system' ); ?></th>
                        <td><label><input type="checkbox" id="yloc-active" checked> <?php esc_html_e( 'Visible to customers', 'yatoon-booking-system' ); ?></label></td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e( 'Set as Default', 'yatoon-booking-system' ); ?></th>
                        <td><label><input type="checkbox" id="yloc-default"> <?php esc_html_e( 'Used when no location is specified in the shortcode', 'yatoon-booking-system' ); ?></label></td>
                    </tr>
                </table>
                <p>
                    <button class="button button-primary" id="yloc-save"><?php esc_html_e( 'Save Location', 'yatoon-booking-system' ); ?></button>
                    <button class="button" id="yloc-cancel" style="margin-left:8px;display:none;"><?php esc_html_e( 'Cancel', 'yatoon-booking-system' ); ?></button>
                    <span id="yloc-msg" style="margin-left:12px;font-size:13px;"></span>
                </p>
            </div>
        </div>

        <script>
        jQuery(function($) {
            const nonce = '<?php echo esc_js( $nonce ); ?>';

            function resetForm() {
                $('#yloc-id').val('');
                $('#yloc-name,#yloc-address,#yloc-phone,#yloc-email,#yloc-description,#yloc-square-id').val('');
                $('#yloc-timezone').val('');
                $('#yloc-color').val('#008a00');
                $('#yloc-active').prop('checked', true);
                $('#yloc-default').prop('checked', false);
                $('#yloc-form-title').text('Add New Location');
                $('#yloc-save').text('Save Location');
                $('#yloc-cancel').hide();
                $('#yloc-msg').text('');
            }

            $('#yloc-cancel').on('click', resetForm);

            $(document).on('click', '.yloc-edit', function() {
                const id = $(this).data('id');
                $.post(ajaxurl, { action: 'yatoon_get_location', nonce: nonce, id: id }, function(r) {
                    if (!r.success) return;
                    var d = r.data;
                    $('#yloc-id').val(d.id);
                    $('#yloc-name').val(d.name);
                    $('#yloc-address').val(d.address);
                    $('#yloc-phone').val(d.phone);
                    $('#yloc-email').val(d.email || '');
                    $('#yloc-description').val(d.description || '');
                    $('#yloc-square-id').val(d.square_id);
                    $('#yloc-timezone').val(d.timezone);
                    $('#yloc-color').val(d.color_accent || '#008a00');
                    $('#yloc-active').prop('checked', d.is_active == 1);
                    $('#yloc-default').prop('checked', d.is_default == 1);
                    $('#yloc-form-title').text('Edit Location: ' + d.name);
                    $('#yloc-save').text('Update Location');
                    $('#yloc-cancel').show();
                    $('html,body').animate({ scrollTop: $('#yloc-form-wrap').offset().top - 40 }, 300);
                });
            });

            $(document).on('click', '.yloc-delete', function() {
                var id = $(this).data('id');
                if (!confirm('Delete this location? This cannot be undone.')) return;
                $.post(ajaxurl, { action: 'yatoon_delete_location', nonce: nonce, id: id }, function(r) {
                    if (r.success) location.reload();
                    else alert((r.data && r.data.message) || 'Error.');
                });
            });

            $('#yloc-save').on('click', function() {
                var $btn = $(this).prop('disabled', true).text('Saving...');
                $.post(ajaxurl, {
                    action:       'yatoon_save_location',
                    nonce:        nonce,
                    id:           $('#yloc-id').val(),
                    name:         $('#yloc-name').val(),
                    address:      $('#yloc-address').val(),
                    phone:        $('#yloc-phone').val(),
                    email:        $('#yloc-email').val(),
                    description:  $('#yloc-description').val(),
                    square_id:    $('#yloc-square-id').val(),
                    timezone:     $('#yloc-timezone').val(),
                    color_accent: $('#yloc-color').val(),
                    is_active:    $('#yloc-active').is(':checked') ? 1 : 0,
                    is_default:   $('#yloc-default').is(':checked') ? 1 : 0,
                }, function(r) {
                    $btn.prop('disabled', false).text($('#yloc-id').val() ? 'Update Location' : 'Save Location');
                    if (r.success) {
                        $('#yloc-msg').css('color','#16a34a').text('\u2713 ' + r.data.message);
                        setTimeout(function() { location.reload(); }, 800);
                    } else {
                        $('#yloc-msg').css('color','#dc2626').text((r.data && r.data.message) || 'Error saving.');
                    }
                });
            });
        });
        </script>
        <?php
    }
}
