<?php

function adminStats($p = null) {
    requireAdmin();
    $total   = queryOne('SELECT COUNT(*) c FROM users WHERE role="student"')['c'];
    $active  = queryOne('SELECT COUNT(*) c FROM users WHERE role="student" AND sub_status="active"')['c'];
    $trial   = queryOne('SELECT COUNT(*) c FROM users WHERE role="student" AND sub_status="trial"')['c'];
    $expired = queryOne('SELECT COUNT(*) c FROM users WHERE role="student" AND sub_status="expired"')['c'];
    $rev     = queryOne('SELECT COALESCE(SUM(amount),0) r FROM payments WHERE status="succeeded"')['r'];
    respond([
        'users'   => ['total'=>$total,'active'=>$active,'trial'=>$trial,'expired'=>$expired],
        'revenue' => number_format($rev / 100, 2),
    ]);
}

function adminUsers($p = null) {
    requireAdmin();
    $page   = max(1, (int)($_GET['page'] ?? 1));
    $limit  = min(50, (int)($_GET['limit'] ?? 20));
    $search = $_GET['search'] ?? '';
    $status = $_GET['status'] ?? '';
    $offset = ($page - 1) * $limit;

    $where  = 'WHERE role="student"';
    $params = [];
    if ($search) {
        $where .= ' AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)';
        $s = '%'.$search.'%';
        $params = array_merge($params, [$s,$s,$s]);
    }
    if ($status) { $where .= ' AND sub_status=?'; $params[] = $status; }

    $users = query("SELECT id,name,email,phone,role,email_verified,phone_verified,sub_status,sub_plan,sub_start,sub_end,trial_used,feature_triangle,feature_energy,is_active,created_at FROM users $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset", $params);
    $total = queryOne("SELECT COUNT(*) c FROM users $where", $params)['c'];
    respond(['users'=>$users,'total'=>$total,'pages'=>ceil($total/$limit),'page'=>$page]);
}

function adminGetUser($id = null) {
    requireAdmin();
    if (!$id) error('User ID required');
    $user = queryOne('SELECT id,name,email,phone,role,email_verified,phone_verified,sub_status,sub_plan,sub_start,sub_end,trial_used,feature_triangle,feature_energy,is_active,created_at FROM users WHERE id=?', [$id]);
    if (!$user) error('User not found', 404);
    $payments = query('SELECT * FROM payments WHERE user_id=? ORDER BY created_at DESC', [$id]);
    respond(['user'=>$user,'payments'=>$payments]);
}

function adminUpdateUser($id = null) {
    requireAdmin();
    if (!$id) error('User ID required');
    $body = getBody();
    $sets = []; $vals = [];

    $fields = ['feature_triangle','feature_energy','is_active','sub_status','sub_end','sub_plan'];
    foreach ($fields as $f) {
        if (array_key_exists($f, $body)) {
            $sets[] = "$f=?";
            $vals[] = in_array($f,['feature_triangle','feature_energy','is_active']) ? (int)(bool)$body[$f] : $body[$f];
        }
    }
    if (!$sets) error('Nothing to update');
    $vals[] = $id;
    execute('UPDATE users SET ' . implode(',',$sets) . ' WHERE id=?', $vals);
    respond(['message'=>'User updated']);
}

function adminExtendSub($id = null) {
    requireAdmin();
    $days = (int)get('days', 0);
    $plan = get('plan');
    if ($days < 1) error('Days required (min 1)');

    $user = queryOne('SELECT * FROM users WHERE id=?', [$id]);
    if (!$user) error('User not found', 404);

    $base = ($user['sub_end'] && strtotime($user['sub_end']) > time()) ? strtotime($user['sub_end']) : time();
    $newEnd = date('Y-m-d H:i:s', $base + $days * 86400);

    execute('UPDATE users SET sub_status="active", sub_end=?, sub_plan=COALESCE(?,sub_plan), sub_start=COALESCE(sub_start,NOW()) WHERE id=?',
        [$newEnd, $plan, $id]);
    respond(['message' => "Extended by $days days until $newEnd"]);
}

function adminRevokeSub($id = null) {
    requireAdmin();
    execute('UPDATE users SET sub_status="cancelled", sub_end=NOW() WHERE id=?', [$id]);
    respond(['message' => 'Subscription revoked']);
}

function adminSettings($p = null) {
    requireAdmin();
    $rows = query('SELECT setting_key, setting_value FROM settings');
    $obj  = [];
    foreach ($rows as $r) $obj[$r['setting_key']] = $r['setting_value'];
    respond($obj);
}

function adminSaveSettings($p = null) {
    requireAdmin();
    $updates = getBody();
    foreach ($updates as $k => $v) {
        execute('INSERT INTO settings (setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?',
            [$k, (string)$v, (string)$v]);
    }
    respond(['message' => 'Settings updated']);
}

function adminPayments($p = null) {
    requireAdmin();
    $page   = max(1,(int)($_GET['page']??1));
    $limit  = min(50,(int)($_GET['limit']??20));
    $offset = ($page-1)*$limit;
    $payments = query("SELECT p.*,u.name,u.email,u.phone FROM payments p JOIN users u ON p.user_id=u.id ORDER BY p.created_at DESC LIMIT $limit OFFSET $offset");
    $total    = queryOne('SELECT COUNT(*) c FROM payments')['c'];
    respond(['payments'=>$payments,'total'=>$total,'pages'=>ceil($total/$limit)]);
}
