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

final class SBC_Agent_Desk {
    public function __construct() {
        add_filter('pre_do_shortcode_tag', [$this,'shortcode_override'], 10, 4);
        add_action('wp_ajax_sbc_agent_desk', [$this,'ajax']);
    }

    public function shortcode_override($return, $tag, $attr, $m) {
        if ($tag !== 'support_bonus_agent_portal') return $return;
        if (!is_user_logged_in()) return $this->login_screen();
        if (!sbc_ops()->is_registered_staff(get_current_user_id())) return '<div class="sbc-desk-denied">This account is not registered as an active support agent.</div>';
        $target=admin_url('admin.php?page=sbc-inbox');
        if(!headers_sent()){wp_safe_redirect($target);exit;}
        return '<script>window.location.href='.wp_json_encode($target).';</script><p><a href="'.esc_url($target).'">Open BluPass</a></p>';
    }

    private function login_screen() {
        $page_id = get_queried_object_id();
        $return_url = $page_id ? get_permalink($page_id) : home_url('/');
        $primary=sanitize_hex_color(get_option('sbc_primary_color','#0867ed'))?:'#0867ed';
        $secondary=sanitize_hex_color(get_option('sbc_secondary_color','#4f46e5'))?:'#4f46e5';
        ob_start(); ?>
        <div class="sbc-desk-login"><style>.sbc-desk-login{--blue:<?php echo esc_attr($primary);?>;--secondary:<?php echo esc_attr($secondary);?>;max-width:460px;margin:50px auto;padding:32px;border-radius:20px;background:#fff;box-shadow:0 18px 60px #1637611c;font:14px system-ui;color:#13233f}.sbc-desk-login-logo{display:block;width:min(280px,80%);height:auto;margin:0 auto 18px}.sbc-desk-login h2{font-size:26px;margin:0 0 6px;color:var(--blue)}.sbc-desk-login p{color:#667085}.sbc-desk-login input{width:100%;box-sizing:border-box;padding:12px;border:1px solid #d6dfeb;border-radius:10px}.sbc-desk-login input:focus{border-color:var(--blue);box-shadow:0 0 0 3px color-mix(in srgb,var(--blue) 16%,transparent);outline:none}.sbc-desk-login .button-primary{width:100%;padding:12px;background:linear-gradient(135deg,var(--blue),var(--secondary));color:#fff;border:0;border-radius:10px;font-weight:700}</style><img class="sbc-desk-login-logo" src="<?php echo esc_url(SBC_PLUGIN_URL . 'assets/images/blupass-logo.png');?>" alt="BluPass"><h2>BluPass Agent Login</h2><p>Sign in with an administrator account or an active agent account registered in Agents &amp; Departments.</p>
        <?php wp_login_form(['redirect'=>esc_url_raw($return_url),'label_username'=>'WordPress username or email','label_password'=>'Password','label_log_in'=>'Sign in to BluPass','remember'=>true]); ?>
        </div><?php return ob_get_clean();
    }

    public function desk_screen() {
        wp_enqueue_script('jquery'); $nonce=wp_create_nonce('sbc_agent_desk'); $staff=sbc_ops()->staff_identity();$primary=sanitize_hex_color(get_option('sbc_primary_color','#0967e8'))?:'#0967e8';$secondary=sanitize_hex_color(get_option('sbc_secondary_color','#4f46e5'))?:'#4f46e5';$accent=sanitize_hex_color(get_option('sbc_accent_color','#14b8a6'))?:'#14b8a6';
        ob_start(); ?>
        <div id="sbc-desk" data-role="<?php echo esc_attr($staff['role']); ?>">
        <style>
        body.sbc-agent-desk-page #secondary,body.sbc-agent-desk-page .widget-area,body.sbc-agent-desk-page aside.sidebar,body.sbc-agent-desk-page .site-sidebar,body.sbc-agent-desk-page .entry-header{display:none!important}
        body.sbc-agent-desk-page #primary,body.sbc-agent-desk-page .content-area,body.sbc-agent-desk-page main.site-main,body.sbc-agent-desk-page .site-main,body.sbc-agent-desk-page .entry-content,body.sbc-agent-desk-page .wp-block-post-content{width:100%!important;max-width:none!important;float:none!important;box-sizing:border-box}
        body.sbc-agent-desk-page .site-content,body.sbc-agent-desk-page .content-wrapper,body.sbc-agent-desk-page .container{max-width:none!important;width:100%!important;box-sizing:border-box}
        body.sbc-agent-desk-page .site-content,body.sbc-agent-desk-page #content,body.sbc-agent-desk-page #primary,body.sbc-agent-desk-page article,body.sbc-agent-desk-page .entry-content{margin-left:0!important;margin-right:0!important;padding-left:0!important;padding-right:0!important}
        #sbc-desk{--blue:<?php echo esc_attr($primary);?>;--secondary:<?php echo esc_attr($secondary);?>;--accent:<?php echo esc_attr($accent);?>;--ink:#13233f;--muted:#667085;--line:#e2e8f0;font:14px system-ui;color:var(--ink);background:#f6f8fc;border:1px solid var(--line);border-radius:14px;overflow:hidden;min-height:calc(100vh - 92px);box-shadow:0 12px 42px #1b3c6814;width:100%;max-width:100%;margin:0;position:relative;box-sizing:border-box}
        .sd-head{height:68px;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:center;padding:0 20px;gap:12px}.sd-logo{width:38px;height:38px;border-radius:10px;background:#fff;display:grid;place-items:center;overflow:hidden}.sd-logo img{width:36px;height:36px;object-fit:contain}.sd-title{font-size:18px;font-weight:800;flex:1}.sd-live{color:#079455;background:#ecfdf3;border-radius:20px;padding:7px 11px}.sd-user{text-align:right}.sd-user small{display:block;color:var(--muted)}
        .sd-tools{display:flex;gap:10px;padding:12px;background:#fff;border-bottom:1px solid var(--line);min-width:0}.sd-tools input,.sd-tools select{padding:10px 12px;border:1px solid var(--line);border-radius:9px;background:#fff;min-width:0}.sd-tools input{flex:1}.sd-grid{display:grid;grid-template-columns:minmax(235px,26%) minmax(360px,1fr) minmax(235px,25%);min-height:calc(100vh - 220px);width:100%}.sd-left,.sd-right{background:#fff;padding:14px;border-right:1px solid var(--line);overflow:auto;min-width:0}.sd-right{border-right:0;border-left:1px solid var(--line)}.sd-center{padding:14px;display:flex;flex-direction:column;min-width:0;overflow:hidden}.sd-tabs{display:flex;gap:18px;border-bottom:1px solid var(--line);padding:4px 4px 10px}.sd-tabs button{border:0;background:none;color:var(--muted);font-weight:700}.sd-tabs button.active{color:var(--blue)}
        .sd-adminlinks{display:flex;gap:7px;margin-left:auto;flex-wrap:wrap}.sd-adminlinks a{display:inline-block;padding:8px 10px;border-radius:8px;background:color-mix(in srgb,var(--blue) 10%,white);color:var(--blue);font-weight:700;text-decoration:none}
        .sd-chat-card{display:block;width:100%;text-align:left;border:1px solid var(--line);border-radius:12px;background:#fff;padding:12px;margin:8px 0;cursor:pointer}.sd-chat-card.active{border-color:var(--blue);background:color-mix(in srgb,var(--blue) 6%,white)}.sd-chat-card strong{display:block;font-size:14px}.sd-chat-card small{display:block;color:var(--muted);margin-top:4px}.sd-badge{display:inline-block;padding:3px 7px;border-radius:12px;background:#fff2db;color:#a84b00;font-size:10px;font-weight:800}.sd-badge.closed{background:#eafaf1;color:#087443}.sd-messages{flex:1;overflow:auto;min-height:420px;padding:12px}.sd-msg{max-width:70%;padding:10px 12px;border-radius:13px;background:#fff;margin:8px 0;box-shadow:0 1px 3px #0000000b}.sd-msg.agent{margin-left:auto;background:linear-gradient(135deg,color-mix(in srgb,var(--blue) 15%,white),color-mix(in srgb,var(--secondary) 10%,white))}.sd-msg.system{max-width:90%;margin:8px auto;background:#fff7e6;color:#7a4700}.sd-msg.warning{max-width:94%;margin:10px auto;background:#fff0f0;color:#941b1b;border:1px solid #f3a1a1;border-left:5px solid #dc2626;text-align:center;font-weight:700}.sd-msg small{display:block;color:var(--muted);font-size:10px;margin-top:5px}.sd-compose{background:#fff;border:1px solid var(--line);border-radius:13px;padding:10px}.sd-compose textarea{width:100%;box-sizing:border-box;border:0;min-height:76px;resize:vertical}.sd-actions{display:flex;gap:8px;align-items:center}.sd-actions select{max-width:180px}.sd-btn{border:0;border-radius:9px;padding:9px 13px;background:color-mix(in srgb,var(--blue) 7%,white);color:var(--ink);font-weight:700;cursor:pointer}.sd-btn.primary{background:linear-gradient(135deg,var(--blue),var(--secondary));color:#fff;margin-left:auto}.sd-panel{border:1px solid var(--line);border-radius:12px;padding:12px;margin-bottom:12px}.sd-panel h3{font-size:13px;margin:0 0 10px}.sd-kv{margin:8px 0}.sd-kv small{display:block;color:var(--muted);font-size:10px;margin-top:5px}.sd-msg.warning small{display:none}.sd-compose{background:#fff;border:1px solid var(--line);border-radius:13px;padding:10px}.sd-kv{margin:8px 0}.sd-alert{padding:10px;border-radius:9px;background:#fff4e5;color:#9a4b00}.sd-empty{display:grid;place-items:center;height:100%;color:var(--muted)}
        @media(max-width:1220px){.sd-grid{grid-template-columns:minmax(220px,28%) minmax(340px,1fr)}.sd-right{display:none}}
        @media(max-width:980px){#sbc-desk{width:calc(100vw - 20px)}.sd-grid{grid-template-columns:280px minmax(0,1fr)}.sd-right{display:none}.sd-head{padding:0 14px}}
        @media(max-width:720px){body.sbc-agent-desk-page .entry-content{padding-left:8px!important;padding-right:8px!important}#sbc-desk{width:100%;min-height:680px;margin:0;border-radius:12px}.sd-head{height:auto;min-height:70px;display:grid;grid-template-columns:38px minmax(0,1fr) auto;padding:10px 12px}.sd-title{font-size:16px;line-height:1.2}.sd-live{font-size:0;padding:7px}.sd-live:first-letter{font-size:12px}.sd-user{grid-column:2/4;text-align:left;font-size:12px}.sd-user small{display:inline;margin-left:5px}.sd-tools{display:grid;grid-template-columns:1fr auto;padding:10px}.sd-tools input{grid-column:1/3;min-width:0;width:100%;max-width:none}.sd-tools select{min-width:0;width:100%}.sd-grid{display:block}.sd-left{max-height:300px}.sd-center{min-height:600px;padding:10px}.sd-messages{min-height:380px;padding:6px}.sd-actions{flex-wrap:wrap}.sd-actions select{flex:1;max-width:none;min-width:130px}.sd-btn.primary{width:100%;margin-left:0}.sd-right{display:none}}
        </style>
        <header class="sd-head"><span class="sd-logo"><img src="<?php echo esc_url(SBC_PLUGIN_URL . 'assets/images/blupass-icon.png');?>" alt=""></span><span class="sd-title">BluPass Inbox</span><span class="sd-live">● Live refresh ON</span><span class="sd-user"><?php echo esc_html($staff['display_name']); ?><small><?php echo esc_html(ucfirst($staff['role']).($staff['department']?' · '.$staff['department']:'')); ?></small></span></header>
        <div class="sd-tools"><input id="sd-search" placeholder="Search customers, email, service…"><select id="sd-status"><option value="all">All statuses</option><option value="waiting">Waiting</option><option value="active">Active</option><option value="closed">Closed</option></select><button class="sd-btn" id="sd-refresh">↻ Refresh</button><?php if(!empty($staff['can_manage'])):?><span class="sd-adminlinks"><a href="<?php echo esc_url(admin_url('admin.php?page=sbc-agents'));?>">Agents</a><a href="<?php echo esc_url(admin_url('admin.php?page=sbc-canned-replies'));?>">Canned Replies</a><a href="<?php echo esc_url(admin_url('admin.php?page=sbc-token-wallet'));?>">Token Buckets</a></span><?php endif;?></div>
        <div class="sd-grid"><aside class="sd-left"><h3>Customers <span id="sd-count"></span></h3><div id="sd-list"></div></aside><main class="sd-center"><div id="sd-main" class="sd-empty">Select a customer to begin.</div></main><aside class="sd-right"><h3>Customer Details</h3><div id="sd-details"></div></aside></div></div>
        <script>(function($){document.body.classList.add('sbc-agent-desk-page');const url=<?php echo wp_json_encode(admin_url('admin-ajax.php'));?>,nonce=<?php echo wp_json_encode($nonce);?>;let current=0,busy=false;const esc=v=>$('<div>').text(v==null?'':v).html();function api(op,data){return $.post(url,Object.assign({action:'sbc_agent_desk',nonce,op},data||{}));}function load(){if(busy)return;api('inbox',{search:$('#sd-search').val(),status:$('#sd-status').val()}).done(r=>{if(!r.success)return;$('#sd-count').text(r.data.chats.length);$('#sd-list').html(r.data.chats.map(c=>`<button class="sd-chat-card ${+c.id===current?'active':''}" data-id="${c.id}"><strong>${esc(c.full_name||c.customer_email)} <span class="sd-badge ${c.status==='closed'?'closed':''}">${esc(c.status)}</span>${c.transferred_to_me?'<span class="sd-badge"> Assigned to you</span>':''}</strong><small>${esc(c.customer_email)}</small><small>${esc(c.service_type)} · ${c.chats_count||1} chat(s) · Latest #${c.id}${c.agent_label?' · '+esc(c.agent_label):''}</small></button>`).join(''));});}function open(id){current=+id;busy=true;api('open',{chat_id:current}).done(r=>{busy=false;if(!r.success){alert(r.data.message);load();return;}const c=r.data.chat,can=r.data.canned||[],agents=r.data.agents||[],closed=c.status==='closed';$('#sd-main').removeClass('sd-empty').html(`<div class="sd-tabs"><button class="active">${closed?'Closed chat':'Reply'}</button>${closed?'':'<button id="sd-close">Close chat</button>'}</div><div class="sd-messages">${c.messages.map(m=>`<div class="sd-msg ${esc(m.sender_type)}">${m.sender_type==='agent'&&m.sender_label?'<strong>'+esc(m.sender_label)+(m.sender_department?' · '+esc(m.sender_department):'')+'</strong><br>':''}${esc(m.message)}<small>${esc(m.sender_type)} · ${esc(m.created_at)}</small></div>`).join('')}</div>${closed?'<div class="sd-alert">This chat is closed. Replies and transfers are disabled.</div>':`<div class="sd-compose"><textarea id="sd-reply" placeholder="Type your reply here…"></textarea><div class="sd-actions"><select id="sd-canned"><option value="">Canned reply</option>${can.map(x=>`<option value="${esc(x.message)}">${esc(x.title)}</option>`).join('')}</select><select id="sd-transfer"><option value="">Transfer chat</option>${agents.map(a=>`<option value="${a.user_id}">${esc(a.tag_name)} · ${esc(a.department_name||'No department')}</option>`).join('')}</select><button class="sd-btn primary" id="sd-send">Send Reply</button></div></div>`}`);let tx='';try{const o=JSON.parse(c.transaction_snapshot||'{}');tx='<pre style="white-space:pre-wrap;font-size:11px">'+esc(JSON.stringify(o,null,2))+'</pre>'}catch(e){}$('#sd-details').html(`<div class="sd-panel"><div class="sd-kv"><small>Name</small>${esc(c.full_name)}</div><div class="sd-kv"><small>Email</small>${esc(c.customer_email)}</div><div class="sd-kv"><small>Service</small>${esc(c.service_type)}</div></div>${c.pending_withdrawal?'<div class="sd-alert">This customer has a pending withdrawal request.</div>':''}<div class="sd-panel"><h3>Transaction / Provider Response</h3>${tx||'No transaction attached.'}</div><div class="sd-panel"><h3>Customer Chat History</h3>${(c.history||[]).map(h=>`<button class="sd-chat-card" data-history="${h.id}">Chat #${h.id} · ${esc(h.status)}<small>${esc(h.updated_at)}</small></button>`).join('')}</div>`);load();}).fail(()=>{busy=false});}function isDrafting(){const reply=document.getElementById('sd-reply');return !!reply&&(document.activeElement===reply||reply.value.length>0);}$('#sd-list').on('click','button',function(){open(this.dataset.id)});$('#sbc-desk').on('click','[data-history]',function(){open(this.dataset.history)});$('#sbc-desk').on('change','#sd-canned',function(){if(this.value)$('#sd-reply').val(this.value).trigger('focus')});$('#sbc-desk').on('change','#sd-transfer',function(){if(this.value&&confirm('Transfer this chat?'))api('transfer',{chat_id:current,target_user_id:this.value}).done(()=>{current=0;load();$('#sd-main').addClass('sd-empty').html('Conversation transferred.')})});$('#sbc-desk').on('click','#sd-send',()=>{const message=$('#sd-reply').val();if(message)api('reply',{chat_id:current,message}).done(r=>{if(!r.success)alert(r.data.message);open(current)})});$('#sbc-desk').on('click','#sd-close',()=>api('close',{chat_id:current}).done(()=>open(current)));$('#sd-search').on('input',load);$('#sd-status').on('change',load);$('#sd-refresh').on('click',load);setInterval(()=>{load();if(current&&!isDrafting())open(current)},3000);load();})(jQuery);</script>
        <?php return ob_get_clean();
    }

    public function ajax() {
        check_ajax_referer('sbc_agent_desk','nonce');
        if(!is_user_logged_in()||!sbc_ops()->is_registered_staff(get_current_user_id()))wp_send_json_error(['message'=>'Your support access is not active.'],403);
        global $wpdb;$chats=$wpdb->prefix.'sbc_chats';$msgs=$wpdb->prefix.'sbc_messages';$withdraw=$wpdb->prefix.'sbc_withdrawal_requests';$op=sanitize_key($_POST['op']??'');$uid=get_current_user_id();
        if($op==='inbox'){$search=sanitize_text_field($_POST['search']??'');$status=sanitize_key($_POST['status']??'all');$like='%'.$wpdb->esc_like($search).'%';$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$chats} WHERE (%s='' OR full_name LIKE %s OR customer_email LIKE %s OR service_type LIKE %s) AND (%s='all' OR status=%s) ORDER BY updated_at DESC,id DESC LIMIT 300",$search,$like,$like,$like,$status,$status));$out=[];$seen=[];foreach($rows as $c)if(sbc_ops()->can_access_chat($c,$uid)&&empty($seen[$c->customer_key])){$seen[$c->customer_key]=1;$c->agent_label=$c->assigned_agent_id?(sbc_ops()->staff_identity((int)$c->assigned_agent_id)['display_name']??'Assigned'):'';$c->transferred_to_me=(int)$c->assigned_agent_id===$uid;$c->chats_count=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$chats} WHERE customer_key=%s",$c->customer_key));$out[]=$c;}wp_send_json_success(['chats'=>$out]);}
        $id=absint($_POST['chat_id']??0);$chat=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$chats} WHERE id=%d",$id));if(!$chat||!sbc_ops()->can_access_chat($chat,$uid))wp_send_json_error(['message'=>'Conversation unavailable.'],404);
        if($op==='open'){sbc_ops()->check_inactivity($id);$chat=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$chats} WHERE id=%d",$id));if($chat->status!=='closed'){$claim=sbc_ops()->claim_chat($id,$uid);if(is_wp_error($claim))wp_send_json_error(['message'=>$claim->get_error_message()],409);$wpdb->update($chats,['assignment_heartbeat_at'=>current_time('mysql')],['id'=>$id]);}$chat=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$chats} WHERE id=%d",$id));$chat->messages=$wpdb->get_results($wpdb->prepare("SELECT id,sender_type,sender_label,sender_department,message,created_at FROM {$msgs} WHERE chat_id=%d ORDER BY id",$id));$chat->history=$wpdb->get_results($wpdb->prepare("SELECT id,status,service_type,updated_at FROM {$chats} WHERE customer_key=%s ORDER BY updated_at DESC,id DESC LIMIT 3",$chat->customer_key));$chat->pending_withdrawal=$chat->user_id?(bool)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$withdraw} WHERE user_id=%d AND status='pending'",$chat->user_id)):false;wp_send_json_success(['chat'=>$chat,'canned'=>sbc_ops()->visible_canned_for_mobile($uid),'agents'=>sbc_ops()->agent_choices()]);}
        if($op==='reply'){if($chat->status==='closed')wp_send_json_error(['message'=>'This chat is closed and cannot receive replies.'],409);$claim=sbc_ops()->claim_chat($id,$uid);if(is_wp_error($claim))wp_send_json_error(['message'=>$claim->get_error_message()],409);$message=sanitize_textarea_field($_POST['message']??'');if(!$message)wp_send_json_error(['message'=>'Reply required.']);$identity=sbc_ops()->staff_identity($uid);$now=current_time('mysql');$wpdb->insert($msgs,['chat_id'=>$id,'sender_type'=>'agent','sender_label'=>$identity['display_name'],'sender_department'=>$identity['department'],'message'=>$message,'created_at'=>$now]);$wpdb->update($chats,['status'=>'active','agent_replied_at'=>$chat->agent_replied_at?:$now,'last_human_activity_at'=>$now,'inactivity_warned_at'=>null,'assignment_heartbeat_at'=>$now,'updated_at'=>$now],['id'=>$id]);wp_send_json_success();}
        if($op==='transfer'){if($chat->status==='closed')wp_send_json_error(['message'=>'A closed chat cannot be transferred.'],409);$r=sbc_ops()->transfer_chat($id,absint($_POST['target_user_id']??0),0,$uid);if(is_wp_error($r))wp_send_json_error(['message'=>$r->get_error_message()],409);wp_send_json_success();}
        if($op==='close'){$now=current_time('mysql');$wpdb->update($chats,['status'=>'closed','closed_at'=>$now,'assignment_heartbeat_at'=>null,'updated_at'=>$now],['id'=>$id]);wp_send_json_success();}
        wp_send_json_error(['message'=>'Invalid action.'],400);
    }
}

$GLOBALS['sbc_agent_desk']=new SBC_Agent_Desk();
