<?php
/**
 * Plugin Name: Sincotechs Cam Platform Final
 * Description: Final version – auto pages + tokens + tips + per-minute billing + rooms. © Sincotechs
 * Version: 1.0.0
 * Author: Sincotechs
 */

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

class SCP_Cam_Platform_Final {

    public function __construct() {
        add_shortcode('sincotechs_cam_room', [$this,'room']);
        add_shortcode('sincotechs_dashboard', [$this,'dashboard']);
        add_shortcode('sincotechs_buy_tokens', [$this,'buytokens']);

        add_action('wp_enqueue_scripts', [$this,'assets']);
        add_action('rest_api_init',        [$this,'rest']);
        add_action('init',                 [$this,'roles']);
    }

    public static function activate() {
        // Create 3 pages if they don't exist yet
        $pages = [
            'Sincotechs Live Room'   => '[sincotechs_cam_room]',
            'Sincotechs Dashboard'   => '[sincotechs_dashboard]',
            'Sincotechs Buy Tokens'  => '[sincotechs_buy_tokens]',
        ];

        foreach ($pages as $title => $shortcode) {
            $existing = get_page_by_title($title);
            if ($existing) continue;

            wp_insert_post([
                'post_title'   => $title,
                'post_content' => $shortcode,
                'post_status'  => 'publish',
                'post_type'    => 'page'
            ]);
        }
    }

    public function roles() {
        add_role('scp_model','Sincotechs Model',['read'=>true]);
        add_role('scp_viewer','Sincotechs Viewer',['read'=>true]);
        add_role('scp_admin','Sincotechs Admin',['read'=>true,'edit_users'=>true]);
    }

    public function assets() {
        $u = plugin_dir_url(__FILE__);
        wp_enqueue_style('scp-final-style', $u.'assets/css/cam-style.css');
        wp_enqueue_script('scp-final-app',  $u.'assets/js/cam-app.js', ['jquery'], false, true);

        wp_localize_script('scp-final-app','SCP_DATA',[
            'user_id' => get_current_user_id(),
            'rest'    => site_url('/wp-json/sincotechs/v1/'),
        ]);
    }

    public function room() {
        ob_start();
        include plugin_dir_path(__FILE__).'templates/room.php';
        return ob_get_clean();
    }

    public function dashboard() {
        ob_start();
        include plugin_dir_path(__FILE__).'templates/dashboard.php';
        return ob_get_clean();
    }

    public function buytokens() {
        ob_start();
        include plugin_dir_path(__FILE__).'templates/buytokens.php';
        return ob_get_clean();
    }

    public function rest() {

        // Token balance
        register_rest_route('sincotechs/v1','/tokens/get',[
            'methods'  => 'GET',
            'callback' => function() {
                $uid = get_current_user_id();
                $b   = intval(get_user_meta($uid,'scp_tokens',true));
                return ['balance'=>$b];
            }
        ]);

        register_rest_route('sincotechs/v1','/tokens/add',[
            'methods'  => 'POST',
            'callback' => function(WP_REST_Request $r) {
                $uid = get_current_user_id();
                $amt = intval($r['amount']);
                if ($amt <= 0) return new WP_Error('bad_amount','Invalid amount');

                $b   = intval(get_user_meta($uid,'scp_tokens',true));
                $new = $b + $amt;
                update_user_meta($uid,'scp_tokens',$new);

                return ['balance'=>$new];
            }
        ]);

        // Rooms
        register_rest_route('sincotechs/v1','/rooms',[
            'methods'  => 'GET',
            'callback' => function() {
                return [
                    ['id'=>1,'name'=>'Public Show','type'=>'public','rate_per_min'=>0,'vip_only'=>false],
                    ['id'=>2,'name'=>'VIP Lounge','type'=>'vip','rate_per_min'=>5,'vip_only'=>true],
                    ['id'=>3,'name'=>'Private Session','type'=>'private','rate_per_min'=>20,'vip_only'=>false],
                ];
            }
        ]);

        // Tips
        register_rest_route('sincotechs/v1','/billing/tip',[
            'methods'  => 'POST',
            'callback' => function(WP_REST_Request $r) {
                $from   = get_current_user_id();
                $to     = intval($r['to']);
                $amount = intval($r['amount']);
                if ($amount <= 0) return new WP_Error('bad_amount','Invalid tip amount');

                $bal_from = intval(get_user_meta($from,'scp_tokens',true));
                if ($bal_from < $amount) {
                    return new WP_Error('no_tokens','Not enough tokens');
                }

                update_user_meta($from,'scp_tokens',$bal_from - $amount);

                $earned = intval(get_user_meta($to,'scp_earnings',true));
                update_user_meta($to,'scp_earnings',$earned + $amount);

                return ['ok'=>1,'remaining'=>$bal_from - $amount];
            }
        ]);

        // Per-minute billing
        register_rest_route('sincotechs/v1','/billing/start',[
            'methods'  => 'POST',
            'callback' => function(WP_REST_Request $r) {
                $viewer = get_current_user_id();
                $model  = intval($r['model']);
                $room   = sanitize_text_field($r['room_type']);
                $rate   = intval($r['rate_per_min']);
                if ($rate < 0) $rate = 0;

                $session_id = 'sess_'.uniqid();
                $data = [
                    'id'          => $session_id,
                    'viewer'      => $viewer,
                    'model'       => $model,
                    'room_type'   => $room,
                    'rate_per_min'=> $rate,
                    'active'      => true,
                    'started'     => time(),
                    'last_tick'   => time(),
                    'total_spent' => 0
                ];
                add_option('scp_final_session_'.$session_id, $data);
                return $data;
            }
        ]);

        register_rest_route('sincotechs/v1','/billing/tick',[
            'methods'  => 'POST',
            'callback' => function(WP_REST_Request $r) {
                $session_id = sanitize_text_field($r['session_id']);
                $opt_name   = 'scp_final_session_'.$session_id;
                $session    = get_option($opt_name);
                if (!$session || empty($session['active'])) {
                    return new WP_Error('no_session','Session not active');
                }

                $viewer = $session['viewer'];
                if ($viewer != get_current_user_id()) {
                    return new WP_Error('not_allowed','Not your session');
                }

                $rate = intval($session['rate_per_min']);
                if ($rate <= 0) {
                    $session['last_tick'] = time();
                    update_option($opt_name,$session);
                    return ['ok'=>1,'total_spent'=>$session['total_spent']];
                }

                $cost = $rate;
                $bal  = intval(get_user_meta($viewer,'scp_tokens',true));
                if ($bal < $cost) {
                    $session['active'] = false;
                    update_option($opt_name,$session);
                    return new WP_Error('no_tokens','Not enough tokens to continue');
                }

                update_user_meta($viewer,'scp_tokens',$bal - $cost);

                $earned = intval(get_user_meta($session['model'],'scp_earnings',true));
                update_user_meta($session['model'],'scp_earnings',$earned + $cost);

                $session['total_spent'] += $cost;
                $session['last_tick']    = time();
                update_option($opt_name,$session);

                return ['ok'=>1,'total_spent'=>$session['total_spent'],'remaining_tokens'=>$bal - $cost];
            }
        ]);

        register_rest_route('sincotechs/v1','/billing/end',[
            'methods'  => 'POST',
            'callback' => function(WP_REST_Request $r) {
                $session_id = sanitize_text_field($r['session_id']);
                $opt_name   = 'scp_final_session_'.$session_id;
                $session    = get_option($opt_name);
                if (!$session) return new WP_Error('no_session','Session not found');
                if ($session['viewer'] != get_current_user_id()) {
                    return new WP_Error('not_allowed','Not your session');
                }
                $session['active'] = false;
                update_option($opt_name,$session);
                return ['ok'=>1,'total_spent'=>$session['total_spent']];
            }
        ]);

        // Users
        register_rest_route('sincotechs/v1','/users',[
            'methods'=>'GET',
            'callback'=>function(){
                $users=get_users(['role__in'=>['scp_model','scp_viewer']]);
                $out=[];
                foreach($users as $u){
                    $out[]=[
                        'id'=>$u->ID,
                        'name'=>$u->user_login,
                        'role'=>implode(',', $u->roles),
                        'online'=>true
                    ];
                }
                return $out;
            }
        ]);
    }
}

$scp_final = new SCP_Cam_Platform_Final();
register_activation_hook(__FILE__, ['SCP_Cam_Platform_Final','activate']);
