<?php

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

class Sabriel_Module_Dashboard extends Sabriel_Module {

	public function get_id() {
		return 'dashboard';
	}

	public function register_hooks() {

		add_action( 'admin_menu', [ $this, 'add_admin_page' ], 1 );
	}

	const LOGO_ICON_BASE64 = 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ii0xMjYuNCAtMTI2LjQgODA4LjQyMDAwMDAwMDAwMDEgODg0LjgiPgogIDxkZWZzPgogICAgPHN0eWxlPgogICAgICAuY2xzLTEsIC5jbHMtMiB7CiAgICAgICAgZmlsbDogI2ZmZjsKICAgICAgfQoKICAgICAgLmNscy0yIHsKICAgICAgICBmaWxsLXJ1bGU6IGV2ZW5vZGQ7CiAgICAgIH0KICAgIDwvc3R5bGU+CiAgPC9kZWZzPgogIDxwYXRoIGNsYXNzPSJjbHMtMiIgZD0iTTQ4Ni4zNiwyMzUuMjhsLTE1NC45LTk0LjY1Yy0xNy4xMi0xMC40Ni0xNi41Mi0zNS41MywxLjA5LTQ1LjE2TDUwMS4xMiwzLjI1YzE4LjE0LTkuOTIsNDAuMDYsNC4xOCwzOC41NSwyNC44bC0xMy42OCwxODYuODdjLTEuNDIsMTkuNDgtMjIuOTYsMzAuNTUtMzkuNjMsMjAuMzYiLz4KICA8cGF0aCBjbGFzcz0iY2xzLTIiIGQ9Ik03NC41NywzOTYuNzJsMTU0LjksOTQuNjVjMTcuMTIsMTAuNDYsMTYuNTIsMzUuNTMtMS4wOSw0NS4xNmwtMTY4LjU4LDkyLjIyYy0xOC4xNCw5LjkyLTQwLjA2LTQuMTgtMzguNTUtMjQuOGwxMy42OC0xODYuODdjMS40Mi0xOS40OCwyMi45Ni0zMC41NSwzOS42My0yMC4zNiIvPgogIDxwYXRoIGNsYXNzPSJjbHMtMiIgZD0iTTI5My43MywyMjguNDRjL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ni40IiB5PSIzODYuNzIiIHdpZHRoPSIyMy4wMiIgaGVpZ2h0PSI3LjkzIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMjAzLjk4IDQzMi4zOCkgcm90YXRlKC02MC42MSkiLz4KICA8cmVjdCBjbGFzcz0iY2xzLTEiIHg9IjIxNC4wMiIgeT0iMzYxLjkxIiB3aWR0aD0iMjMuMDIiIGhlaWdodD0iNy40NCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTIwMy43OSAzODEuMDMpIHJvdGF0ZSgtNjAuMzkpIi8+Cjwvc3ZnPg==';

	const GIORNI_TRAFFICO = 30;

	public function add_admin_page() {
		add_menu_page(
			__( 'Sabriel AI', 'sabriel-ai' ),
			__( 'Sabriel AI', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai',
			[ $this, 'render_admin_page' ],
			'data:image/svg+xml;base64,' . self::LOGO_ICON_BASE64,
			30
		);

		add_submenu_page(
			'sabriel-ai',
			__( 'Dashboard', 'sabriel-ai' ),
			__( 'Dashboard', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai',
			[ $this, 'render_admin_page' ]
		);
	}

	public function render_admin_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Access denied', 'sabriel-ai' ) );
		}

		$business_name = Sabriel_Module_Settings::get( 'business_name' );
		$sab_traffico  = Sabriel_Module_Traffico::statistiche( self::GIORNI_TRAFFICO );
		?>
<div class="wrap">

<style>
.sab-card{background:#fff;border:1px solid #e5e5e5;border-radius:10px;padding:16px 18px;margin-bottom:10px;display:flex;align-items:flex-start;gap:14px;box-shadow:0 1px 4px rgba(0,0,0,.04)}
.sab-btn{padding:8px 0;border-radius:7px;border:none;cursor:pointer;font-size:13px;font-weight:700;font-family:inherit;width:100%;text-align:center}
.sab-empty{text-align:center;padding:40px;color:#aaa;font-size:14px}
@keyframes sabFadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
.sab-fadeup{opacity:0;animation:sabFadeUp .55s cubic-bezier(.16,1,.3,1) forwards}
</style>

<h1 style="display:flex;align-items:center;gap:8px">&#128197; Dashboard <?php echo esc_html( $business_name ); ?></h1>

<div class="sab-fadeup" style="font-weight:700;font-size:16px;margin:26px 0 12px;animation-delay:60ms">&#127760; <?php esc_html_e( 'General site analytics', 'sabriel-ai' ); ?></div>
<?php if ( ! $sab_traffico['ha_dati'] ) : ?>
  <div class="sab-empty"><?php esc_html_e( 'No data yet: as soon as the site gets its first visits (even just your own, by opening any page to try it), this section fills in on its own.', 'sabriel-ai' ); ?></div>
<?php else : ?>
<div style="display:flex;gap:14px;flex-wrap:wrap;margin-bottom:18px">
  <div class="sab-card sab-fadeup" style="flex-direction:column;align-items:flex-start;gap:4px;flex:1;min-width:150px;animation-delay:90ms">
    <div style="font-size:11.5px;color:#888;font-weight:700;text-transform:uppercase;letter-spacing:.04em"><?php esc_html_e( 'Total visits', 'sabriel-ai' ); ?></div>
    <div style="font-size:28px;font-weight:800;color:#111"><span class="sab-countup" data-target="<?php echo (int) $sab_traffico['visite_totali']; ?>" data-decimals="0">0</span></div>
  </div>
  <div class="sab-card sab-fadeup" style="flex-direction:column;align-items:flex-start;gap:4px;flex:1;min-width:150px;animation-delay:120ms">
    <div style="font-size:11.5px;color:#888;font-weight:700;text-transform:uppercase;letter-spacing:.04em"><?php esc_html_e( 'Unique visitors', 'sabriel-ai' ); ?></div>
    <div style="font-size:28px;font-weight:800;color:#111"><span class="sab-countup" data-target="<?php echo (int) $sab_traffico['visitatori_unici']; ?>" data-decimals="0">0</span><?php echo ! empty( $sab_traffico['visitatori_parziale'] ) ? '+' : ''; ?></div>
  </div>
  <div class="sab-card sab-fadeup" style="flex-direction:column;align-items:flex-start;gap:4px;flex:1;min-width:150px;animation-delay:150ms">
    <div style="font-size:11.5px;color:#888;font-weight:700;text-transform:uppercase;letter-spacing:.04em"><?php esc_html_e( 'Chats opened', 'sabriel-ai' ); ?></div>
    <div style="font-size:28px;font-weight:800;color:#111"><span class="sab-countup" data-target="<?php echo (int) $sab_traffico['chat_aperte']; ?>" data-decimals="0">0</span></div>
  </div>
  <div class="sab-card sab-fadeup" style="flex-direction:column;align-items:flex-start;gap:4px;flex:1;min-width:150px;animation-delay:180ms">
    <div style="font-size:11.5px;color:#888;font-weight:700;text-transform:uppercase;letter-spacing:.04em"><?php esc_html_e( 'Average visits/day', 'sabriel-ai' ); ?></div>
    <div style="font-size:28px;font-weight:800;color:#111"><span class="sab-countup" data-target="<?php echo esc_attr( round( $sab_traffico['visite_totali'] / max( 1, count( $sab_traffico['per_giorno'] ) ), 1 ) ); ?>" data-decimals="1">0</span></div>
  </div>
  <div class="sab-card sab-fadeup" style="flex-direction:column;align-items:flex-start;gap:4px;flex:1;min-width:150px;animation-delay:210ms">
    <div style="font-size:11.5px;color:#888;font-weight:700;text-transform:uppercase;letter-spacing:.04em">&#128274; <?php esc_html_e( 'Security blocks', 'sabriel-ai' ); ?></div>
    <div style="font-size:28px;font-weight:800;color:<?php echo $sab_traffico['blocchi_sicurezza'] > 0 ? '#b45309' : '#111'; ?>"><span class="sab-countup" data-target="<?php echo (int) $sab_traffico['blocchi_sicurezza']; ?>" data-decimals="0">0</span></div>
  </div>
</div>
<?php if ( ! empty( $sab_traffico['pagine_top'] ) ) : $sab_max_pagina = max( $sab_traffico['pagine_top'] ); ?>
<div class="sab-card sab-fadeup" style="flex-direction:column;align-items:stretch;gap:12px;max-width:1150px;margin-bottom:22px;animation-delay:240ms;padding:22px">
  <div style="font-weight:700;font-size:15px">&#128200; <?php esc_html_e( 'Most visited pages', 'sabriel-ai' ); ?></div>
  <?php foreach ( $sab_traffico['pagine_top'] as $sab_pagina => $sab_n ) : $sab_pct = $sab_max_pagina ? round( $sab_n / $sab_max_pagina * 100 ) : 0; $sab_pagina_etichetta = ( '/' === $sab_pagina ) ? __( 'Homepage (/)', 'sabriel-ai' ) : $sab_pagina; ?>
  <div style="display:flex;align-items:center;gap:12px;font-size:13px">
    <div style="width:180px;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:monospace;font-size:12px" title="<?php echo esc_attr( $sab_pagina ); ?>"><?php echo esc_html( $sab_pagina_etichetta ); ?></div>
    <div style="flex:1;background:#f0f0f0;border-radius:5px;height:16px;overflow:hidden">
      <div class="sab-bar-fill" data-width="<?php echo esc_attr( $sab_pct ); ?>" style="background:linear-gradient(90deg,#1461CC,#4b8ee8);height:100%;width:0;border-radius:5px;transition:width 1.1s cubic-bezier(.16,1,.3,1)"></div>
    </div>
    <div style="width:38px;text-align:right;color:#888;font-weight:700"><?php echo (int) $sab_n; ?></div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>
<p style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a5f;font-size:11.5px;padding:9px 12px;border-radius:8px;margin:-4px 0 22px;max-width:1150px"><?php esc_html_e( 'Anonymous counting, without cookies: each visitor is recognised only for that same day, never tracked over time. "Security blocks" are attempts stopped automatically because they came too often (see Settings → Limits): a few are normal, many at once can mean an abuse attempt. Data kept for 90 days.', 'sabriel-ai' ); ?></p>
<?php endif; ?>

<div class="sab-fadeup" style="font-weight:700;font-size:16px;margin:30px 0 12px;animation-delay:270ms">&#128295; <?php esc_html_e( 'Tools', 'sabriel-ai' ); ?></div>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:14px;max-width:1100px">
  <div class="sab-card sab-fadeup" style="flex-direction:column;align-items:flex-start;gap:10px;animation-delay:300ms">
    <div style="font-weight:700;font-size:14.5px">&#128275; <?php esc_html_e( 'Unlock chat limit', 'sabriel-ai' ); ?></div>
    <div style="font-size:12.5px;color:#777;line-height:1.5"><?php echo esc_html( sprintf( /* translators: %d: how many messages per day the current configuration allows */ _n( 'Removes the block on the %d daily message for anyone who hit the limit while you were testing.', 'Removes the block on the %d daily messages for anyone who hit the limit while you were testing.', Sabriel_Module_Chat::limite_configurato(), 'sabriel-ai' ), Sabriel_Module_Chat::limite_configurato() ) ); ?></div>
    <a href="#" onclick="sabUnlockLimits();return false;" class="sab-btn" style="background:#f5f5f5;color:#333;text-decoration:none;display:block;width:100%;box-sizing:border-box;text-align:center;margin-top:auto"><?php esc_html_e( 'Unlock', 'sabriel-ai' ); ?></a>
  </div>
</div>

<script>
var SABBASE = <?php echo wp_json_encode( esc_url_raw( rest_url( 'sabriel/v1' ) ) ); ?>;
var SABNONCE = <?php echo wp_json_encode( wp_create_nonce( 'wp_rest' ) ); ?>;
var SAB_DEC = <?php echo wp_json_encode( $GLOBALS['wp_locale']->number_format['decimal_point'] ); ?>;
var SAB_ERRORE = <?php echo wp_json_encode( __( 'Error: ', 'sabriel-ai' ) ); ?>;
(function(){
  function animaIngresso(){
    document.querySelectorAll('.sab-bar-fill').forEach(function(b){ b.style.width = (b.getAttribute('data-width')||0) + '%'; });
    document.querySelectorAll('.sab-countup').forEach(function(el, i){
      var target = parseFloat(el.getAttribute('data-target')) || 0;
      var decimali = parseInt(el.getAttribute('data-decimals')||'0', 10);
      var t0 = null, durata = 900;
      function passo(ts){
        if(!t0) t0 = ts;
        var p = Math.min((ts - t0) / durata, 1);
        var eas = 1 - Math.pow(1 - p, 3);
        el.textContent = (eas * target).toFixed(decimali).replace('.', SAB_DEC);
        if(p < 1) requestAnimationFrame(passo);
      }
      setTimeout(function(){ requestAnimationFrame(passo); }, i * 55);
    });
  }
  requestAnimationFrame(function(){ requestAnimationFrame(animaIngresso); });
})();

function sabUnlockLimits(){
  if(!confirm(<?php echo wp_json_encode( __( 'Unlock the chat message limit for everyone? Only useful for testing, real customers aren\'t affected unless they\'re blocked.', 'sabriel-ai' ) ); ?>))return;
  fetch(SABBASE+'/chat/unlock',{method:'POST',credentials:'same-origin',headers:{'X-WP-Nonce':SABNONCE}})
    .then(function(r){return r.json();})
    .then(function(d){
      /* ⚠ Non basta che il server abbia risposto: se la rotta non esiste piu' o il
         gettone e' scaduto, WordPress risponde comunque un JSON, `d.deleted` e'
         indefinito e il messaggio diceva lo stesso «sbloccati 0 limiti» come se
         l'operazione fosse riuscita. Qui si guarda se la risposta ha davvero la
         forma attesa, e se non ce l'ha si dice che NON e' riuscita. */
      if(!d || typeof d!=='object' || typeof d.deleted==='undefined'){
        alert(SAB_ERRORE+((d&&(d.message||d.code))||'?'));
        return;
      }
      try{localStorage.removeItem('sab_blk_v1');}catch(e){}
      alert(<?php echo wp_json_encode( /* translators: %d: how many chat limits were unlocked */ __( 'Unlocked %d chat limits on the server. I\'ve also cleared the memory of the browser you\'re using now, so if you ran your tests from here the block disappears straight away. If you tested from another phone or browser, open the chat there and reload the page.', 'sabriel-ai' ) ); ?>.replace('%d',(d.deleted||0)));
    }).catch(function(e){alert(SAB_ERRORE+e.message);});
}
</script>
</div>
		<?php
	}
}
