<?php
/**
 * Heritage Voice — users.php
 * GET    /api/users                        Danh sách user (admin+)
 * POST   /api/users                        Tạo user mới (admin+)
 * GET    /api/users/{id}                   Chi tiết user (admin+)
 * PUT    /api/users/{id}                   Sửa role/status (admin+)
 * PUT    /api/users/{id}/password          Reset password (admin+)
 * GET    /api/users/export                 Export CSV (admin+)
 * GET    /api/users/{id}/permissions       Lấy permissions theo site
 * PUT    /api/users/{id}/permissions       Cập nhật permissions
 */

function users_list(): void {
    require_admin_role();
    $page   = int_param('page', 1, 1);
    $limit  = int_param('limit', 20, 1, 100);
    $offset = ($page - 1) * $limit;
    $role   = str_param('role');
    $status = str_param('status', 'active');
    $search = str_param('search');

    $where  = [];
    $params = [];
    if ($status !== 'all') { $where[] = 'status = :status'; $params[':status'] = $status; }
    if ($role)   { $where[] = 'role = :role';   $params[':role']   = $role; }
    if ($search) { $where[] = '(email LIKE :s OR display_name LIKE :s2)'; $params[':s'] = "%$search%"; $params[':s2'] = "%$search%"; }
    $w = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    $cs = db()->prepare("SELECT COUNT(*) FROM users $w");
    $cs->execute($params);
    $total = (int)$cs->fetchColumn();

    $stmt = db()->prepare("SELECT id,email,display_name,role,status,provider,created_at,last_seen_at FROM users $w ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->bindValue(':limit',  $limit,  PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $rows = $stmt->fetchAll();

    json_ok(['items' => $rows, 'pagination' => paginate($total, $page, $limit)]);
}

function user_detail(string $id): void {
    require_admin_role();
    $stmt = db()->prepare("SELECT id,email,display_name,role,status,provider,created_at,last_seen_at FROM users WHERE id=:id");
    $stmt->execute(array(':id' => $id));
    $u = $stmt->fetch();
    if (!$u) json_error('Không tìm thấy user', 404);

    // Thống kê
    $s1 = db()->prepare("SELECT COUNT(*) FROM listen_events WHERE user_id=:id AND event_type='complete_audio'");
    $s1->execute(array(':id' => $id));
    $u['listened'] = (int)$s1->fetchColumn();

    $s2 = db()->prepare("SELECT COUNT(*) FROM qr_scan_logs WHERE user_id=:id");
    $s2->execute(array(':id' => $id));
    $u['qr_scanned'] = (int)$s2->fetchColumn();

    json_ok($u);
}

function user_create(): void {
    require_admin_role();
    $b = body();

    $email = trim($b['email'] ?? '');
    $pass  = $b['password'] ?? '';
    $name  = trim($b['display_name'] ?? '');
    $role  = $b['role'] ?? 'member';

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) json_error('Email không hợp lệ');
    if (strlen($pass) < 6) json_error('Mật khẩu phải có ít nhất 6 ký tự');
    if (empty($name)) json_error('Vui lòng nhập họ tên');

    $allowed_roles = array('guest','member','reviewer','editor','admin','superadmin');
    if (!in_array($role, $allowed_roles)) json_error('Role không hợp lệ');
    if ($role === 'superadmin') require_superadmin();

    $ck = db()->prepare("SELECT id FROM users WHERE email=:e");
    $ck->execute(array(':e' => $email));
    if ($ck->fetch()) json_error('Email đã tồn tại', 409);

    $hash = password_hash($pass, PASSWORD_BCRYPT);
    $anon = bin2hex(random_bytes(16));

    db()->prepare("INSERT INTO users(email,display_name,provider,role,anonymous_id,status,created_at,updated_at) VALUES(:e,:n,'email',:r,:a,'active',NOW(),NOW())")->execute(array(':e'=>$email,':n'=>$name,':r'=>$role,':a'=>$anon));
    $uid = (int)db()->lastInsertId();

    db()->prepare("CREATE TABLE IF NOT EXISTS user_passwords(user_id INT UNSIGNED NOT NULL,password_hash VARCHAR(255) NOT NULL,PRIMARY KEY(user_id))ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")->execute();
    db()->prepare("INSERT INTO user_passwords(user_id,password_hash) VALUES(:u,:h) ON DUPLICATE KEY UPDATE password_hash=VALUES(password_hash)")->execute(array(':u'=>$uid,':h'=>$hash));

    json_ok(array('id'=>$uid,'email'=>$email,'display_name'=>$name,'role'=>$role), 'Tạo user thành công');
}

function user_update(string $id): void {
    require_admin_role();
    $b      = body();
    $fields = [];
    $params = array(':id' => $id);

    $allowed_roles = array('guest','member','reviewer','editor','admin','superadmin');

    if (isset($b['role'])) {
        if (!in_array($b['role'], $allowed_roles)) json_error('Role không hợp lệ');
        if ($b['role'] === 'superadmin') require_superadmin();
        $fields[] = 'role = :role';
        $params[':role'] = $b['role'];
    }
    if (isset($b['status'])) {
        if (!in_array($b['status'], array('active','inactive','banned'))) json_error('Status không hợp lệ');
        $fields[] = 'status = :status';
        $params[':status'] = $b['status'];
    }
    if (isset($b['display_name'])) {
        $fields[] = 'display_name = :name';
        $params[':name'] = trim($b['display_name']);
    }

    if (!$fields) json_error('Không có trường nào để cập nhật');
    $fields[] = 'updated_at = NOW()';
    db()->prepare("UPDATE users SET " . implode(', ', $fields) . " WHERE id=:id")->execute($params);
    json_ok(array('id' => $id), 'Cập nhật thành công');
}

function user_reset_password(string $id): void {
    require_admin_role();
    $b    = body();
    $pass = $b['password'] ?? '';
    if (strlen($pass) < 6) json_error('Mật khẩu phải có ít nhất 6 ký tự');

    $hash = password_hash($pass, PASSWORD_BCRYPT);
    db()->prepare("CREATE TABLE IF NOT EXISTS user_passwords(user_id INT UNSIGNED NOT NULL,password_hash VARCHAR(255) NOT NULL,PRIMARY KEY(user_id))ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")->execute();
    db()->prepare("INSERT INTO user_passwords(user_id,password_hash) VALUES(:u,:h) ON DUPLICATE KEY UPDATE password_hash=VALUES(password_hash)")->execute(array(':u'=>$id,':h'=>$hash));
    json_ok(array('id'=>$id), 'Đã reset mật khẩu');
}

function users_export(): void {
    require_admin_role();
    $stmt = db()->prepare("SELECT id,email,display_name,role,status,provider,created_at,last_seen_at FROM users ORDER BY created_at DESC");
    $stmt->execute();
    $rows = $stmt->fetchAll();

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="heritage-voice-users-' . date('Y-m-d') . '.csv"');
    header('Access-Control-Allow-Origin: *');

    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, array('ID','Email','Họ tên','Role','Trạng thái','Provider','Ngày tạo','Lần cuối online'));
    foreach ($rows as $r) {
        fputcsv($out, array($r['id'],$r['email'],$r['display_name'],$r['role'],$r['status'],$r['provider'],$r['created_at'],$r['last_seen_at']));
    }
    fclose($out);
    exit;
}

// ── PERMISSIONS ───────────────────────────────────────────────

function user_get_permissions(string $id): void {
    require_admin_role();
    $stmt = db()->prepare("
        SELECT p.*, hs.name AS site_name
        FROM user_site_permissions p
        LEFT JOIN heritage_sites hs ON hs.id = p.site_id
        WHERE p.user_id = :uid
        ORDER BY hs.name ASC
    ");
    $stmt->execute([':uid' => $id]);
    $rows = $stmt->fetchAll();
    foreach ($rows as &$r) {
        $r['can_edit']      = (bool)$r['can_edit'];
        $r['can_review']    = (bool)$r['can_review'];
        $r['can_create_qr'] = (bool)$r['can_create_qr'];
        $r['can_guide']     = (bool)($r['can_guide'] ?? false);
    }
    json_ok($rows);
}

function user_set_permissions(string $id): void {
    require_admin_role();
    $b       = body();
    $site_id = trim($b['site_id'] ?? '');
    $me      = require_auth();

    if (empty($site_id)) json_error('Thiếu site_id');

    // Xoá nếu không có quyền nào
    if (empty($b['can_edit']) && empty($b['can_review']) && empty($b['can_create_qr']) && empty($b['can_guide'])) {
        db()->prepare("DELETE FROM user_site_permissions WHERE user_id=:u AND site_id=:s")
            ->execute([':u' => $id, ':s' => $site_id]);
        json_ok(null, 'Đã xoá phân quyền');
    }

    db()->prepare("
        INSERT INTO user_site_permissions (user_id, site_id, can_edit, can_review, can_create_qr, can_guide, created_by)
        VALUES (:u, :s, :e, :r, :q, :g, :by)
        ON DUPLICATE KEY UPDATE
          can_edit      = VALUES(can_edit),
          can_review    = VALUES(can_review),
          can_create_qr = VALUES(can_create_qr),
          can_guide     = VALUES(can_guide)
    ")->execute([
        ':u'  => $id,
        ':s'  => $site_id,
        ':e'  => (int)!empty($b['can_edit']),
        ':r'  => (int)!empty($b['can_review']),
        ':q'  => (int)!empty($b['can_create_qr']),
        ':g'  => (int)!empty($b['can_guide']),
        ':by' => $me['id'],
    ]);

    json_ok(null, 'Đã cập nhật phân quyền');
}

function user_delete_permission(string $id): void {
    require_admin_role();
    $b       = body();
    $site_id = trim($b['site_id'] ?? '');
    if (empty($site_id)) json_error('Thiếu site_id');
    db()->prepare("DELETE FROM user_site_permissions WHERE user_id=:u AND site_id=:s")
        ->execute([':u' => $id, ':s' => $site_id]);
    json_ok(null, 'Đã xoá phân quyền');
}
