<?php
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
/**
 * Shared resources and capacity-aware availability.
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class YATOON_Resources {
    public static function init() {
        self::install_schema();
        add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 24 );
        add_action( 'admin_post_yatoon_save_resource', array( __CLASS__, 'save_resource' ) );
        add_action( 'admin_post_yatoon_delete_resource', array( __CLASS__, 'delete_resource' ) );
    }

    public static function install_schema() {
        if ( get_option( 'yatoon_resources_schema', '' ) === YATOON_DB_VERSION ) {
            return;
        }
        global $wpdb;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        $charset = $wpdb->get_charset_collate();
        dbDelta( "CREATE TABLE {$wpdb->prefix}yatoon_resources (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            location_id bigint(20) NOT NULL DEFAULT 0,
            name varchar(255) NOT NULL,
            capacity int(11) NOT NULL DEFAULT 1,
            is_active tinyint(1) NOT NULL DEFAULT 1,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY is_active (is_active),
            KEY location_id (location_id)
        ) {$charset};" );
        dbDelta( "CREATE TABLE {$wpdb->prefix}yatoon_resource_services (
            resource_id bigint(20) NOT NULL,
            service_id bigint(20) NOT NULL,
            quantity_required int(11) NOT NULL DEFAULT 1,
            PRIMARY KEY (resource_id,service_id),
            KEY service_id (service_id)
        ) {$charset};" );
        if ( YATOON_Schema_Verifier::tables_exist( array( 'yatoon_resources', 'yatoon_resource_services' ) ) ) {
            update_option( 'yatoon_resources_schema', YATOON_DB_VERSION, false );
        }
    }

    public static function is_available( $service_id, DateTimeInterface $start, DateTimeInterface $end, $exclude_booking_id = 0, $location_id = null, $exclude_group_session_id = 0 ) {
        if ( class_exists( 'YATOON_Feature_Modules' ) && ! YATOON_Feature_Modules::enabled( 'resources' ) ) { return true;
        }
        global $wpdb;
        $location_id = null === $location_id ? absint( $_POST['yatoon_location_id'] ?? 0 ) : absint( $location_id );
        $requirements = $wpdb->get_results( $wpdb->prepare(
            "SELECT r.id, r.capacity, r.location_id, rs.quantity_required
             FROM {$wpdb->prefix}yatoon_resources r
             JOIN {$wpdb->prefix}yatoon_resource_services rs ON rs.resource_id=r.id
             WHERE rs.service_id=%d AND r.is_active=1 AND (r.location_id=0 OR r.location_id=%d)",
            $service_id,
            $location_id
        ) );
        if ( ! $requirements ) {
            return true;
        }
        foreach ( $requirements as $resource ) {
            $used = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COALESCE(SUM(rs.quantity_required),0)
                 FROM {$wpdb->prefix}yatoon_bookings b
                 JOIN {$wpdb->prefix}yatoon_resource_services rs ON rs.service_id=b.service_id
                 WHERE rs.resource_id=%d
                   AND b.id<>%d
                   AND (%d=0 OR b.location_id=%d)
                   AND b.status NOT IN ('cancelled','canceled','declined')
                   AND b.start_time < %s AND b.end_time > %s",
                $resource->id,
                absint( $exclude_booking_id ),
                (int) $resource->location_id,
                (int) $resource->location_id,
                $end->format( 'Y-m-d H:i:s' ),
                $start->format( 'Y-m-d H:i:s' )
            ) );
            if ( class_exists( 'YATOON_Feature_Modules' ) && YATOON_Feature_Modules::enabled( 'group_appointments' ) ) {
                $used += (int) $wpdb->get_var( $wpdb->prepare(
                    "SELECT COALESCE(SUM(rs.quantity_required),0)
                     FROM {$wpdb->prefix}yatoon_group_sessions g
                     JOIN {$wpdb->prefix}yatoon_resource_services rs ON rs.service_id=g.service_id
                     WHERE rs.resource_id=%d AND g.id<>%d AND g.status='active'
                       AND (%d=0 OR g.location_id=%d)
                       AND g.start_time<%s AND g.end_time>%s",
                    $resource->id, absint( $exclude_group_session_id ), (int) $resource->location_id, (int) $resource->location_id,
                    $end->format( 'Y-m-d H:i:s' ), $start->format( 'Y-m-d H:i:s' )
                ) );
            }
            if ( $used + max( 1, (int) $resource->quantity_required ) > max( 1, (int) $resource->capacity ) ) {
                return false;
            }
        }
        return true;
    }

    public static function add_menu() {
        add_submenu_page(
            'yatoon-booking-system',
            __( 'Resources', 'yatoon-booking-system' ),
            __( 'Resources', 'yatoon-booking-system' ),
            'yatoon_manage_services',
            'yatoon-resources',
            array( __CLASS__, 'render_admin' )
        );
    }

    private static function require_admin() {
        if ( ! current_user_can( 'yatoon_manage_services' ) ) {
            wp_die( esc_html__( 'You do not have permission to manage resources.', 'yatoon-booking-system' ) );
        }
    }

    public static function save_resource() {
        self::require_admin();
        check_admin_referer( 'yatoon_save_resource' );
        global $wpdb;
        $id = absint( $_POST['resource_id'] ?? 0 );
        $data = array(
            'location_id' => absint( $_POST['location_id'] ?? 0 ),
            'name' => sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) ),
            'capacity' => max( 1, absint( $_POST['capacity'] ?? 1 ) ),
            'is_active' => empty( $_POST['is_active'] ) ? 0 : 1,
            'updated_at' => current_time( 'mysql' ),
        );
        if ( ! $data['name'] ) {
            wp_safe_redirect( admin_url( 'admin.php?page=yatoon-resources' ) );
            exit;
        }
        if ( $id ) {
            $wpdb->update( $wpdb->prefix . 'yatoon_resources', $data, array( 'id' => $id ) );
        } else {
            $data['created_at'] = current_time( 'mysql' );
            $wpdb->insert( $wpdb->prefix . 'yatoon_resources', $data );
            $id = (int) $wpdb->insert_id;
        }
        $wpdb->delete( $wpdb->prefix . 'yatoon_resource_services', array( 'resource_id' => $id ) );
        foreach ( array_map( 'absint', (array) ( $_POST['service_ids'] ?? array() ) ) as $service_id ) {
            if ( $service_id ) {
                $wpdb->insert(
                    $wpdb->prefix . 'yatoon_resource_services',
                    array(
                        'resource_id' => $id,
                        'service_id' => $service_id,
                        'quantity_required' => max( 1, absint( $_POST['quantity_required'][ $service_id ] ?? 1 ) ),
                    )
                );
            }
        }
        wp_safe_redirect( admin_url( 'admin.php?page=yatoon-resources' ) );
        exit;
    }

    public static function delete_resource() {
        self::require_admin();
        check_admin_referer( 'yatoon_delete_resource' );
        global $wpdb;
        $id = absint( $_GET['resource_id'] ?? 0 );
        $wpdb->delete( $wpdb->prefix . 'yatoon_resource_services', array( 'resource_id' => $id ) );
        $wpdb->delete( $wpdb->prefix . 'yatoon_resources', array( 'id' => $id ) );
        wp_safe_redirect( admin_url( 'admin.php?page=yatoon-resources' ) );
        exit;
    }

    public static function render_admin() {
        self::require_admin();
        global $wpdb;
        $edit_id = absint( $_GET['resource_id'] ?? 0 );
        $editing = $edit_id ? $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}yatoon_resources WHERE id=%d", $edit_id ) ) : null;
        $assigned = $edit_id ? $wpdb->get_results( $wpdb->prepare( "SELECT service_id, resource_id, quantity_required FROM {$wpdb->prefix}yatoon_resource_services WHERE resource_id=%d", $edit_id ), OBJECT_K ) : array();
        $services = $wpdb->get_results( "SELECT id,name FROM {$wpdb->prefix}yatoon_services WHERE is_active=1 ORDER BY name" );
        $locations = $wpdb->get_results( "SELECT id,name FROM {$wpdb->prefix}yatoon_locations WHERE is_active=1 ORDER BY name" );
        $resources = $wpdb->get_results(
            "SELECT r.*, COUNT(rs.service_id) service_count FROM {$wpdb->prefix}yatoon_resources r
             LEFT JOIN {$wpdb->prefix}yatoon_resource_services rs ON rs.resource_id=r.id
             GROUP BY r.id ORDER BY r.name"
        );
        ?>
        <div class="wrap yr-wrap"><h1><?php esc_html_e( 'Shared resources', 'yatoon-booking-system' ); ?></h1><p><?php esc_html_e( 'Limit simultaneous bookings by equipment, chairs, rooms, or workstations.', 'yatoon-booking-system' ); ?></p>
        <div class="yr-grid"><section class="yr-panel"><h2><?php echo esc_html( $editing ? __( 'Edit resource', 'yatoon-booking-system' ) : __( 'Add resource', 'yatoon-booking-system' ) ); ?></h2><form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><?php wp_nonce_field( 'yatoon_save_resource' ); ?><input type="hidden" name="action" value="yatoon_save_resource"><input type="hidden" name="resource_id" value="<?php echo esc_attr( $edit_id ); ?>"><label><?php esc_html_e( 'Name', 'yatoon-booking-system' ); ?><input name="name" required value="<?php echo esc_attr( $editing->name ?? '' ); ?>" placeholder="<?php echo esc_attr__( 'Pedicure chairs', 'yatoon-booking-system' ); ?>"></label><label><?php esc_html_e( 'Location', 'yatoon-booking-system' ); ?><select name="location_id"><option value="0"><?php esc_html_e( 'Shared across all locations', 'yatoon-booking-system' ); ?></option><?php foreach ( $locations as $location ) : ?><option value="<?php echo esc_attr( $location->id ); ?>" <?php selected( $editing->location_id ?? 0, $location->id ); ?>><?php echo esc_html( $location->name ); ?></option><?php endforeach; ?></select></label><label><?php esc_html_e( 'Available capacity', 'yatoon-booking-system' ); ?><input type="number" min="1" name="capacity" value="<?php echo esc_attr( $editing->capacity ?? 1 ); ?>"></label><label class="yr-check"><input type="checkbox" name="is_active" value="1" <?php checked( ! $editing || $editing->is_active ); ?>> <?php esc_html_e( 'Active', 'yatoon-booking-system' ); ?></label><h3><?php esc_html_e( 'Services that use this resource', 'yatoon-booking-system' ); ?></h3><div class="yr-services"><?php foreach ( $services as $service ) : $link = $assigned[ $service->id ] ?? null; ?><div><label class="yr-check"><input type="checkbox" name="service_ids[]" value="<?php echo esc_attr( $service->id ); ?>" <?php checked( (bool) $link ); ?>> <?php echo esc_html( $service->name ); ?></label><label><?php esc_html_e( 'Units per booking', 'yatoon-booking-system' ); ?><input type="number" min="1" name="quantity_required[<?php echo esc_attr( $service->id ); ?>]" value="<?php echo esc_attr( $link->quantity_required ?? 1 ); ?>"></label></div><?php endforeach; ?></div><button class="button button-primary"><?php esc_html_e( 'Save resource', 'yatoon-booking-system' ); ?></button></form></section>
        <section class="yr-panel"><h2><?php esc_html_e( 'Resources', 'yatoon-booking-system' ); ?></h2><?php if ( ! $resources ) : ?><p><?php esc_html_e( 'No shared resources configured. Availability continues to use staff capacity only.', 'yatoon-booking-system' ); ?></p><?php endif; ?><?php foreach ( $resources as $resource ) : ?><article class="yr-row"><div><strong><?php echo esc_html( $resource->name ); ?></strong><small><?php echo esc_html( sprintf( _n( 'Capacity %1$d · %2$d service · %3$s', 'Capacity %1$d · %2$d services · %3$s', $resource->service_count, 'yatoon-booking-system' ), $resource->capacity, $resource->service_count, $resource->is_active ? __( 'Active', 'yatoon-booking-system' ) : __( 'Paused', 'yatoon-booking-system' ) ) ); ?></small></div><div><a class="button button-small" href="<?php echo esc_url( admin_url( 'admin.php?page=yatoon-resources&resource_id=' . $resource->id ) ); ?>"><?php esc_html_e( 'Edit', 'yatoon-booking-system' ); ?></a> <a class="button button-small" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=yatoon_delete_resource&resource_id=' . $resource->id ), 'yatoon_delete_resource' ) ); ?>" onclick="return confirm('<?php echo esc_js( __( 'Delete this resource?', 'yatoon-booking-system' ) ); ?>')"><?php esc_html_e( 'Delete', 'yatoon-booking-system' ); ?></a></div></article><?php endforeach; ?></section></div>
        <style>.yr-wrap{max-width:1200px}.yr-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px}.yr-panel{background:#fff;border:1px solid #dcdcde;border-radius:6px;padding:20px}.yr-panel>h2{margin-top:0}.yr-panel label{display:block;font-weight:600;margin:12px 0}.yr-panel input[type=text],.yr-panel input[type=number],.yr-panel input:not([type]){display:block;width:100%;margin-top:5px}.yr-check{font-weight:500!important}.yr-services{max-height:420px;overflow:auto;border:1px solid #dcdcde;padding:0 14px;margin-bottom:18px}.yr-services>div{display:grid;grid-template-columns:1fr 120px;align-items:center;border-bottom:1px solid #eee}.yr-row{display:flex;justify-content:space-between;gap:12px;padding:14px 0;border-bottom:1px solid #eee}.yr-row small{display:block;color:#646970;margin-top:4px}@media(max-width:900px){.yr-grid{grid-template-columns:1fr}}</style></div>
        <?php
    }
}
