<?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,
            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)
        ) {$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};" );
        update_option( 'yatoon_resources_schema', YATOON_DB_VERSION, false );
    }

    public static function is_available( $service_id, DateTimeInterface $start, DateTimeInterface $end, $exclude_booking_id = 0 ) {
        global $wpdb;
        $requirements = $wpdb->get_results( $wpdb->prepare(
            "SELECT r.id, r.capacity, 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",
            $service_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 b.status NOT IN ('cancelled','canceled','declined')
                   AND b.start_time < %s AND b.end_time > %s",
                $resource->id,
                absint( $exclude_booking_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(
            '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" );
        $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>Shared resources</h1><p>Limit simultaneous bookings by equipment, chairs, rooms, or workstations.</p>
        <div class="yr-grid"><section class="yr-panel"><h2><?php echo $editing ? 'Edit resource' : 'Add resource'; ?></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>Name<input name="name" required value="<?php echo esc_attr( $editing->name ?? '' ); ?>" placeholder="Pedicure chairs"></label><label>Available capacity<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 ); ?>> Active</label><h3>Services that use this resource</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>Units per booking<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">Save resource</button></form></section>
        <section class="yr-panel"><h2>Resources</h2><?php if ( ! $resources ) : ?><p>No shared resources configured. Availability continues to use staff capacity only.</p><?php endif; ?><?php foreach ( $resources as $resource ) : ?><article class="yr-row"><div><strong><?php echo esc_html( $resource->name ); ?></strong><small>Capacity <?php echo esc_html( $resource->capacity ); ?> · <?php echo esc_html( $resource->service_count ); ?> services · <?php echo $resource->is_active ? 'Active' : 'Paused'; ?></small></div><div><a class="button button-small" href="<?php echo esc_url( admin_url( 'admin.php?page=yatoon-resources&resource_id=' . $resource->id ) ); ?>">Edit</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('Delete this resource?')">Delete</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
    }
}
