<?php

/**
 * Provide a admin area view for the plugin
 *
 * This file is used to markup the admin-facing aspects of the plugin.
 *
 * @link       https://onexgen.com
 * @since      1.0.0
 *
 * @package    Mpwa_Notifications
 * @subpackage Mpwa_Notifications/admin/partials
 */

?>

<?php
if ( ! defined( 'ABSPATH' ) ) exit;

settings_errors( 'mpwa_notifications_main_messages' );

if ( ! function_exists( 'is_plugin_active' ) ) {
    include_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$wc_installed = file_exists( WP_PLUGIN_DIR . '/woocommerce/woocommerce.php' );
$wc_active = class_exists('WooCommerce') && ( is_plugin_active('woocommerce/woocommerce.php') || ( function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('woocommerce/woocommerce.php') ) );

$is_secret_key_set = isset($mpwa_options['mpwa_notifications_field_secret_key']) && trim($mpwa_options['mpwa_notifications_field_secret_key']) != '';
?>
<div class="wrap">
  <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
</div>

<div class="mpwa-admin-list wrap" data-wc-ready="<?php echo $wc_active ? '1' : '0'; ?>">
  <?php if (!$is_secret_key_set): ?>
  <div class="mpwa-alert mpwa-alert-danger">
    <button type="button" class="mpwa-clsbutton" aria-label="Close">&times;</button>
    <div class="mpwa-alert-header">[Action Required] Secret Key is not set.</div>
    <div class="mpwa-alert-content">
      <p>The secret key must be set for message notification to work. Please visit the <b><a href="<?php echo esc_url( admin_url('admin.php?page=mpwa-notifications-options') ) ?>">Options</a></b> page to configure the Secret Key.</p>
    </div>
  </div>
  <?php endif; ?>

  <?php if (!$wc_active): ?>
  <div class="mpwa-alert mpwa-alert-warning">
    <button type="button" class="mpwa-clsbutton" aria-label="Close">&times;</button>
    <div class="mpwa-alert-header">WooCommerce is required</div>
    <div class="mpwa-alert-content">
      <?php if ( $wc_installed ): ?>
        <p>WooCommerce is installed but not active. Please <a href="<?php echo esc_url( admin_url('plugins.php') ); ?>">activate WooCommerce</a> to use MPWA Notifications.</p>
      <?php else: ?>
        <p>WooCommerce is not installed. Please <a href="<?php echo esc_url( admin_url('plugin-install.php?s=woocommerce&tab=search&type=term') ); ?>">install WooCommerce</a> and activate it to use MPWA Notifications.</p>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <div class="mpwa-toolbar">
    <div class="mpwa-toolbar-left">
      <div class="mpwa-title">WooCommerce Notifications</div>
    </div>
    <div class="mpwa-toolbar-right">
      <input type="search" id="mpwa-filter" class="regular-text mpwa-toolbar-right" placeholder="Filter events...">
      <button type="button" id="mpwa-enable-all" class="button" <?php echo $wc_active ? '' : 'disabled'; ?>>Enable all</button>
      <button type="button" id="mpwa-disable-all" class="button" <?php echo $wc_active ? '' : 'disabled'; ?>>Disable all</button>
    </div>
  </div>

  <form action="options.php" method="post" id="mpwa-main-form">
    <div class="mpwa-card <?php echo $wc_active ? '' : 'mpwa-card-disabled'; ?>">
      <div class="mpwa-wp-loading-overlay" id="mpwa_loading_overlay"><div class="mpwa-spinner"></div>Loading...</div>
      <table class="widefat striped mpwa-wp-table mpwa-table">
        <thead>
          <tr>
            <th>Event</th>
            <th>Status</th>
            <th style="width:160px">Action</th>
          </tr>
        </thead>
        <tbody id="mpwa-table-body">
          <?php foreach ($template_contents as $key => $content): ?>
            <?php $current_content_db = $mpwa_db->get_content($content['code']); ?>
            <tr>
              <td class="mpwa-evt">
                <div class="mpwa-evt-title"><?php echo esc_html( $content['title'] ) ?></div>
                <div class="mpwa-evt-meta"><?php echo esc_html( $content['code'] ) ?></div>
              </td>
              <td>
                <label class="mpwa-wp-switch">
                  <input
                    class="mpwa-content-status"
                    type="checkbox"
                    name="<?php echo esc_attr( $content['code'] ) ?>"
                    <?php if (!empty($current_content_db)) { if ($current_content_db->is_active == '1') echo 'checked'; } ?>
                    <?php echo $wc_active ? '' : 'disabled'; ?>
                    title="<?php echo $wc_active ? '' : 'Disabled until WooCommerce is active'; ?>"
                  >
                  <span class="mpwa-wp-slider round"></span>
                </label>
              </td>
              <td>
                <a
                  class="button button-primary mpwa-edit-btn <?php echo $wc_active ? '' : 'is-disabled'; ?>"
                  href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=mpwa-notifications&template_code=' . urlencode($content['code'])), 'mpwa_edit_template' ) ); ?>"
                  <?php echo $wc_active ? '' : 'tabindex="-1" aria-disabled="true"'; ?>
                  title="<?php echo $wc_active ? 'Edit Template' : 'Enable WooCommerce to edit templates'; ?>"
                >
                  <span class="dashicons dashicons-edit"></span>
                  Edit Template
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </form>
</div>

<style>
.mpwa-admin-list{--gap:16px;margin-top:10px}
.mpwa-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;border:1px solid #e2e8f0;background:#fff;border-radius:10px;padding:12px 14px;margin-bottom:12px}
.mpwa-title{font-weight:600}
.mpwa-toolbar-right{display:flex;align-items:center;gap:8px}
.mpwa-card{position:relative;border:1px solid #e2e8f0;background:#fff;border-radius:10px;overflow:hidden}
.mpwa-card-disabled{opacity:.6}
.mpwa-card-disabled .mpwa-edit-btn{pointer-events:none}
.mpwa-table thead th{background:#f8fafc;border-bottom:1px solid #e2e8f0}
.mpwa-table td,.mpwa-table th{vertical-align:middle}
.mpwa-evt-title{font-weight:600}
.mpwa-evt-meta{font-size:12px;color:#64748b;margin-top:2px}
.mpwa-edit-btn{display:inline-flex;align-items:center;gap:6px}
.mpwa-edit-btn.is-disabled{pointer-events:none;opacity:.6}
.mpwa-edit-btn .dashicons{line-height:1;transform:translateY(1px)}
.mpwa-wp-loading-overlay{position:absolute;inset:0;background-color:rgba(255,255,255,.75);display:none;align-items:center;justify-content:center;gap:10px;font-weight:600;z-index:5}
.mpwa-wp-loading-overlay.show{display:flex}
.mpwa-spinner{width:18px;height:18px;border-radius:50%;border:2px solid #cbd5e1;border-top-color:#3b82f6;animation:mpwa-spin 1s linear infinite}
@keyframes mpwa-spin{to{transform:rotate(360deg)}}
.mpwa-alert{border:1px solid transparent;border-radius:10px;padding:12px 14px;margin-bottom:12px;position:relative}
.mpwa-alert .mpwa-clsbutton{position:absolute;right:10px;top:8px;background:transparent;border:0;font-size:18px;cursor:pointer;line-height:1}
.mpwa-alert-danger{background:#fef2f2;border-color:#fecaca}
.mpwa-alert-warning{background:#fffbeb;border-color:#fde68a}
.mpwa-alert-header{font-weight:700;margin-bottom:4px;color:#92400e}
.mpwa-alert-danger .mpwa-alert-header{color:#991b1b}
.mpwa-alert-content{color:#7c2d12}
.mpwa-alert-danger .mpwa-alert-content{color:#7f1d1d}
.mpwa-wp-switch{position:relative;display:inline-block;width:44px;height:24px}
.mpwa-wp-switch input{opacity:0;width:0;height:0}
.mpwa-wp-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#e2e8f0;transition:.2s;border-radius:24px}
.mpwa-wp-slider:before{position:absolute;content:"";height:18px;width:18px;left:3px;bottom:3px;background-color:white;transition:.2s;border-radius:50%}
.mpwa-wp-switch input:checked + .mpwa-wp-slider{background-color:#22c55e}
.mpwa-wp-switch input:checked + .mpwa-wp-slider:before{transform:translateX(20px)}
@media (max-width:900px){
  .mpwa-toolbar{flex-direction:column;align-items:flex-start}
  .mpwa-toolbar-right{width:100%}
  .mpwa-toolbar-right input{flex:1}
}
</style>

<script>
(function(){
  var filter=document.getElementById('mpwa-filter');
  var tbody=document.getElementById('mpwa-table-body');
  var rows=tbody?tbody.querySelectorAll('tr'):[];
  var enableAll=document.getElementById('mpwa-enable-all');
  var disableAll=document.getElementById('mpwa-disable-all');
  var overlay=document.getElementById('mpwa_loading_overlay');
  var closeBtns=document.querySelectorAll('.mpwa-clsbutton');
  var wcReady=document.querySelector('.mpwa-admin-list')?.getAttribute('data-wc-ready')==='1';

  function setOverlay(v){ if(overlay){ overlay.classList.toggle('show', !!v); } }

  function doFilter(q){
    if(!rows) return;
    var qq=(q||'').toLowerCase();
    for(var i=0;i<rows.length;i++){
      var t=rows[i].querySelector('.mpwa-evt-title')?.textContent.toLowerCase()||'';
      var m=rows[i].querySelector('.mpwa-evt-meta')?.textContent.toLowerCase()||'';
      rows[i].style.display=(t.includes(qq)||m.includes(qq))?'table-row':'none';
    }
  }

  function bulkToggle(toState){
    if(!wcReady) return;
    if(!tbody) return;
    setOverlay(true);
    var inputs=tbody.querySelectorAll('input.mpwa-content-status[type="checkbox"]:not([disabled])');
    for(var i=0;i<inputs.length;i++){
      var el=inputs[i];
      if(!!el.checked!==toState){
        el.checked=toState;
        var evt=document.createEvent('HTMLEvents');
        evt.initEvent('change', true, false);
        el.dispatchEvent(evt);
      }
    }
    setTimeout(function(){ setOverlay(false); }, 500);
  }

  if(filter){ filter.addEventListener('input', function(){ doFilter(this.value); }); }
  if(enableAll){ enableAll.addEventListener('click', function(){ bulkToggle(true); }); }
  if(disableAll){ disableAll.addEventListener('click', function(){ bulkToggle(false); }); }
  if(closeBtns&&closeBtns.length){ for(var i=0;i<closeBtns.length;i++){ closeBtns[i].addEventListener('click', function(){ this.parentElement.style.display='none'; }); } }

  if(!wcReady){
    if(tbody){
      tbody.addEventListener('click',function(e){
        var isCheckbox=e.target && e.target.matches('input.mpwa-content-status[type="checkbox"]');
        var isEdit=e.target && (e.target.closest('.mpwa-edit-btn'));
        if(isCheckbox){ e.preventDefault(); e.stopPropagation(); }
        if(isEdit){ e.preventDefault(); }
      }, true);
    }
  }
})();
</script>
