<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<?php
global $wpdb;
$categories = ROS_DB::get_categories();
$active_cat = intval( $_GET['cat'] ?? ( $categories[0]['id'] ?? 0 ) );
$edit_cat   = intval( $_GET['edit_cat'] ?? 0 );
$edit_dish  = intval( $_GET['edit_dish'] ?? 0 );
$add_dish   = intval( $_GET['add_dish'] ?? 0 );

$editing_cat  = $edit_cat ? $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ros_categories WHERE id=%d", $edit_cat ), ARRAY_A ) : null;
$editing_dish = $edit_dish ? $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ros_dishes WHERE id=%d", $edit_dish ), ARRAY_A ) : null;
$s            = ROS_DB::get_all_settings();
$currency     = $s['currency_symbol'] ?? '$';
?>
<div class="ros-admin-wrap">
  <div class="ros-admin-header">
    <h1>📖 Menu Management</h1>
    <a href="<?php echo admin_url( 'admin.php?page=ros-menu&edit_cat=new' ); ?>" class="ros-btn ros-btn-primary">+ Add Category</a>
  </div>
  <?php if ( isset( $_GET['saved'] ) ): ?><div class="notice notice-success"><p>✅ Saved!</p></div><?php endif; ?>

  <!-- Category Form -->
  <?php if ( isset( $_GET['edit_cat'] ) ): ?>
  <div class="ros-form-card">
    <h2><?php echo $editing_cat ? 'Edit Category' : 'New Category'; ?></h2>
    <form method="post" action="<?php echo admin_url( 'admin-post.php' ); ?>">
      <?php wp_nonce_field( 'ros_category' ); ?>
      <input type="hidden" name="action" value="ros_save_category">
      <input type="hidden" name="cat_id" value="<?php echo esc_attr( $editing_cat['id'] ?? 0 ); ?>">
      <div class="ros-field">
        <label>Category Name</label>
        <input type="text" name="name" value="<?php echo esc_attr( $editing_cat['name'] ?? '' ); ?>" required>
      </div>
      <div class="ros-field">
        <label>Sort Order</label>
        <input type="number" name="sort_order" value="<?php echo esc_attr( $editing_cat['sort_order'] ?? 0 ); ?>">
      </div>
      <button type="submit" class="ros-btn ros-btn-primary">Save Category</button>
      <a href="<?php echo admin_url( 'admin.php?page=ros-menu' ); ?>" class="ros-btn ros-btn-secondary">Cancel</a>
    </form>
  </div>
  <?php endif; ?>

  <!-- Dish Form -->
  <?php if ( $editing_dish || $add_dish ): ?>
  <div class="ros-form-card">
    <h2><?php echo $editing_dish ? 'Edit Dish' : 'New Dish'; ?></h2>
    <form method="post" action="<?php echo admin_url( 'admin-post.php' ); ?>">
      <?php wp_nonce_field( 'ros_dish' ); ?>
      <input type="hidden" name="action" value="ros_save_dish">
      <input type="hidden" name="dish_id" value="<?php echo esc_attr( $editing_dish['id'] ?? 0 ); ?>">
      <div class="ros-field">
        <label>Category</label>
        <select name="category_id">
          <?php foreach ( $categories as $cat ): ?>
            <option value="<?php echo $cat['id']; ?>" <?php selected( ( $editing_dish['category_id'] ?? $add_dish ), $cat['id'] ); ?>>
              <?php echo esc_html( $cat['name'] ); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="ros-field">
        <label>Dish Name</label>
        <input type="text" name="name" value="<?php echo esc_attr( $editing_dish['name'] ?? '' ); ?>" required>
      </div>
      <div class="ros-field">
        <label>Description</label>
        <textarea name="description" rows="2"><?php echo esc_textarea( $editing_dish['description'] ?? '' ); ?></textarea>
      </div>
      <div class="ros-field">
        <label>Price (<?php echo esc_html( $currency ); ?>)</label>
        <input type="number" name="price" step="0.01" min="0" value="<?php echo esc_attr( $editing_dish['price'] ?? '' ); ?>" required>
      </div>
      <div class="ros-field">
        <label>Image URL</label>
        <div style="display:flex;gap:10px;align-items:center">
          <input type="text" name="image_url" id="ros_dish_img" value="<?php echo esc_attr( $editing_dish['image_url'] ?? '' ); ?>" style="flex:1">
          <button type="button" class="button" id="ros-upload-dish-img">Upload</button>
        </div>
      </div>
      <div class="ros-field">
        <label>Sort Order</label>
        <input type="number" name="sort_order" value="<?php echo esc_attr( $editing_dish['sort_order'] ?? 0 ); ?>">
      </div>
      <div class="ros-field">
        <label><input type="checkbox" name="available" value="1" <?php checked( $editing_dish['available'] ?? 1, 1 ); ?>> Available</label>
      </div>
      <button type="submit" class="ros-btn ros-btn-primary">Save Dish</button>
      <a href="<?php echo admin_url( 'admin.php?page=ros-menu&cat=' . $active_cat ); ?>" class="ros-btn ros-btn-secondary">Cancel</a>
    </form>
  </div>
  <script>
  jQuery(function($){
    $('#ros-upload-dish-img').click(function(){
      var frame = wp.media({ title:'Select Image', multiple:false });
      frame.on('select', function(){ $('#ros_dish_img').val(frame.state().get('selection').first().toJSON().url); });
      frame.open();
    });
  });
  </script>
  <?php endif; ?>

  <!-- Category Tabs -->
  <div class="ros-cat-admin-tabs">
    <?php foreach ( $categories as $cat ): ?>
      <a href="<?php echo admin_url( 'admin.php?page=ros-menu&cat=' . $cat['id'] ); ?>"
         class="ros-cat-admin-tab <?php echo $active_cat == $cat['id'] ? 'active' : ''; ?>">
        <?php echo esc_html( $cat['name'] ); ?>
        <span class="ros-cat-actions">
          <a href="<?php echo admin_url( 'admin.php?page=ros-menu&edit_cat=' . $cat['id'] ); ?>">✏️</a>
          <a href="<?php echo wp_nonce_url( admin_url( 'admin-post.php?action=ros_delete_category&id=' . $cat['id'] ), 'ros_del_cat' ); ?>"
             onclick="return confirm('Delete category and all its dishes?')">🗑️</a>
        </span>
      </a>
    <?php endforeach; ?>
  </div>

  <!-- Dishes Table -->
  <?php if ( $active_cat ): ?>
    <div class="ros-dishes-admin">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px">
        <h2>Dishes</h2>
        <a href="<?php echo admin_url( 'admin.php?page=ros-menu&add_dish=' . $active_cat ); ?>" class="ros-btn ros-btn-primary">+ Add Dish</a>
      </div>
      <?php $dishes = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ros_dishes WHERE category_id=%d ORDER BY sort_order,name", $active_cat ), ARRAY_A ); ?>
      <?php if ( empty( $dishes ) ): ?>
        <p class="ros-empty">No dishes yet. <a href="<?php echo admin_url( 'admin.php?page=ros-menu&add_dish=' . $active_cat ); ?>">Add the first dish.</a></p>
      <?php else: ?>
        <table class="widefat ros-table">
          <thead><tr><th>Image</th><th>Name</th><th>Description</th><th>Price</th><th>Available</th><th>Actions</th></tr></thead>
          <tbody>
          <?php foreach ( $dishes as $dish ): ?>
            <tr>
              <td><?php if ( $dish['image_url'] ): ?><img src="<?php echo esc_url( $dish['image_url'] ); ?>" style="width:50px;height:50px;object-fit:cover;border-radius:6px"><?php else: ?>—<?php endif; ?></td>
              <td><strong><?php echo esc_html( $dish['name'] ); ?></strong></td>
              <td><?php echo esc_html( wp_trim_words( $dish['description'], 8 ) ); ?></td>
              <td><?php echo esc_html( $currency . number_format( $dish['price'], 2 ) ); ?></td>
              <td><?php echo $dish['available'] ? '✅' : '❌'; ?></td>
              <td>
                <a href="<?php echo admin_url( 'admin.php?page=ros-menu&edit_dish=' . $dish['id'] . '&cat=' . $active_cat ); ?>" class="button button-small">Edit</a>
                <a href="<?php echo wp_nonce_url( admin_url( 'admin-post.php?action=ros_delete_dish&id=' . $dish['id'] . '&cat=' . $active_cat ), 'ros_del_dish' ); ?>"
                   class="button button-small ros-btn-danger-sm" onclick="return confirm('Delete this dish?')">Delete</a>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</div>
